环境需求
- 安装node.js(包括npm)
项目结构
假设基本项目结构如下
my-project
├── package.json
├── index.html
├── src
│ └── index.js
└── .gitignore
安装webpack
npm install webpack webpack-cli -D
-D 将其保存到 package.json 中的devDependencies中
然后在package.json中添加如下配置
// package.json
"scripts": {
"build": "webpack --config webpack.config.js"
}
创建webpack配置文件
Webpack 依赖于一个管理其所有设置的配置文件:webpack.config.js
// webpack.config.js
const path = require(‘path‘);
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
- entry为打包入口文件src/index.js
- output.filename为输出bundle的名称
- output.path将打包后的文件放入文件夹dist中
- path.resolve获取绝对路径
启用生产模式
要启用生产模式,只需要设置mode选项,生产模式下打包会删除死代码
// webpack.config.js
const path = require(‘path‘);
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
- },
+ },
+ mode: 'production',
};
自动清理打包文件
安装clean-webpack-plugin
npm install --save-dev clean-webpack-plugin
// webpack.config.js
const path = require('path');
+ const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
//...
plugins: [
+ new CleanWebpackPlugin(),
],
};
处理CSS和图片
npm install --save-dev style-loader css-loader file-loader
// webpack.config.js
const path = require('path');
+ const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// ...
module: {
rules: [
+ {
+ test: /\.css$/,
+ use: [MiniCssExtractPlugin.loader, 'css-loader'],
+ },
+ {
+ test: /\.(png|jpg|gif|woff|woff2|eot|ttf|otf)$/,
+ use: 'file-loader',
+ }
]
},
plugins: [
+ new MiniCssExtractPlugin(),
new CleanWebpackPlugin(),
]
};
配置开发服务器
npm install --save-dev webpack-dev-server
// webpack.config.js
module.exports = {
//...
+ devServer: {
+ static: './dist',
+ open: true
+ },
plugins: [...],
};
更改package.json里的控制台命令
"scripts": {
- "build": "webpack ..."
+ "build": "webpack ...",
+ "dev": "webpack serve"
},