环境: win10, webpack v3.5.6, node v8.4, npm v5.3.
安装与配置
新建一个项目目录demo
, 在当前目录执行如下命令:
npm init -y
npm install --save-dev webpack
npm install --save lodash
根据如下目录结构创建文件:
demo
|- package.json
+ |- webpack.config.js
|- /dist
|- index.html
|- /src
|- index.js
新版npm会自动创建package-lock.json
dist是distribution code的缩写, 用来存放生产环境的代码.
webpack.config.js 内容如下
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
dist/index.html 内如如下
<html>
<head>
<title>Getting Started</title>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
src/index.js 内容如下
import _ from 'lodash';
function component() {
var element = document.createElement('div');
// Lodash, now imported by this script
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
return element;
}
document.body.appendChild(component());
在package.json中添加如下内容
"scripts": {
"build": "webpack"
}
测试使用
执行npm run build
, 将会在dist
目录下生成bundle.js
. 成功执行后将输出以下内容:
sheng@SHENG-LAPTOP D:\Asheng_IDE\FrontEnd\study_tree\webpack\demo
> npm run build
> demo@1.0.0 build D:\Asheng_IDE\FrontEnd\study_tree\webpack\demo
> webpack
Hash: bf97d2bdc70ce2f70877
Version: webpack 3.5.6
Time: 386ms
Asset Size Chunks Chunk Names
bundle.js 544 kB 0 [emitted] [big] main
[0] ./src/index.js 263 bytes {0} [built]
[2] (webpack)/buildin/global.js 509 bytes {0} [built]
[3] (webpack)/buildin/module.js 517 bytes {0} [built]
+ 1 hidden module
此时, 在dist
目录下的2个文件: index.html
和 bundle.js
即为打包的在生产环境中使用
的文件, 双击index.html
可直接运行.