共计 1106 个字符,预计需要花费 3 分钟才能阅读完成。
目录
上节:懒加载
上节目录如下:
css 代码分割一般用于生产环境,先修改 src/index.js:
import './styles/index.less';
import _ from 'lodash';
const root = document.getElementById('root');
root.innerText = _.join(['hello', 'webpack']);
styles/index.less:
#root{color: blue;}
然后 npm run build, 浏览器运行 bundles/index.html:
现在样式是通过 style 标签内联在页面上的。
现在修改配置,让样式通过 link 标签外部引入:
webpack/webpack.prod.js:
const CleanWebpackPlugin = require('clean-webpack-plugin');
const merge = require('webpack-merge');
const baseConfig = require('./webpack.base');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = merge(baseConfig, {
mode: 'production',
output: {filename: '[name].[contenthash:10].js'
},
devtool: 'cheap-module-source-map',
module: {
rules: [{
test: /\.less$/,
use: [{loader: MiniCssExtractPlugin.loader,}, 'css-loader', 'postcss-loader', 'less-loader']
}]
},
plugins: [
new MiniCssExtractPlugin({filename: '[name].css',
chunkFilename: '[id].css'
}),
new CleanWebpackPlugin()],
optimization: {
splitChunks: {chunks: 'all'}
}
});
安装 mini-css-extract-plugin:npm i mini-css-extract-plugin -D
然后打包 npm run build:
生成了单独的 css 文件,浏览器运行 bundles/index.html, 打开 f12:
这样就实现了 link 的外部引入
详细配置参考:https://webpack.js.org/plugin…
下节:shiming(待更新)
正文完