Webpack学习笔记(四):管理输出

Webpack学习笔记(四):管理输出


目的

避免在index.html中手动引入所有资源,使用插件进行管理,而不是继续手动管理

分离入口

代码继承自Webpack学习笔记(三):管理资源
1.项目中添加新的js文件,作为打包的入口

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

2.修改webpack.config.js,将打包入口分离

const path = require('path');
  module.exports = {
-   entry: './src/index.js',
+   entry: {
+     app: './src/index.js',
+     print: './src/print.js'
+   },
    output: {
-     filename: 'bundle.js',
+     filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };

3.修改index.html,为 webpack 分离入口做好准备

  <!doctype html>
  <html>
    <head>
-     <title>管理资源</title>
+     <title>管理输出</title>
+     <script src="./print.bundle.js"></script>
    </head>
    <body>
-     <script src="./bundle.js"></script>
+     <script src="./app.bundle.js"></script>
    </body>
  </html>

设置 HtmlWebpackPlugin

上面的代码中存在一个问题, 如果我们更改了我们的一个入口起点的名称,甚至添加了一个新的入口,会在构建时重新命名生成的 bundle,但是我们的 index.html 文件仍然引用旧的名称.

这就会导致index.html无法引入我们新生成的js,为了解决这个问题,我们可以使用HtmlWebpackPlugin插件

HtmlWebpackPlugin简化了HTML文件的创建,以便为webpack包提供服务.这对于在文件名中包含每次会随着编译而发生变化哈希的 webpack bundle 尤其有用. 可以让插件为你生成一个HTML文件,使用lodash模板提供自己的模板,或使用自己的loader

  const path = require('path');
+ const HtmlWebpackPlugin = require('html-webpack-plugin');

  module.exports = {
    entry: {
      app: './src/index.js',
      print: './src/print.js'
    },
+   plugins: [
+     new HtmlWebpackPlugin({
+       title: '管理输出'
+     })
+   ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };

clean-webpack-plugin

clean-webpack-plugin是一个流行的清理插件,它可以在每次运行打包命令时清空/dist文件夹,避免将上次打包遗留的文件和新生成的文件混杂在一起

  const path = require('path');
  const HtmlWebpackPlugin = require('html-webpack-plugin');
  // 注意在新版本的webpack里面要这么引入
+ const { CleanWebpackPlugin } = require('clean-webpack-plugin'); // 正确引入方式
  // const CleanWebpackPlugin = require('clean-webpack-plugin'); // 错误引入方式
  module.exports = {
    entry: {
      app: './src/index.js',
      print: './src/print.js'
    },
    plugins: [
+     new CleanWebpackPlugin(),
      new HtmlWebpackPlugin({
        title: '管理输出'
      })
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };

参考链接

  1. webpack管理资源
  2. 代码地址
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值