本项目基于 webpack@3.0 版本
- 项目 github
- 快速开发项目的 webpack 脚手架
目录
- 安装与基础配置
- 常用插件
- 常用加载器
- 优化结构与配置
安装与基础配置
1. 安装 webpack
# 全局中安装 - (需要使用 webpack 命令)
$ cnpm install -g webpack@3.*
# 项目中安装
$ cnpm install --save-dev webpack@3.*
cnpm 为使用淘宝的镜像。使用命令
$ npm install -g cnpm --registry=https://registry.npm.taobao.org
即可安装~
2. 新建入口文件
// ./index.js
alert('Hello world!');
3. 新建配置文件
// ./webpack.config.js
module.exports = {
// 入口文件
entry: __dirname + '/index.js',
// 开发模式记录错误信息
devtool: 'inline-source-map',
// 输出文件
output: {
path: __dirname + '/dist',
filename: 'bundle-[hash].js'
}
};
4. 运行测试
$ webpack
Hash: 7ac8e5097f8728f373f3
Version: webpack 3.10.0
Time: 83ms
Asset Size Chunks Chunk Names
bundle-7ac8e5097f8728f373f3.js 2.5 kB 0 [emitted] main
[0] ./index.js 22 bytes {0} [built]
常用插件
1. 自动清理打包目录的插件
$ cnpm install --save-dev clean-webpack-plugin
// ./webpack.config.js
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
...
// 加载模块
plugins: [
new CleanWebpackPlugin(['dist'])
]
};
2. 自动生成模板插件
$ cnpm install --save-dev html-webpack-plugin
// ./webpack.config.js
...
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
...
// 加载模块
plugins: [
...
new HtmlWebpackPlugin()
]
};
3. 新建入口默认模板
// ./index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Webpack App</title>
</head>
<body>
</body>
</html>
// ./webpack.config.js
new HtmlWebpackPlugin({
filename: 'index.html',
// 使用默认模版
template: __dirname + '/index.html'
})
4. webpack 开发服务器
$ cnpm install --save-dev webpack-dev-server webpack-cli
// ./webpack.config.js
...
module.exports = {
...
devServer: {
// 服务器文件路径
contentBase: './dist',
// 不跳转url
historyApiFallback: true,
// inline模式url不用变化
inline: ture,
// 热更新
hot: true,
// 开启GZIP
compress: true,
}
...
}
// 增加 start 命令
// ./package.json
"scripts": {
...
"start": "webpack-dev-server --open"
}
webpack4.0 之后依赖 webpack-cli。
5. 运行测试
$ npm start
// 浏览器弹出‘Hello world!’测试成功
6. 整理项目目录
新建 app 文件夹,将
index.js
,index.html
整理在里面,修改webpack.config.js
:
// ./webpack.config.js
const HtmlWebpa