node: 14.17.0 webpack: 5^

初始化项目

  1. yarn init
  2. yarn add webpack webpack-cli html-webpack-plugin -D

创建基础文件

  1. |--webpack-demo
  2. |--/node_modules
  3. |--/public
  4. |--index.html
  5. |--/src
  6. |--index.js
  7. |--package.json
  8. |--webpack.config.js
  9. |--yarn.lock

webpack文件基础配置

  1. const HtmlWebpackPlugin = require('html-webpack-plugin');
  2. module.exports = {
  3. mode: 'development',
  4. entry: './src/index.js',
  5. devtool: 'inline-source-map', // 定位报错位置
  6. output: {
  7. filename: '[name].chunk.js',
  8. path: `${__dirname}/dist`,
  9. clean: true,
  10. },
  11. plugins: [new HtmlWebpackPlugin({ template: './public/index.html' })]
  12. }

构建开发环境

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启动服务