How to Implement css module Using css loader in vue cli

  • 2021-10-16 00:55:11
  • OfStack

[Preface]

css modular solutions of vue and react are realized by relying on loader. In use, scoped attribute is used to realize style privatization in vue, and deep action selector/deep is used to realize style de-privatization.

Examples:


<div>
  <div class="demo">
    <div class="child"></
    div>
  </div>
</div>
<script>
// some code
<script/>
<style lang="less" scoped>
 .demo {
  height: 100px;
  padding-top: 20px;
  background-color: grey;
  /deep/.child {
   color: red;
  }
 }
</style>

This is how it is used in react (based on css-loader):


//test.less
.demo {
  height: 100px;
  padding-top: 20px;
  background-color: grey;
  :global(.child) {
    color: red
  }
}

import styles from './test.less'

// some code

<div className={styles.demo}>
  <div class="child"></div>
</div>

It must be said that vue is more convenient to use.

What if you insist on using css-loader in vue to implement this solution of css module? Take vue-clie 3. x as an example.

webpack-chain is now used to configure webpack, both in the scaffold vue-cli of vue and in the scaffold umi of react.

Here, under the project root directory of the vue-cli scaffold creation, create a new vue. config. js and write the following:


module.exports = {
 chainWebpack: (config) => {
  config.devServer
   .proxy({
    '/api': {
     target: 'http://localhost:3000',
     pathRewrite: { '^/api': '', },
    },
   })
   .port(9000);

  config.module
  .rule('less')
  .oneOf('normal-modules')
  .test(/.less$/)
  .use('css-loader')
  .tap(options => {
   return Object.assign(options, {
    modules: {
     localIdentName: '[name]__[local]___[hash:base64:5]',
     auto: /\.less$/i,
    },
   })
  });

 },
};

Actually, there is no need to write this paragraph. By default, the scaffold of vue-cli has been configured with the modularization of css-loader, but it is necessary to name the less file in the form of xxx.module. less, which is different from umi and inconvenient. If you configure it and restart it, you can write css like react1. In addition, I'm just talking about the solution that can be used with css-loader on vue-cli, but the best practice is to use the one that comes with vue.

Finish

The above is how to use css-cli to implement css module in vue-cli. For more information about css-loader to implement css module in vue-cli, please pay attention to other related articles on this site!


Related articles: