Use sass in vue2 and configure global sass style files

If the style file sass is used in vue, if each.Vue file introduces this style, it will inevitably cause duplication and redundancy of the style after the file is built out. If a scss file is introduced globally in main.js, and no error is defined in referencing the reference variable in other components or pages, other styles can be displayed normally, which is obviously a compilation problem.Then, it's necessary to set the global settings and load the styles!

First, npm is installed

 "sass-loader": "^6.0.7",
 "sass-resources-loader": "^1.3.3",

In build/webpack.base.conf.js, add in rule of module

 {
        test: /\.scss$/,
        loaders: ["style", "css", "sass"]
      }

Then add the following code to the build/utils.js file:

Note that my global style is placed in src/common/sass/index.scss

  function resolveResouce(name) {
    return path.resolve(__dirname, '../src/common/sass/' + name);
  }
  function generateSassResourceLoader() {
    var loaders = [
      cssLoader,
      'postcss-loader',
      'sass-loader',
      {
        loader: 'sass-resources-loader',
        options: {
          //This is the sass file used, multiple files are passed in as arrays, this is the scss file with variables and mixin s
          resources: [resolveResouce('variable.scss'), resolveResouce('mixin.scss')] Note that this is the location of my global style, different individuals, need to adjust
        }
      }
    ];

    if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader'
      })
    } else {
      return ['vue-style-loader'].concat(loaders)
    }
  }

Finally, change the return section at the bottom of the page to look like this

  return {
    css: generateLoaders(),
    postcss: generateLoaders(),
    less: generateLoaders('less'),
    //sass: generateLoaders('sass', { indentedSyntax: true }),
    //scss: generateLoaders('sass'),
    sass: generateSassResourceLoader(),
    scss: generateLoaders('sass')
      .concat(
        {
          loader: 'sass-resources-loader',
          options: {
            resources: path.resolve(__dirname, '../src/common/sass/index.scss')  //Note that this is the location of my global style, different individuals, need to adjust
          }
        }
      ),
    stylus: generateLoaders('stylus'),
    styl: generateLoaders('stylus')
  }

Reference resources: https://blog.csdn.net/qq_27868533/article/details/79651659
https://segmentfault.com/a/1190000013220058?utm_source=tag-newest

Keywords: sass Vue less npm

Added by bogu on Tue, 24 Mar 2020 18:05:30 +0200