Vue configures global styles (style-resources-loader)

Hits: 0

1. Introduction

  • When the style is introduced, the introduction of variables needs to be introduced once in each file. In order to avoid the problem of needing to be introduced separately every time it is used, it is adopted style-resources-loader.

  • Here is an lessexample , create a new one reset.less(the file name is arbitrary), and the path is @/assets/reset.less.

  • Single page import example:

    <style lang="less" scoped></p> <p>// The path here cannot use the @ symbol, otherwise an error will be reported // @import "@/assets/reset.less" ; @import "../assets/reset.less";</p> <p>.content { color: @dzm-color; }</p> <p></style>

  • It is impossible to implement global styles simply by introducing them in the main.jsfile import '@/assets/reset.less'. This method is wrong.

  • The following two configuration methods do not need to be introduced in the main.jsfile , import '@/assets/reset.less'and can be used directly after configuration.

2. Configuration method 1

  • Installstyle-resources-loader

    $ npm i style-resources-loader

  • Installvue-cli-plugin-style-resources-loader

    $ npm i vue-cli-plugin-style-resources-loader

  • Create vue.config.js and add the following configuration

    const path = require('path');
    module.exports = {
    pluginOptions: {
    'style-resources-loader': {
    preProcessor: 'less' ,
    // All three patterns can be written
    // patterns: ["./src/assets/reset1.less", "./src/assets/reset2.less"]
    // patterns: "./src/assets/reset.less"
    patterns: [
    // Both paths can be written, the path here cannot use the @ symbol, otherwise an error will be reported
    // path.resolve(__dirname, './src/assets/reset.less')
    path.resolve(__dirname, 'src/assets /reset.less' )
    ]
    }
    }
    };

3. Configuration method 2

  • Installstyle-resources-loader

    $ npm i style-resources-loader

  • Create vue.config.js and add the following configuration

    module.exports = {
    chainWebpack: (config) => {
    const oneOfsMap = config.module.rule("less").oneOfs.store;
    oneOfsMap.forEach(item => {
    item
    .use("style-resources-loader")
    .loader("style-resources-loader")
    .options({
    // The path here cannot use the @ symbol, otherwise an error will be reported
    // patterns: ["./src/assets/reset1.less", "./src/assets/reset2.less"]
    patterns: "./src/assets /reset.less"
    })
    .end()
    })
    }
    };

Fourth, choose one of the above two methods

  • After configuration, re-run the project to test

    <template> <div class="content">DZM - Test</div> </template></p> <p><script> export default { } </script></p> <p><style lang="less" scoped> // Use the style, there will be no need to import a single page here, you can use it directly .content { margin-top: 50px; color: @dzm-color; } </style>

You may also like...

Leave a Reply

Your email address will not be published.