macOS: 10.13.5
webpack: 4.12.0
两个配置文件
新手可能会搞混package.json和webpack.config.js。可以这样理解,把npm和webpack当成两个函数,package.json负责给npm传递参数,webpack.config.js负责向webpack传递参数。
基本配置
安装webpack和webpack-cli
npm install webpack webpack-cli --save-dev
创建项目并使用npm初始化,-y(yes)表示不询问,使用默认值
mkdir webpack-demo && cd webpack-demo
npm init -y
根据下面文件树创建文件夹和文件,并写入内容。+表示新增加的文件
project
webpack-demo
|- package.json
+ |- index.html
+ |- /src
+ |- index.js
Lodash是一个“工具函数集”,它实现了一些常用的功能,如实现循环、遍历数组、生成随机数等等,它把这些功能抽象成函数,集合在一起。可以把它当成一个工具箱。
src/index.js
function component() {
//使用Lodash, _表示loadsh,_.joint()表示调用loadsh的joint函数。是否想到了jQuery的$。这里,Lodash由index.html文件引入。
let element = doucment.createElement('div');
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
return element;
}
document.body.appendChild(component());
<!doctype html>
<html>
<head>
<title>Getting Started</title>
<script src="https://unpkg.com/lodash@4.16.6"></script>
</head>
<body>
<script src="./src/index.js"></script>
</body>
</html>
修改package.json,将项目(package)改为私有的,避免不小心把代码发布出去。-表示删除 。package.json是npm的配置文件,可以参考npm官方文档
package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
+ "private": true,
- "main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.0.1",
"webpack-cli": "^2.0.9"
},
"dependencies": {}
}
上面的例子有一个暗含的依赖关系,在index.html中,index.js是在引用“lodash@4.16.6”后调用的。因为index.js使用了lodash,不先引用lodash程序无法正常执行。这种依赖关系有明显的缺点:
- 不清楚index.js需要引用其他的库(library),我们并不清楚index.js中使用的“_”变量是需要引用外部库的。
- 如果我们在index.html忘了引用lodash,或者index.js先于lodash引用,程序都无法正常执行。
- 我们在html文件中引入了外部库,即便没有使用它,浏览器依然会强制将其下载。
上面这些缺点webpack都能解决。首先,将整个项目根据下面的文件树进行修改
project
webpack-demo
|- package.json
+ |- /dist
+ |- index.html
- |- index.html
|- /src
|- index.js
如上所示,我们将“源码”(source)和“发布代码”(distribution)进行分离,把index.html移入dist文件夹。源码由我们创建、编辑和修改,“发布代码”是经过webpack借由各种组件压缩、优化过后,可供发布,最终在浏览器加载的代码。
下面我们来解决index.js与lodash的依赖关系,将lodash与index.js打包在一起,让webpack这个打包器名副其实。把lodash下载到本地
npm install --save lodash
下载后,如果lodash没有被使用,那么它是不会被打包到最终的“发布代码”的。webpack还有按需引用的能力,一些被引用的库,如果只有部分代码被使用,那么只有这部分代码会被打包。打包在一起的资源还可以进一步地压缩和优化。
src/index.js
+ import _ from 'lodash';
+
function component() {
var element = document.createElement('div');
// Lodash, 不在html 文件引入,由js文件引入
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
return element;
}
document.body.appendChild(component());
更新index.html,不再由它引入Lodash
<!doctype html>
<html>
<head>
<title>Getting Started</title>
- <script src="https://unpkg.com/lodash@4.16.6"></script>
</head>
<body>
- <script src="./src/index.js"></script>
+ <script src="main.js"></script>
</body>
</html>
上面的一番操作,很明确地引入了lodash,而且把它绑定到了_。这样避免了“全域污染”(no global scope pollution)。根据这样的设置,webpack能构建出依赖图(dependency graph),由此图,将项目资源进行打包,优化,而且会明确代码的执行顺序。
终于来到激动人心的一步,在终端执行npx webpack
。npx是新版本npm附带的工具,它会帮你方便地执行依赖包。没有npx前,查看webpack的版本号,需要执行./node_modules/.bin/webpack -v
,现在一行npx webpack -v
搞定。 npx 会自动查找你想执行的依赖包中的可执行文件,如果找不到,就会去 PATH 里找。如果依然找不到,就会帮你安装。
npx webpack
Hash: c2831644d36e1f21c8c3
Version: webpack 4.12.0
Time: 3169ms
Built at: 06/10/2018 9:05:35 PM
Asset Size Chunks Chunk Names
main.js 70.4 KiB 0 [emitted] main
[1] (webpack)/buildin/module.js 497 bytes {0} [built]
[2] (webpack)/buildin/global.js 489 bytes {0} [built]
[3] ./src/index.js 218 bytes {0} [built]
+ 1 hidden module
WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/
在浏览器打开index.html。没有意外的话,'Hello webpack' 就显示在你面前。
使用配置文件
webpack4后是可以不用配置文件的,但是复杂的项目还是离不开它的。设置一个配置文件,总比在命令行输入各种指令要方便、高效得多。
在根目录创建webpack.config.js
project
webpack-demo
|- package.json
+ |- webpack.config.js
|- /dist
|- index.html
|- /src
|- index.js
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
执行构建指令,这次给它指定配置文件
npx webpack --config webpack.config.js
Hash: 39ac053a4c4975e616af
Version: webpack 4.12.0
Time: 3039ms
Built at: 06/10/2018 9:42:17 PM
Asset Size Chunks Chunk Names
bundle.js 70.4 KiB 0 [emitted] main
[1] (webpack)/buildin/module.js 497 bytes {0} [built]
[2] (webpack)/buildin/global.js 489 bytes {0} [built]
[3] ./src/index.js 218 bytes {0} [built]
+ 1 hidden module
WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/
配置文件当然不止这点功能,详见 文档。
执行webpack,它会自己查找是否有个叫webpack.config.js的文件,有就把它用起来。上面使用“--config”是为了说明可以为webpack指定配置文件,至于配置文件叫啥,随你便。
利用package.json
package.json为执行npm提供配置信息。借助它可以避免在终端搞一大堆指令。修改package.json如下
package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
+ "build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.0.1",
"webpack-cli": "^2.0.9",
"lodash": "^4.17.5"
}
}
执行npm run build
,等价于之前的npx webpack
。
npm run build
> webpack-demo@1.0.0 build /Users/Roy/Downloads/webpack-test/webpack-demo
> webpack
Hash: 39ac053a4c4975e616af
Version: webpack 4.12.0
Time: 407ms
Built at: 06/10/2018 10:06:42 PM
Asset Size Chunks Chunk Names
bundle.js 70.4 KiB 0 [emitted] main
[1] (webpack)/buildin/module.js 497 bytes {0} [built]
[2] (webpack)/buildin/global.js 489 bytes {0} [built]
[3] ./src/index.js 218 bytes {0} [built]
+ 1 hidden module
WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/
npm run build
顶替了前面的npx
,你可以在pack.json的“webpack”后添加前面用的--config参数:
"build": "webpack --config webpack.config.js"
结论
至此,项目的结构如下:
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
+ "build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.0.1",
"webpack-cli": "^2.0.9",
"lodash": "^4.17.5"
}
}