How can SCSS variables be used as JS variables

Currently we use SCSS variables with two pain points:

  1. You need to manually import
  2. In order to solve these two problems, we create JS files to define SCSS variables in JSON format, and then through the configuration of webpack parsing rules to achieve that can be used like ordinary SCSS, and can be used as JS variables.

Specification for use of SCSS variables

Variable to create

All SCSS variables are written in style/ variable.scss.

  1. Only lowercase letters are allowed
  2. The words are joined with an underscore “_”
  3. Naming should be simple and easy to understand, beginning with a large module or high-level word followed by a functional description of the word
const variables = {
  'header_height': '60px',
  'header_background': `#ededed`
}

module.exports = variables;
Copy the code

Note: the underlined link is named to enable a single import in the JS file, which has been converted in Webpack and must follow this format! Import {header_height} from “@/style/ variable.scss. Js “;

Variable used

Configure sASS parsing in WebPack. Generally speaking, the project builder has already handled it and the project members do not need to care. There is no need to import it, just use it normally in the style file.

Example used in SCSS

.the-nav{
  height: $header-height;
}
Copy the code

Js for example

import { header_height } from "@/style/variables.scss.js"; .data() {return {
    header_height: header_height
  }
}
...
Copy the code

The configuration on

Vue. Config. Js cuecli3 +

let scssVariables = require('./src/style/variables.scss.js'); module.exports = { css: { loaderOptions: { sass: { prependData: Object.keys(scssVariables) .map(k => `\? {k.replace('_', '-')}: ${scssVariables[k]}; `) .join('\n') } } } };Copy the code

Note: there is a pitfall here, the new version of Sas-Loader has replaced the API parameter prependData but there seems to be no documentation

Cuecli3 + in earlier versions of Sas-loader vue. Config. js

let scssVariables = require('./src/style/variables.scss.js'); module.exports = { css: { loaderOptions: { sass: { data: Object.keys(scssVariables) .map(k => `\? {k.replace('_', '-')}: ${scssVariables[k]}; `) .join('\n') } } } };Copy the code

Data of the old version => prependData of the new version

Vuecli2 webpack. Config. Js

let scssVariables = require('./src/style/variables.scss.js'); . {test: /\.scss$/,
  use: [
    'css-loader'.'postcss-loader',
    {
      loader: 'sass-loader',
      options: {
        data: Object.keys(scssVariables)
          .map(k => `\$${k.replace('_', '-')}: ${scssVariables[k]}; `) .join('\n'}}]}...Copy the code

After a posture, to here can successfully unlock the new world ~~~~

Lose your hair in a graceful manner ~ oh no code ~

GitHub welcomes friends