前言:
webpack4.x,单独配置webpack-dev-server、html-webpack-plugin写的小demo。提前给出demo涉及的环境以及包版本信息:
- node v10.14.2
- npm v6.4.1
- webpack v4.46.0
- webpack-dev-server v3.11.2
- html-webpack-plugin v4.5.1
- 文件预览
demo:.
│ package-lock.json
│ package.json
│ webpack.config.js
└─src
│ index.html
│ index.js
├─css
├─imgs
└─js
从零开始配置(node的安装已经环境变量配置这里不做赘述)
1.新建如下文件结构
demo:.
│ webpack.config.js
└─src
│ index.html
│ index.js
├─css
├─imgs
└─js
webpack.config.js内容:
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './dist'),
},
}
2.执行npm init
- 全部默认值即可
- 该命令会自动生成package.json 和 package-lock.json文件
- 在package.json中scripts属性下增加:
"build": "webpack", "dev": "webpack-dev-server"
3.安装webpack、 webpack-dev-server及配置
npm install webpack@4 webpack-dev-server@3 --save-dev
- 假如已经全局安装了webpack,避免不必要的问题(版本号存在差异),也需安装执行以上命令进行安装
- webpack-dev-server是webpack官方提供的一个小型Express服务器
- 安装完成,package.json中的devDependencies属性为
"devDependencies": { "webpack": "^4.46.0", "webpack-dev-server": "^3.11.2" }
- webpack.config.js中配置webpack-dev-server内容如下
const path = require('path');
const webpack = require('webpack');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './dist'),
},
plugins: [
new webpack.HotModuleReplacementPlugin(), // 本身自带自动刷新的功能,但是配置上可以局部热更新
],
devServer: {
contentBase: 'src', // 指定托管的文件夹,不指定会自动默认打开当前所在的目录文件,且,假如该文件下,没有index.html文件即使设置open:true;也无效
port: 1200, // 端口号
open: true, // 自动打开浏览器
hot: true, // 启动热更新 - 配合上面HotModuleReplacementPlugin插件使用
}
}
说明:即使我们不做HotModuleReplacementPlugin;hot:true的配置,更改文件时也会自动刷新。
4.安装html-webpack-plugin及配置
npm install html-webpack-plugin@4 --save-dev
- 该插件会在内存中自动生成一个index.html文件,且将打包的JS文件自动通过script插入到文件中
- 安装完成,package.json中的devDependencies属性为
"devDependencies": { "html-webpack-plugin": "^4.5.1", "webpack": "^4.46.0", "webpack-dev-server": "^3.11.2" }
- 配置简述及最终呈现
- 引入该插件
const HtmlWebpackPlugin = require('html-webpack-plugin'); // html文件处理插件
- plugins中增加如下配置
new HtmlWebpackPlugin({ template: path.resolve(__dirname, './src/index.html'), // 模板的路径 filename: 'index.html', // 生成的文件名 }),
- webpack.config.js最终展示:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin'); // html文件处理插件
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './dist'),
},
plugins: [
new webpack.HotModuleReplacementPlugin(), // 本身自带自动刷新的功能,但是配置上可以局部热更新
new HtmlWebpackPlugin({
template: path.resolve(__dirname, './src/index.html'), // 模板的路径
filename: 'index.html', // 生成的文件名
}),
],
devServer: {
contentBase: 'src', // 指定托管的文件夹,不指定会自动默认打开当前所在的目录文件,且,假如该文件下,没有index.html文件即使设置open:true;也无效
port: 1200, // 端口号
open: true, // 自动打开浏览器
hot: true, // 启动热更新 - 配合上面HotModuleReplacementPlugin插件使用
}
}
5.至此一个可通过服务器打开且可自动热更新刷新的demo落幕完成。
npm run dev
执行以上命令即可进行预览。