webpack5(四)plugin的使用

插件是 webpack 的 支柱 功能。webpack 自身也是构建于你在 webpack 配置中用到的相同的插件系统之上!

插件目的在于解决 loader 无法实现的其他事。

clean-webpack-plugin

每次打包自动帮我们先删除原来的包文件夹

  1. 下载

npm install clean-webpack-plugin -D

  1. 配置使用
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

module.exports = {
  ...
  plugins: [
    new CleanWebpackPlugin()
  ]
}
复制代码

现在我们在每次通过webpack构建打包前就不用手动删除包了

html-webpack-plugin

该插件将为你生成一个 HTML5 文件, 在 body 中使用 script 标签引入你所有 webpack 生成的 bundle

  1. 下载

npm install html-webpack-plugin -D

  1. 配置使用
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  ...
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin()
  ]
}
复制代码

自定义html模板

插件默认模板

image.png

模仿Vue中使用自定义模板

node_modules@vue\cli-service\generator\template\public\index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%%= BASE_URL %%>favicon.ico">
    <title><%%= htmlWebpackPlugin.options.title %%></title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%%= htmlWebpackPlugin.options.title %%> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

复制代码

配置使用自定义模板,传入title

plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: 'hello webpack', // 模板中通过ejs解析这里的title
      template: './public/index.html'
    })
  ]
复制代码

编译中发现报错,因为模板中使用了全局变量BASE_URL,而我们没有定义
image.png

difine-plugin

webpack内置插件。允许在 编译时 创建配置的全局常量,这在需要区分开发模式与生产模式进行不同的操作时非常有用。解决上述报错

const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')

plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: 'hello webpack', // 模板中通过ejs解析这里的title
      template: './public/index.html'
    }),
    new webpack.DefinePlugin({
      BASE_URL: '"./"' // 传入path需加引号,否则内部解析为变量报错
    })
  ]
复制代码

构建编译成功

image.png

但是模板中引入的favicon.ico没有打包,需要通过copy-webpack-plugin实现

copy-webpack-plugin

将已存在的单个文件或整个目录复制到生成目录。

  1. 下载

npm insstall copy-webpack-plugin -D

  1. 配置使用
const CopyWebpackPlugin = require('copy-webpack-plugin')

plugins: [
    new CopyWebpackPlugin({
      patterns: [
        {
          from: 'public',
          globOptions: {
            ignore: [ // 配置不用copy的文件
              '**/index.html',
              '**/.DS_Store',
              '**/test.txt'
            ]
          }
        }
      ]
    })
  ]
复制代码

编译结果

image.png

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享