您的当前位置:首页正文

详解vue项目中如何引入全局sass/less变量、function、mixin

2020-11-27 来源:品趣旅游知识分享网

让我们考虑下场景:当使用rem/vw开发移动端的时候,你定义了一个px转rem的函数,或者是网站配色的全局变量等,然后到工程里为每个vue文件或者组件@import ‘publicfilename.scss',那得重复做这样的工作很多很多...次,万一这些公用文件目录路径变怎么办呢,哭都来不及,想想都觉得恐怖呀!

接下来拯救我们的神器就要登场了---sass-resources-loader,它可以省去重复性的引入,还支持less,postcss等,具体用法如下:

npm install -d sass-resource-loader

首先我们找到项目里build目录,在该目录下找到util.js

更新前util.js代码如下:

'use strict'
const path = require('path')
const config = require('../config')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const packageConfig = require('../package.json')
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: {
 sourceMap: options.sourceMap
 }
 }

 // generate loader string to be used with extract text plugin
 function generateLoaders (loader, loaderOptions) {
 const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [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)
 }
 }

 // https://vue-loader.vuejs.org/en/configurations/extract-css.html
 return {
 css: generateLoaders(),
 postcss: generateLoaders(),
 less: generateLoaders('less'),
 sass: generateLoaders('sass', { indentedSyntax: true }),
 scss: generateLoaders('sass'),
 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
}

exports.createNotifierCallback = () => {
 const notifier = require('node-notifier')

 return (severity, errors) => {
 if (severity !== 'error') return

 const error = errors[0]
 const filename = error.file && error.file.split('!').pop()

 notifier.notify({
 title: packageConfig.name,
 message: severity + ': ' + error.name,
 subtitle: filename || '',
 icon: path.join(__dirname, 'logo.png')
 })
 }
}

/**
 * 增加 hljs 的 classname
 */
exports.wrapCustomClass = function (render) {
 return function (...args) {
 return render(...args)
 .replace('<code class="', '<code class="hljs ')
 .replace('<code>', '<code class="hljs">')
 }
}
/**
 * Format HTML string
 */
exports.convertHtml = function (str) {
 return str.replace(/(&#x)(\w{4});/gi, $0 => String.fromCharCode(parseInt(encodeURIComponent($0).replace(/(%26%23x)(\w{4})(%3B)/g, '$2'), 16)))
}

看util.js文件,我们首先找到我需要修改目标在哪:

// https://vue-loader.vuejs.org/en/configurations/extract-css.html
 return {
 css: generateLoaders(),
 postcss: generateLoaders(),
 less: generateLoaders('less'),
 sass: generateLoaders('sass', { indentedSyntax: true }),
 scss: generateLoaders('sass'),
 stylus: generateLoaders('stylus'),
 styl: generateLoaders('stylus')
 }

我们那sass为例,用sass-resources-loader对其改造:

/**
 * sass Less 源文件
 * @param name classFile
 * @returns {string}
 */
 function resolveResouce(name) {
 return path.resolve(__dirname, '../static/' + name);
 }

 //导入全局sass mixin function等
 function generateSassResourceLoader(){
 var loaders = [
 cssLoader,
 //'postcss-loader',
 'sass-loader',
 {
 loader:'sass-resources-loader',
 options: {
 //需要一个全局路径
 resources: [resolveResouce('index.scss')]
 }
 }
 ]
 if(options.extract){
 return ExtractTextPlugin.extract({
 use:loaders,
 fallback: 'vue-style-loader'
 })
 }else{
 return ['vue-style-loader'].concat(loaders)
 }
 }

工具写好好了,接下来直接把上门return对象做些调整,代码如下

 // https://vue-loader.vuejs.org/en/configurations/extract-css.html
 return {
 css: generateLoaders(),
 postcss: generateLoaders(),
 less: generateLoaders('less'),
 sass:generateSassResourceLoader(),
 scss:generateSassResourceLoader(),
 stylus: generateLoaders('stylus'),
 styl: generateLoaders('stylus')
 }

从代码中可以看出,我们把sass和scss的loader换成我们自己根据sass-resources-loader写的方法了,这样就实现了我们的目标。

显示全文