每次编译代码时,需要手动输入yarn run build,挺麻烦的,有没有自动编译的方式呢?还真有,如下三种:
在package.json中添加观察模式的npm script脚本
"scripts": {
"watch": "webpack --watch",
"build": "webpack"
}
启动:yarn run watch
优点:自动编译
缺点:需手动刷新浏览器
添加web服务器插件
yarn add webpack-dev-server -D
在package.json中添加web服务器的npm script脚本
"scripts": {
"watch": "webpack --watch",
"build": "webpack",
"dev": "webpack-dev-server --open"
}
在webpack.config.js配置文件中添加devServer配置项
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const ManifestPlugin = require('webpack-manifest-plugin')
const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
module.exports = {
// 多入口,根据入口起点名称动态生成bundle名称
entry: {
app: './src/index.js',
print: './src/print.js'
},
// 开发服务器,实时重新加载
devServer: {
contentBase: './dist'
},
plugins: [
// 每次构建前清理dist文件夹
new CleanWebpackPlugin(['dist']),
// html-webpack-plugin插件默认生成index.html文件
new HtmlWebpackPlugin({
title: 'Document'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
}
启动:yarn run dev
优点:自动编译+实时重新加载浏览器
添加webpack中间件和express
yarn add express webpack-dev-middleware -D
在package.json中添加web服务器的npm script脚本
"scripts": {
"watch": "webpack --watch",
"build": "webpack",
"dev": "webpack-dev-server --open",
"server": "node server.js"
}
webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const ManifestPlugin = require('webpack-manifest-plugin')
const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
module.exports = {
// 多入口,根据入口起点名称动态生成bundle名称
entry: {
app: './src/index.js',
print: './src/print.js'
},
plugins: [
// 每次构建前清理dist文件夹
new CleanWebpackPlugin(['dist']),
// html-webpack-plugin插件默认生成index.html文件
new HtmlWebpackPlugin({
title: 'Output Management'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
// 输出解析文件的目录
publicPath: '/'
}
}
server.js 启动服务器
const express = require('express')
const webpack = require('webpack')
const webpackDevMiddleware = require('webpack-dev-middleware')
const app = express()
const config = require('./webpack.config.js')
const compiler = webpack(config)
// 告诉express使用webpack中间件和webpack配置文件
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
}))
app.listen(8080, () => {
console.log('listening on port 8080\n')
})
启动:yarn run server
优点:自动编译
缺点:需手动刷新浏览器+配置文件和插件多