vue項目中怎樣引入全局sass/less變量、function、mixin

讓我們斟酌下場景:當運用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寫的要領了,如許就完成了我們的目的。

    原文作者:hankblog
    原文地址: https://segmentfault.com/a/1190000015134504
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞