详解Vue CLI3配置解析之css.extract

2019-11-15,,,

大家还记得我们在老版本中,对于线上环境配置中会把所有的 css 多打成一个文件:

核心是使用了插件 extract-text-webpack-plugin,方式如下:

第一步都是加载插件

const ExtractTextPlugin = require('extract-text-webpack-plugin')

这个插件的描述如下:

Extract text from a bundle, or bundles, into a separate file.

然后配置如下:(省去了 rules 相关的配置)

一般配置 filename 来保证最终生成的 css 文件名

plugins: [
 new ExtractTextPlugin({
   filename: utils.assetsPath('css/[name].[contenthash].css')
 })
]

我们可以预先用 vue inspect --plugin extract-css 看看最终生成的配置:

/* config.plugin('extract-css') */
new MiniCssExtractPlugin(
 {
  filename: 'css/[name].[contenthash:8].css',
  chunkFilename: 'css/[name].[contenthash:8].css'
 }
)

在文件 @vue/cli-service/lib/config/css.js 中:

最开始需要获取 vue.config.js 里面配置的 css.extract

const isProd = process.env.NODE_ENV === 'production'

const {
 extract = isProd
} = options.css || {}

设置一个变量 shouldExtract

const shadowMode = !!process.env.VUE_CLI_CSS_SHADOW_MODE
const shouldExtract = extract !== false && !shadowMode

如果变量 shouldExtract 为 true,调用 plugin 方法来生成一个插件配置:

这里依赖的插件为 mini-css-extract-plugin

if (shouldExtract) {
   webpackConfig
    .plugin('extract-css')
     .use(require('mini-css-extract-plugin'), [extractOptions])
}

filename 内部也有一个判断过程,如果设置了 filenameHashing,它默认是 true:

filenameHashing: true

类型为 boolean:

filenameHashing: joi.boolean()
const filename = getAssetPath(
   options,
   `css/[name]${options.filenameHashing ? '.[contenthash:8]' : ''}.css`
  )

处理 filename 之后,插件还有一个配置项:chunkFilename

下面就是通过 Object.assign 来生成 extractOptions

const extractOptions = Object.assign({
   filename,
   chunkFilename: filename
  }, extract && typeof extract === 'object' ? extract : {})

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持北冥有鱼。

您可能感兴趣的文章:

  • vue-cli3.0使用及部分配置详解
  • vue-cli3脚手架的配置及使用教程
  • 详解如何配置vue-cli3.0的vue.config.js
  • 详解vue-cli脚手架中webpack配置方法
  • Vue-cli配置打包文件本地使用的教程图解
  • 详解vue-cli官方脚手架配置
  • 基于vue cli 通过命令行传参实现多环境配置
  • vue-cli配置环境变量的方法
  • vue-cli 引入、配置axios的方法
  • vue-cli脚手架-bulid下的配置文件

《详解Vue CLI3配置解析之css.extract.doc》

下载本文的Word格式文档,以方便收藏与打印。