node: 14.17.0 webpack: 5^
初始化项目
yarn inityarn add webpack webpack-cli html-webpack-plugin -D
创建基础文件
|--webpack-demo|--/node_modules|--/public|--index.html|--/src|--index.js|--package.json|--webpack.config.js|--yarn.lock
webpack文件基础配置
const HtmlWebpackPlugin = require('html-webpack-plugin');module.exports = {mode: 'development',entry: './src/index.js',devtool: 'inline-source-map', // 定位报错位置output: {filename: '[name].chunk.js',path: `${__dirname}/dist`,clean: true,},plugins: [new HtmlWebpackPlugin({ template: './public/index.html' })]}
构建开发环境
webpack watch 观察模式
webpack会watch依赖图中所有文件的更改并自动重新编译,但需要手动刷新浏览器
yarn run webpack --watch
webpack-dev-server
安装依赖
yarn add webpack-dev-server -D
webpack-dev-server提供了一个基本的web server,且具有live reloading功能
修改webpack.config.js
...
module.exports = {
...
devServer: {
static: './dist'
},
...
}
static:'./dist'告知dev-server将dist目录下文件作为server可访问资源serve到localhost:8080下
此时运行yarn webpack server可以看到输出信息如下:[webpack-dev-server] Content not from webpack is served from './dist' directory
如不设置static则输出信息如下:[webpack-dev-server] Content not from webpack is served from 'your/project/root/path/public' directory
:::warning
dev-server在编译后不会输出文件到dist目录,而是将bundle文件保存在内存中
:::
webpack-dev-middleware
webpack-dev-middleware是一个封装器,webpack-dev-server就是使用的它。它将webpack处理过的文件发送到一个server下,以下为webpack-dev-middleware配合express使用。
安装依赖
yarn add express webpack-dev-middleware -D
修改配置文件
...
module.exports = {
...
output: {
...
publicPath: '/'
}
...
}
添加server启动文件
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-dev-middleware,
// 以及将 webpack.config.js 配置文件作为基础配置。
app.use(
webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath,
})
);
// 将文件 serve 到 port 3000。
app.listen(3000, function () {
console.log('Example app listening on port 3000!\n');
});
使用node server.js启动服务
