速學Webpack5 - Plugin

插件能夠完成 webpack 本身不具有的功能。它的使用一般是在 webpack 的配置信息 plugins 選項中指定。
在上一章中,打包后需要我們手動把打包的 js 文件引入到 html 中去。其實我們可以通過html-webpack-plugin插件實現(xiàn)自動生成 html 文件和引入 js 的功能。

html-webpack-plugin

1. 安裝

npm i html-webpack-plugin -D

2. 配置 html-webpack-plugin

webpack 插件的使用需要先引入,然后在plugins選項中實例化調(diào)用(插件本身是個類),代碼如下:

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

module.exports = {
  entry: './src/index.js', // 注意這里把入口文件index.js修改到了src目錄下
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, './dist')
  },
  plugins: [new HtmlWebpackPlugin()],
  mode: 'development'
};

清空dist目錄,然后使用npx webpack命令打包,我們會發(fā)現(xiàn)dist目錄里自動生成了一個index.html。
有時我們想要自定義 html, 我們可以通過template參數(shù)傳入我們自定義的 html 路徑作為模板。代碼如下:

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

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, './dist')
  },
  plugins: [new HtmlWebpackPlugin({ template: './index.html', filename: 'index.html', inject: 'body' })],
  mode: 'development'
};

其中,plugins選項是一個數(shù)組,里面是使用的各種插件。我們實例化了html-webpack-plugin插件,并且傳入了三個參數(shù)template, filename,inject。
template: 我們的 html 模板,可以根據(jù)自己需要創(chuàng)建、修改
filename: html-webpack-plugin生成 html 文件的名稱
inject: 打包生成的 js 文件,在 html 文件哪個位置引入
更多配置,可以查詢 html-webpack-plugin的 api

清除上一次打包內(nèi)容

前面的打包中,我們發(fā)現(xiàn),每次打包都要手動清除上一次的dist文件。事實上,這個清除功能我們也可以通過插件解決。
在 webpack4 中,一般使用clean-webpack-plugin插件來清除上一次打包的內(nèi)容。
webpack5 集成了 clean 插件,我們只需要在輸出中配置clean: true即可。
代碼如下:

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

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, './dist'),
    clean: true
  },
  plugins: [new HtmlWebpackPlugin({ template: './index.html', filename: 'index.html', inject: 'body' })],
  mode: 'development'
};

總結(jié)

  1. webpack 插件本身是一個類,使用時需要先引入,然后在plugins選項中實例化調(diào)用
  2. html-webpack-plugin能夠以某個 html 作為模板,且能指定 js 引入位置,以及輸出 html 文件名
  3. webpack5 集成了 clean 插件,直接在輸出中加入 clean: true 即可在每次打包的時候清除上一次打包的內(nèi)容。

參考資料:

webpack 官方文檔

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容