Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Vue CLI CSS-related


May 07, 2021 Vue CLI


Table of contents


Vue CLI projects are born to support PostCSS, CSS Modules, and preprocessors including Sass, Less, Stylus, and more.

Refers to a static resource

All compiled CSS resolves the url() references in them through css-loader and treats them as module requests. T his means that you can refer to static resources with relative paths based on the local file structure. A lso note that if you want to reference a file in an npm dependency, or if you want to use webpack alias, you need to prefix the path with . . . to avoid ambiguity. For more details, please refer to Working with static resources.

Preprocessor

You can select a preprocessor (Sass/Less/Stylus) when you create the project. I f not selected at the time, the built-in webpack will still be preconfigured to do all the processing. You can also manually install the appropriate webpack loader:

# Sass
npm install -D sass-loader node-sass

# Less
npm install -D less-loader less

# Stylus
npm install -D stylus-loader stylus

You can then import the appropriate file type, or use it in the .vue file:

<style lang="scss">
$color: red;
</style>

Automated import

If you want to automate the import of files (for colors, variables, mixin...), you can use style-resources-loader. Here's an example of Stylus importing ./src/styles/imports.styl in each single-file component and Stylus file:

// vue.config.js
const path = require('path')

module.exports = {
  chainWebpack: config => {
    const types = ['vue-modules', 'vue', 'normal-modules', 'normal']
    types.forEach(type => addStyleResource(config.module.rule('stylus').oneOf(type)))
  },
}

function addStyleResource (rule) {
  rule.use('style-resource')
    .loader('style-resources-loader')
    .options({
      patterns: [
        path.resolve(__dirname, './src/styles/imports.styl'),
      ],
    })
}

You can also choose to use vue-cli-plugin-style-resources-loader.

PostCSS

PostCSS is used internally in the Vue CLI.

You can configure PostCSS through .postcsrc or any configuration source supported by postcs-load-config. Postcss-loader can also be .js css.loaderOptions.postcss in the vue.config file.

We turned autoprefixer on by default. If you want to configure the target browser, you can use the browserslist field of package.json.

Notes about browser prefix rules in CSS

In a production environment build, the Vue CLI optimizes the CSS and discards unnecessary browser prefix rules based on the target browser. Because autoprefixer is turned on by default, you can only use CSS rules without prefixes.

CSS Modules

You can use CSS Modules in the .vue file in an out-of-the-box manner.

If you want to import CSS or other preprocessed files in JavaScript as CSS Modules, the file should be in .module. (css|less|s|s |sstyl) ends:

import styles from './foo.module.css'
// 所有支持的预处理器都一样工作
import sassStyles from './foo.module.scss'

If you want to remove the .module from the file name, you can set css.requireModuleExtension in the vue.config .js the file name to false:

// vue.config.js
module.exports = {
  css: {
    requireModuleExtension: false
  }
}

If you want to customize the class name of the generated CSS Modules module, you can do so by using the css.loaderOptions .js option in the vue.config .css. All css-loader options are supported here, such as localIdentName and camelCase:

// vue.config.js
module.exports = {
  css: {
    loaderOptions: {
      css: {
        // 注意:以下配置在 Vue CLI v4 与 v3 之间存在差异。
        // Vue CLI v3 用户可参考 css-loader v1 文档
        // https://github.com/webpack-contrib/css-loader/tree/v1.0.1
        modules: {
          localIdentName: '[name]-[hash]'
        },
        localsConvention: 'camelCaseOnly'
      }
    }
  }
}

Pass options to the preprocessor Loader

There are times when you want to pass options to the webpack's preprocessor loader. Y ou can use the css.loaderoptions .js in the vue.config option. For example, you can pass in shared global variables to all Sass/Less styles like this:

// vue.config.js
module.exports = {
  css: {
    loaderOptions: {
      // 给 sass-loader 传递选项
      sass: {
        // @/ 是 src/ 的别名
        // 所以这里假设你有 `src/variables.sass` 这个文件
        // 注意:在 sass-loader v7 中,这个选项名是 "data"
        prependData: `@import "~@/variables.sass"`
      },
      // 默认情况下 `sass` 选项会同时对 `sass` 和 `scss` 语法同时生效
      // 因为 `scss` 语法在内部也是由 sass-loader 处理的
      // 但是在配置 `data` 选项的时候
      // `scss` 语法会要求语句结尾必须有分号,`sass` 则要求必须没有分号
      // 在这种情况下,我们可以使用 `scss` 选项,对 `scss` 语法进行单独配置
      scss: {
        prependData: `@import "~@/variables.scss";`
      },
      // 给 less-loader 传递 Less.js 相关选项
      less:{
        // http://lesscss.org/usage/#less-options-strict-units `Global Variables`
        // `primary` is global variables fields name
        globalVars: {
          primary: '#fff'
        }
      }
    }
  }
}

Loader can be configured with loaderOptions, including:

Tips

This is more recommended than manually specifying loader using chainWebpack, because these options need to be applied in multiple places where the loader is used.