[Vue CLI 3] 配置解析之 css.extract

你们还记得咱们在老版本中,对于线上环境配置中会把全部的 css 多打成一个文件css

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

第一步都是加载插件webpack

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

这个插件的描述以下:web

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

而后配置以下:(省去了 rules 相关的配置)ui

通常配置 filename 来保证最终生成的 css 文件名插件

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

咱们能够预先用 vue inspect --plugin extract-css 看看最终生成的配置:code

/* 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 中:get

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

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

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

设置一个变量 shouldExtractio

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 : {})
相关文章
相关标签/搜索