大家還記得我們?cè)诶习姹局校瑢?duì)于線上環(huán)境配置中會(huì)把所有的 css 多打成一個(gè)文件:
核心是使用了插件 extract-text-webpack-plugin,方式如下:
第一步都是加載插件
const ExtractTextPlugin = require('extract-text-webpack-plugin')這個(gè)插件的描述如下:
Extract text from a bundle, or bundles, into a separate file.
然后配置如下:(省去了 rules 相關(guān)的配置)
一般配置 filename 來保證最終生成的 css 文件名
plugins: [ new ExtractTextPlugin({   filename: utils.assetsPath('css/[name].[contenthash].css') })]我們可以預(yù)先用 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 || {}設(shè)置一個(gè)變量 shouldExtract
const shadowMode = !!process.env.VUE_CLI_CSS_SHADOW_MODEconst shouldExtract = extract !== false && !shadowMode
如果變量 shouldExtract 為 true,調(diào)用 plugin 方法來生成一個(gè)插件配置:
這里依賴的插件為 mini-css-extract-plugin
if (shouldExtract) {   webpackConfig    .plugin('extract-css')     .use(require('mini-css-extract-plugin'), [extractOptions])}filename 內(nèi)部也有一個(gè)判斷過程,如果設(shè)置了 filenameHashing,它默認(rèn)是 true:
filenameHashing: true
類型為 boolean:
filenameHashing: joi.boolean()
const filename = getAssetPath(   options,   `css/[name]${options.filenameHashing ? '.[contenthash:8]' : ''}.css`  )處理 filename 之后,插件還有一個(gè)配置項(xiàng):chunkFilename
下面就是通過 Object.assign 來生成 extractOptions
const extractOptions = Object.assign({   filename,   chunkFilename: filename  }, extract && typeof extract === 'object' ? extract : {})以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持錯(cuò)新站長站。
新聞熱點(diǎn)
疑難解答
圖片精選