webpack(9)plugin插件功能的使用

plugin

插件是 webpack 的支柱功能。webpack 自身也是構建於你在 webpack 配置中用到的相同的插件系統之上!
插件目的在於解決 loader 沒法實現的其餘事。
 css

經常使用的插件

因爲插件能夠攜帶參數/選項,你必須在 webpack 配置中,向 plugins 屬性傳入一個 new 實例,接下來咱們介紹幾個經常使用的插件
 html

BannerPlugin

將橫幅添加到每一個生成的塊的頂部。通常用於添加版權聲明vue

const webpack = require('webpack'); // 訪問內置的插件
const path = require('path');

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: "dist/"
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: 'babel-loader',
      },
    ],
  },
  plugins: [
    new VueLoaderPlugin(),
    new webpack.BannerPlugin("最終版權歸jkc全部")
  ],
};

最後咱們進行打包,打包後的bundler.js文件的最上方會出現以下的一行註釋webpack

/*! 最終版權歸jkc全部 */

 

HtmlWebpackPlugin

目前咱們的index.html文件是存放在項目的根目錄,可是咱們真實發布項目的時候是發佈的dist文件夾下的內容,可是dist文件夾下若是沒有index.html文件,那麼打包的js文件也就沒有意義了,因此咱們須要將index.html打包到dist文件夾下,這個時候咱們就可使用插件HtmlWebpackPluginweb

HtmlWebpackPlugin會自動生成一個index.html文件(能夠指定模板生成),而後將打包的js文件自動經過script標籤插入到body中。
使用插件前咱們須要安裝插件,命令以下:npm

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

安裝完成之後,咱們須要在webpack中引用它,並對其進行配置json

const { VueLoaderPlugin } = require('vue-loader')
const path = require('path')
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');  // 導入插件

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    // publicPath: "dist/"
  },
  resolve: {
    extensions: ['.json', '.js', '.vue', '.css'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
    },
  },
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.less$/,
        use: [
          'vue-style-loader',
          'css-loader',
          'less-loader'
        ]
      },
      {
        test: /\.png/,
        type: 'asset'
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      }
    ],
  },
  plugins: [
    // 請確保引入這個插件!
    new VueLoaderPlugin(),
    new webpack.BannerPlugin("最終版權歸jkc全部"),
    new HtmlWebpackPlugin({ template: 'index.html' }),   // 配置插件,並提供了本身的模板選項,這裏的index是與webpack.config.js同目錄下自定義的模板文件
  ]
}

最後進行打包,打包後dist目錄下就會生成一個index.html文件babel

相關文章
相關標籤/搜索