1. 程式人生 > 實用技巧 >08、Webpack配置外掛

08、Webpack配置外掛

目錄

Plugin

橫幅plugin

Webpack中的外掛就是對Webpack現有功能的各種擴充套件,比如打包優化,檔案壓縮等。

loader和plugin的區別:

  • loader主要用於轉換某些型別的模組,它是一個轉換器;
  • plugin是外掛,它是對webpack本身的擴充套件,是一個擴充套件器。

plugin的使用過程:

  • 通過npm安裝需要使用的外掛,(某些webpack已經內建的外掛不需要安裝);
  • 在webpack.config.js的plugins中配置外掛。

新增版權的Plugin

該外掛名稱為BannerPlugin,屬於webpack自帶的外掛。

const path = require("path");
const { VueLoaderPlugin } = require("vue-loader");
const webpack = require("webpack");

module.exports = {
    entry: "./src/main.js",
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: "bundle.js"
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    {loader: "style-loader"},
                    {loader: "css-loader"}
                ]
            }, 
            {
                test: /\.vue$/,
                use: {loader: 'vue-loader'}
            }
        ]
    },
    resolve: {
        alias: {
            'vue$': 'vue/dist/vue.esm.js'
        }
    },
    plugins: [
        new VueLoaderPlugin(),
        new webpack.BannerPlugin("BannerPlugin版權外掛.")
    ]
}

重新打包,檢視bundle.js檔案。

HtmlWebpackPlugin

目前我們的index.html檔案是存放在專案的根目錄下的。

  • 我們知道在真實發布專案時,釋出的是dist資料夾下的內容,所以我們需要將index.html檔案打包到dist資料夾中,這個時候就可以使用HtmlWebpackPlugin外掛;

HtmlWebpackPlugin可以為我們做:

  • 自動生成一個index.html;
  • 將打包的bundle.js檔案,自動通過script標籤插入到body中。

安裝外掛:

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

webpack.config.js

const path = require("path");
const { VueLoaderPlugin } = require("vue-loader");
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"
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    {loader: "style-loader"},
                    {loader: "css-loader"}
                ]
            }, 
            {
                test: /\.vue$/,
                use: {loader: 'vue-loader'}
            }
        ]
    },
    resolve: {
        // 在引入.js、.css、.vue檔案時不需要寫字尾
        extensions: ['.js', '.css', '.vue'],
        alias: {
            'vue$': 'vue/dist/vue.esm.js'
        }
    },
    plugins: [
        new VueLoaderPlugin(),
        new webpack.BannerPlugin("BannerPlugin版權外掛."),
        new HtmlWebpackPlugin({
            template: "index.html"
        })
    ]
}
import {sum, mul} from "./js/mathutil"


console.log(sum(10, 20));
console.log(mul(10, 20));

// 匯入css模組
require("./css/mycss");

// 使用vue進行開發
import Vue from "vue"
import App from './vue/App'

const app = new Vue({
    el: '#app',
    template: "<App></App>",
    components: {
        App
    }
})

重新打包釋出,自動生成的index.html。