0.安装与初始化
- 初始化项目:
npm init 配置选择默认即可,生成package.json文件
- 安装webpack:
npm install --save-dev webpack webpack-cli
1. 转译JS
- 随意编写一个js文件
- 编写配置文件,
webpack.config.js
const path = require('path')
module.exports = {
entry: path.resolve(__dirname, './src/index.js'),
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist')
}
}
-
添加编译命令
"scripts": { "build": "webpack --config ./webpack.config.js",} -
执行命令
npm run build -
文件名哈希
filename: "index.[contenthash].js"
在配置出口文件时通过设置哈希值防止文件覆盖,配合HTTP缓存使用
2. 自动生成HTML
单页面
- 安装插件
npm install --save-dev html-webpack-plugin - 引入插件并配置
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: path.resolve(__dirname, './src/index.js'),
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new HtmlWebpackPlugin({
title: '首页'
})
]
}
2.运行
npm run build
多页面
-
创建所有需要使用的页面html文件
-
修改配置
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: path.resolve(__dirname, './src/index.js'),
output: {
filename: 'main.[contenthash].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, "src/assets/index.html"),
filename: 'index.html',
chunks: ['index'] // 与入口文件对应的模块名(entry 配置),这里可以理解为引入 main.js
}),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'src/assets/header.html'),
filename: 'header.html',
chunks: ['header'] // 添加 chunks
}),
]
}
清理dist目录
- 版本相对较新,5.20.或者近期版本
output: {
// ...
clean: true, // 在生成文件之前清空 output 目录
},
- 相对老的版本
"build": "rm -rf dist && webpack",
"build": "rimraf dist && webpack",
两种命令起到相同效果,前一种对win10兼容性一般,后者需要安装额外的包
- 依靠插件 搜索插件并安装
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
...
plugins: [
...
new CleanWebpackPlugin(),
]
}
webpack-dev-server
webpack-dev-server 是一个开发服务器,可以实现 HMR(模块热替换),所谓的 MHR 就是它把构建出来的文件保存到运行内存中,确保运行速度,每当你的开发代码发生改变时,立刻重新构建一遍到内存中,且通知浏览器更新页面内容。
- 安装
npm i -D webpack-dev-server
- 配置 webpack.config.js
module.exports = {
...
devServer: {
port: 3000,
hot: true,
static: './dist' // 旧版使用contentBase
},
}
{
...
"scripts": {
"dev": "webpack-dev-server --config webpack.config.js --open",
...
},
...
}
运行命令 npm run dev