vue-cli (webpack) automatically injects global Sass or Less styles

In the vue project, we cannot directly import Sass/Less styles at the project entry main.js like *.css. So, how should we import Sass/Less global styles.

First of all, we need to find the direction to solve the problem and understand its principle. We know that the entire project is built using vue-cli, and vue-cli packages files through webpack. webpack reads a single file component (SFC, simple file component), and then sends the component to the corresponding loader to compile and transform it.

As shown in the figure below, after webpack reads SFC, it will first hand it over to vue-loader to convert the SFC code. If our SFC file contains Sass/Less, then webpack will also hand over the SFC style to Sass-loader or Less-loader. Convert style into css code.

If no other Sass/Less styles are imported in the style tag of SFC, then webpack will not use other style loaders for parsing. When we use other styles in SFC, such as external style variables, without importing external styles, webpack will report an error when packaging.

So, is there a mechanism to tell webpack when it converts, can it bring in other files to participate in the conversion process?

Open the official website of the scaffolding vue-cli , find the column of css configuration, and you will find that it has told us how to import global styles in the project built by vue-cli.

 In the project built by vue-cli, you need to configure vue.config.js to tell webpack which files are involved in the conversion. The following is the sample code:

// vue.config.js
module.exports = {
  css: {
    loaderOptions: {
      // 给 sass-loader 传递选项
      sass: {
        // ~@/ 是 src/ 的别名,属于webpack的知识
        // 所以这里假设你有 `src/variables.sass` 这个文件
        // 注意:在 sass-loader v8 中,这个选项名是 "prependData"
        additionalData: `@import "~@/variables.sass"`, // or @import url("~@/variables.sass")
      },
      // 默认情况下 `sass` 选项会同时对 `sass` 和 `scss` 语法同时生效
      // 因为 `scss` 语法在内部也是由 sass-loader 处理的
      // 但是在配置 `prependData` 选项的时候
      // `scss` 语法会要求语句结尾必须有分号,`sass` 则要求必须没有分号
      // 在这种情况下,我们可以使用 `scss` 选项,对 `scss` 语法进行单独配置
      scss: {
        additionalData: `@import "~@/variables.scss";` // 在``内可配置多个样式,注意别少了“;”
      }
    }
  }
}

 After this configuration, all SFCs will be imported in the style tag, and you can use them happily without manually importing external styles multiple times for each file.

// SFC 样式
<style>
@import "~@/variables.sass";
@import "~@/variables.scss";

.sfc{}
</style>

Guess you like

Origin blog.csdn.net/qq_58062502/article/details/129249113
Recommended