大家還記得我們在老版本中,對于線上環境配置中會把所有的 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_MODEconst 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 : {})以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答