webpack基础-管理输出

42 阅读1分钟

管理输出

project结构:

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

dist/index.html

 <!DOCTYPE html>
 <html>
   <head>
     <meta charset="utf-8" />
-    <title>管理资源</title>
+    <title>管理输出</title>
+    <script src="./print.bundle.js"></script>
   </head>
   <body>
-    <script src="bundle.js"></script>
+    <script src="./index.bundle.js"></script>
   </body>
 </html>

接下来在 entry 添加 src/print.js 作为新的入口起点(命名为 print),然后修改 output 使得能够根据入口起点定义的名称动态生成 bundle 名称:

webpack.config.js

 const path = require('path');

 module.exports = {
-  entry: './src/index.js',
+  entry: {
+    index: './src/index.js',
+    print: './src/print.js',
+  },
   output: {
-    filename: 'bundle.js',
+    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'),
   },
 };

HtmlWebpackPlugin 插件仍然会默认生成 index.html 文件,即使用新生成的 index.html` 文件替换原有文件。

参阅 HtmlWebpackPlugin 仓库源码以了解 HtmlWebpackPlugin 插件提供的全部功能。

清理 /dist 文件夹

通常比较推荐的做法是在每次构建前清理 /dist 文件夹,那么构建后就只会存在将要用到的文件。可以使用 output.clean 配置选项实现这个需求。

   output: {
     filename: '[name].bundle.js',
     path: path.resolve(__dirname, 'dist'),
+    clean: true,
   },

manifest

你可能会对 webpack 和 webpack 插件似乎“知道”应该生成哪些文件感兴趣。webpack 通过 manifest 追踪所有模块到输出的 bundle 之间的映射。了解 manifest 将会帮助了解如何以其他方式控制 webpack 输出

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