webpack指南(管理输出、开发环境)

管理输出

随着应用程序的不断增长,开始 使用哈希值进行文件命名 并输出 多个 bundle

预先准备

project

复制代码
 webpack-demo
  |- package.json
  |- package-lock.json
  |- webpack.config.js
  |- /dist
  |- /src
    |- index.js
 +  |- print.js
  |- /node_modules
复制代码

在 src/print.js 文件中添加一些逻辑:

src/print.js

export default function printMe() {
  console.log('I get called from print.js!');
}
复制代码
const path = require('path');

 module.exports = {
  entry: {
    index: './src/index.js',
    print: './src/print.js',
  },
   output: {
    filename: '[name].bundle.js',
     path: path.resolve(__dirname, 'dist'),
   },
 };
复制代码

设置 HtmlWebpackPlugin

安装插件并且调整 webpack.config.js 文件:

npm install --save-dev html-webpack-plugin

webpack.config.js

复制代码
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

 module.exports = {
   entry: {
     index: './src/index.js',
     print: './src/print.js',
   },
  plugins: [
    new HtmlWebpackPlugin({
      title: '管理输出',
    }),
  ],
   output: {
     filename: '[name].bundle.js',
     path: path.resolve(__dirname, 'dist'),
   
clean: true, // 重新打包时,先清理dist文件夹
}, };
复制代码

执行npm run build打包,会生成index.html覆盖原来的文件

清理 /dist 文件夹

output.clean来配置

manifest

webpack 通过 manifest 追踪所有模块到输出的 bundle 之间的映射。

WebpackManifestPlugin 插件可以将 manifest 数据提取为 json 文件。

复制代码
const { WebpackManifestPlugin } = require('webpack-manifest-plugin');
module.exports = {
   entry: {
     index: './src/index.js',
     print: './src/print.js',
   },
  plugins: [
    new HtmlWebpackPlugin({
      title: '管理输出',
    }),
    new WebpackManifestPlugin()
  ],
   output: {
     filename: '[name].bundle.js',
     path: path.resolve(__dirname, 'dist'),
   },
 };
复制代码

输出manifest.json

{
  "index.js": "auto/index.bundle.js",
  "print.js": "auto/print.bundle.js",
  "index.html": "auto/index.html"
}

开发环境

 设置开发环境:mode 设置为 'development'

webpack.config.js

 
复制代码
const path = require('path');
 const HtmlWebpackPlugin = require('html-webpack-plugin');

 module.exports = {
   mode: 'development',
   entry: {
     index: './src/index.js',
     print: './src/print.js',
   },
   plugins: [
     new HtmlWebpackPlugin({
      title: 'Development',
     }),
   ],
 };
复制代码

使用 source map

复制代码
const path = require('path');
 const HtmlWebpackPlugin = require('html-webpack-plugin');

 module.exports = {
   mode: 'development',
   entry: {
     index: './src/index.js',
   print: './src/print.js' }, devtool:
'inline-source-map',  // 此设置必须mode为development时才起作用 plugins: [ new HtmlWebpackPlugin({ title: 'Development', }), ], };
复制代码

有source-map后,能在控制台看到源代码。可以查看错误,如下:

 

选择一个开发工具

每次编译代码都需要手动运行 npm run build 会显得很麻烦

webpack 提供了几种可选方式帮助在代码发生变化后自动编译代码:

  1. webpack 的 观察模式
  2. webpack-dev-server
  3. webpack-dev-middleware

在多数场景中可能会使用 webpack-dev-server

使用观察模式

 可以指示 webpack “观察”依赖图中所有文件的更改。如果其中一个文件被更新,代码将被自动重新编译,所以不必再去手动运行整个构建。

package.json

 
复制代码
{
   "name": "webpack-demo","private": true,
   "scripts": {
     "test": "echo \"Error: no test specified\" && exit 1",
    "watch": "webpack --watch",  // 观察模块
     "build": "webpack"
   },"devDependencies": {
     "html-webpack-plugin": "^4.5.0",
     "webpack": "^5.4.0",
     "webpack-cli": "^4.2.0"
   },
   "dependencies": {
     "lodash": "^4.17.20"
   }
 }
复制代码

观察模式唯一的缺点是需要手动刷新浏览器才能看到修改后的实际效果。实现 webpack-dev-server 将能够自动刷新浏览器!

使用 webpack-dev-server

webpack-dev-server 提供了一个能够实时重新加载的基本的 web server。安装依赖如下:

npm install --save-dev webpack-dev-server

webpack.config.js

 
复制代码
const path = require('path');
 const HtmlWebpackPlugin = require('html-webpack-plugin');

 module.exports = {
   mode: 'development',
   entry: {
     index: './src/index.js',
     print: './src/print.js',
   },
   devtool: 'inline-source-map',
  devServer: {
    static: './dist',
  },
   plugins: [
     new HtmlWebpackPlugin({
       title: 'Development',
     }),
   ],
   output: {
     filename: '[name].bundle.js',
     path: path.resolve(__dirname, 'dist'),
     clean: true,
   },
  optimization: {
    runtimeChunk: 'single',
  },
 };
复制代码

以上配置告知 webpack-dev-server 将 dist 目录下的文件作为可访问资源部署在 localhost:8080

在package.json中添加一个命令:

"scripts": {
     "test": "echo \"Error: no test specified\" && exit 1",
     "watch": "webpack --watch",
+    "start": "webpack serve --open",
     "build": "webpack"
   },

npm run start运行起来后,浏览器中 http://localhost:8080/ 访问页面

webpack-dev-server 具有许多可配置的选项。参阅 配置文档 以了解更多配置选项。

使用 webpack-dev-middleware

 webpack-dev-middleware 是一个包装器,它可以把 webpack 处理过的文件发送到 server。这是 webpack-dev-server 内部的原理,但是它也可以作为一个单独的包使用,以便根据需求进行更多自定义设置。
下面是一个 webpack-dev-middleware 配合 express server 的示例。
npm install --save-dev express webpack-dev-middleware

webpack.config.js

 
复制代码
const path = require('path');
 const HtmlWebpackPlugin = require('html-webpack-plugin');

 module.exports = {
   mode: 'development',
   entry: {
     index: './src/index.js',
     print: './src/print.js',
   },
   devtool: 'inline-source-map',
   devServer: {
     static: './dist',
   },
   plugins: [
     new HtmlWebpackPlugin({
       title: 'Development',
     }),
   ],
   output: {
     filename: '[name].bundle.js',
     path: path.resolve(__dirname, 'dist'),
     clean: true,
    publicPath: '/',
   },
 };
复制代码

project

复制代码
  webpack-demo
  |- package.json
  |- package-lock.json
  |- webpack.config.js
 |- server.js
  |- /dist
  |- /src
    |- index.js
    |- print.js
  |- /node_modules
复制代码

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-dev-middleware,
// 以及将 webpack.config.js 配置文件作为基础配置。webpackDevMiddleware是一个包装器,将webpack处理过的文件发送到server
app.use(
  webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath,
  })
);

// 将文件 serve 到 port 3000。
app.listen(3000, function () {
  console.log('Example app listening on port 3000!\n');
});
复制代码

package.json

 
复制代码
 {
   "name": "webpack-demo",
   "version": "1.0.0",
   "description": "",
   "private": true,
   "scripts": {
     "test": "echo \"Error: no test specified\" && exit 1",
     "watch": "webpack --watch",
     "start": "webpack serve --open",
    "server": "node server.js",
     "build": "webpack"
   },
   "keywords": [],
   "author": "",
   "license": "ISC",
   "devDependencies": {
     "express": "^4.17.1",
     "html-webpack-plugin": "^4.5.0",
     "webpack": "^5.4.0",
     "webpack-cli": "^4.2.0",
     "webpack-dev-middleware": "^4.0.2",
     "webpack-dev-server": "^3.11.0"
   },
   "dependencies": {
     "lodash": "^4.17.20"
   }
 }
复制代码

 

posted @   心意12  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示