VUE3之WebPack插件

插件的使用和loader一样,不仅需要安装,也需要在webpack.config.js中的plugins中进行配置。plugins是一个数组,数组的每一个元素都是一个对象。

clean-webpack-plugin

可以用于在webpack每一次打包时先删除先前打包的内容。安装:

npm install clean-webpack-plugin -D

配置:

const {CleanWebpackPlugin} = require("clean-webpack-plugin");
module.exports = {
    entry: "./src/main.js",
    output:{
        path: path.resolve(__dirname,"./build"),
        filename:"bundle.js"
    },
    plugins:[
        new CleanWebpackPlugin()
    ]
}

html-webpack-plugin

可以将html文件也打包。如果不指定模板的话就会按照默认的模板。安装:

npm install html-webpack-plugin -D

可以对html指定套用的模板:

const HtmlWebpackPlugin=require("html-webpack-plugin");
module.exports = {
    plugins:[
        new HtmlWebpackPlugin({
            template: "./public/index.html"
        })
    ]
}
// /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><%= htmlWebpackPlugin.options.title %> not work</strong>
    </noscript>
    <div id="app"></div>
</body>
</html>

<% 变量 %>是ejs语法,可以使用DefinePlugin来为其指定变量。

DefinePlugin

DefinePlugin是WebPack内部的插件,直接从Webpack中结构就能得到,不需要另外安装:

const {DefinePlugin}=require("webpack");

使用方法:在DefinePlugin的实例化过程中传入要指定的参数:

const {DefinePlugin}=require("webpack");

module.exports = {
    plugins:[
        new DefinePlugin({
            BASE_URL: "'./'"
        })
    ]
}

CopyWebpackPlugin复制文件

通过CopyWebpackPlugin可以将需要复制的文件(如/public/)复制到打包的目的文件夹中。安装:

npm install copy-webpack-plugin -D

patterns数组表示要复制的匹配信息。from指定复制的源文件夹,to表示目的文件夹(根目录为build),ignore表示忽略的文件。

    plugins:[
        new CopyWebpackPlugin({
            patterns: [
                {
                    from: "./public",
                    to: "./",
                    globOptions:{
                        ignore:[
                            "**/index.html"
                        ]
                    }
                }
            ]
        })
    ]

webpack的其它设置

module.exports = {
    // 设置模式
    // development 开发阶段
    // production 准备打包上线
    mode:"development",
    // 设置source-map,建立js映射文件,方便调试代码错误
    devtool: "source-map"
}

发表评论