Webpack:使用plugins让打包更便捷

HtmlWebpackPlugin

文档:地址

HtmlWebpackPlugin作用

HtmlWebpackPlugin 会在打包结束后,自动生成一个html文件,并把打包生成的js自动引入到这个html中


webpack.config.js

plugin的作用

可以在webpack运行到某个时刻的时候,帮你做一些事情。

类似于vue的生命周期钩子

CleanWebpackPlugin

作用:在打包前先删除dist文件夹

安装:npm install clean-webpack-plugin -D


webpack.config.js

const path = require('path'); //引入node核心模块
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
    mode: 'development',//打包模式(默认)
    entry: {
        main: './src/index.js',//从那一个文件开始打包
    },
    module: { //当遇到不知道怎么打包的模块时,到此位置查找
        rules: [{
            test: /\.(jpg|png|gif)$/,
            use: {
                loader: 'url-loader',
                options: { 
                    name: '[name]_[hash].[ext]',
                    outputPath: 'images/',
                    limit: 2048
                }
            }
        }, {
            test: /\.(eot|ttf|svg|woff|woff2)$/,
            use: {
                loader: 'file-loader'
            }
        }, {
            test: /\.scss$/,
            use: [
                'style-loader', 
                {
                    loader: 'css-loader',
                    options: {
                        importLoaders: 2,
                    }
                },
                'sass-loader',
                'postcss-loader'
            ]
        }]
    },
    output: { //打包好的文件,放置信息如下
        path: path.resolve(__dirname, 'dist'),
        //dirname 表示当前路径,dist 是文件夹
        filename: 'bundle.js'
    },
    plugins: [new HtmlWebpackPlugin({
        template: 'src/index.html'
        //设置src目录下的index.html文件为模版
    }), new CleanWebpackPlugin()]
}

参数设置文档:https://github.com/johnagan/clean-webpack-plugin#options-and-defaults-optional

猜你喜欢

转载自blog.csdn.net/weixin_41900808/article/details/88669413