webpack学习第十四步——css代码分割及压缩

2020-02-14  本文已影响0人  Love小六六

修改chunkname

output: {
    path: path.resolve(__dirname, '../build'),
    filename: '[name].js',
    // 增加chunkFilename
    chunkFilename: "[name].chunk.js"
},
import _ from 'lodash'
document.addEventListener('click',() => {
    import(/* webpackPrefetch: true *//* webpackChunkName:'handleClick' */'./handleClick.js').then(({default: func}) => {
        func()
    })
})

css代码分割

npm install mini-css-extract-plugin -D
// webpack.common.js中对css相关的处理放到webpack.dev.js和webpack.prod.js中
// webpack.dev.js增加对css普通处理
module: {
    rules: [
        {
            test: /\.css$/,
            use: [
                'style-loader',
                'css-loader',
                'postcss-loader'
            ]
        }
    ]
}
// 修改webpack.prod.js
const merge = require('webpack-merge')
const commonConfig = require('./webpack.common')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const prodConfig = {
    mode: "production",
    devtool: "cheap-module-source-map",
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                // 使用MiniCssExtractPlugin的loader
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    'postcss-loader'
                ]
            }
        ]
    },
    plugins:[
        new MiniCssExtractPlugin()
    ]

}

module.exports = merge(commonConfig,prodConfig)
import './style.css'
body{
    background: green;
}
// 表示对css文件不使用treeShaking,因为css文件的引入方式是import ./style.css,不是模块化的方式
"sideEffects": [
    "*.css"
]

css代码分割配置

plugins:[
    new MiniCssExtractPlugin({
        filename: 'style.css',
        // filename: '[name].css'
    })
]

css代码压缩

npm install optimize-css-assets-webpack-plugin -D
const merge = require('webpack-merge')
const commonConfig = require('./webpack.common')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCssAssetsbpackPlugin = require('optimize-css-assets-webpack-plugin')
const prodConfig = {
    mode: "production",
    devtool: "cheap-module-source-map",
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    'postcss-loader'
                ]
            }
        ]
    },
    optimization: {
    // 使用插件进行css代码压缩
        minimizer: [new OptimizeCssAssetsbpackPlugin({})]
    },
    plugins:[
        new MiniCssExtractPlugin({
            filename: '[name].css',
            chunkFilename: '[name].chunk.css'
        })
    ]

}

module.exports = merge(commonConfig,prodConfig)
上一篇下一篇

猜你喜欢

热点阅读