1. 程式人生 > >webpack4 自學筆記五(tree-shaking)

webpack4 自學筆記五(tree-shaking)

全部的程式碼及筆記都可以在我的github上檢視, 歡迎star:

https://github.com/Jasonwang911/webpackStudyInit/tree/master/ThreeShaking  

Three Shaking : 刪除冗餘程式碼,常規優化和引入第三方庫

JS Three Shaking

webpack在2.0以後會標識多餘程式碼 webpack.optimize.uglifyJS 來移除這些被標識的程式碼

npm run pord 才開啟tree shaking
npm webpack-deep-scope-plugin (深度tree shaking)

 

CSS Three Shaking

需要藉助 Purify CSS
安裝依賴: npm instal purify-css purifycss-webpack glob-all --save-dev

option:
path: glob.sync([]) // npm install glob-all --save-dev 處理多路徑

 

var path = require('path');
var MiniCssExtractPlugin = require('mini-css-extract-plugin');
var PurifyCSS = require("purifycss-webpack");
var glob = require("glob-all");
var ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
    mode: 'development',
    entry: {
        app: './src/app.js'
    },

    output: {
        path: path.resolve(__dirname, 'dist'),
        publicPath: './dist/',
        filename: '[name].bundle.js',
        chunkFilename: '[name].bundle.js'
    },

    module: {
        rules: [{
            test: /\.less$/,
            use: [
                MiniCssExtractPlugin.loader,
                {
                    loader: 'css-loader',
                    options: {
                        minimize: true,
                        localIdentName: '[path][name]__[local]--[hash:base64:5]'
                    }
                },
                {
                    loader: 'less-loader'
                }
            ]
        }]
    },

    plugins: [
        new MiniCssExtractPlugin({
            filename: "[name].min.css",
            chunkFilename: "[name].css"
        }),
        new PurifyCSS({
            paths: glob.sync([
                // 要做CSS Tree Shaking的路徑檔案
                path.resolve(__dirname, "./*.html"),
                path.resolve(__dirname, "./src/*.js")
            ])
        })
    ]

}