在使用vue开发SPA应用中,我们经常需要在一个或多个scss文件中定义公共变量或者mixin亦或是很多通用的function,而且不希望在每个vue文件中都去@import,针对这种情况,可以使用下面的方法添加全局引入的sass文件,使这些样式或者方法可以被打包到全局的样式文件中。
添加依赖
npm install sass-resources-loader --save-dev
修改build/utils.js
'use strict' const path = require('path') const config = require('../config') const ExtractTextPlugin = require('extract-text-webpack-plugin') exports.assetsPath = function (_path) { const assetsSubDirectory = process.env.NODE_ENV === 'production' ? config.build.assetsSubDirectory : config.dev.assetsSubDirectory return path.posix.join(assetsSubDirectory, _path) } exports.cssLoaders = function (options) { options = options || {} const cssLoader = { loader: 'css-loader', options: { minimize: process.env.NODE_ENV === 'production', sourceMap: options.sourceMap } } // generate loader string to be used with extract text plugin function generateLoaders (loader, loaderOptions) { const loaders = [cssLoader] if (loader) { loaders.push({ loader: loader + '-loader', options: Object.assign({}, loaderOptions, { sourceMap: options.sourceMap }) }) } // Extract CSS when that option is specified // (which is the case during production build) if (options.extract) { return ExtractTextPlugin.extract({ use: loaders, fallback: 'vue-style-loader' }) } else { return ['vue-style-loader'].concat(loaders) } } // 引入sass全局变量,mixin,function等 function resolveResouce(name) { return path.resolve(__dirname, '../src/assets/style/' + name); } function generateSassResourceLoader() { var loaders = [ cssLoader, // 'postcss-loader', 'sass-loader', { loader: 'sass-resources-loader', options: { // it need a absolute path resources: [ resolveResouce('reset.scss'), resolveResouce('var.scss'), resolveResouce('common.scss') ] } } ]; if (options.extract) { return ExtractTextPlugin.extract({ use: loaders, fallback: 'vue-style-loader' }) } else { return ['vue-style-loader'].concat(loaders) } } // https://vue-loader.vuejs.org/en/configurations/extract-css.html // return部分加入上面的loader return { css: generateLoaders(), postcss: generateLoaders(), less: generateLoaders('less'), sass: generateSassResourceLoader(), scss: generateSassResourceLoader(), stylus: generateLoaders('stylus'), styl: generateLoaders('stylus') } } // Generate loaders for standalone style files (outside of .vue) exports.styleLoaders = function (options) { const output = [] const loaders = exports.cssLoaders(options) for (const extension in loaders) { const loader = loaders[extension] output.push({ test: new RegExp('\\.' + extension + '$'), use: loader }) } return output }
前端大佬主题能共享吗?不会前端的小菜鸡路过
可以的,加我qq1637077309
不错不错,我喜欢看 https://www.jiwenlaw.com/
怎么收藏这篇文章?
看的我热血沸腾啊https://www.237fa.com/