2

目录

上节: 懒加载

上节目录如下:

clipboard.png

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:

clipboard.png

现在样式是通过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:

clipboard.png

生成了单独的css文件,浏览器运行bundles/index.html, 打开f12:

clipboard.png

这样就实现了link的外部引入

详细配置参考:https://webpack.js.org/plugin...

下节:编写一个loader


会js的诸葛村夫
282 声望617 粉丝

主angular,兼ts|webpack|rxjs|vue,擅长造轮子