vue.jswebpacksassnativescript-vue

ISO proper way to chain Webpack via vue.config.js to add global .scss imports to my .vue files (vue-cli-plugin-nativescript-vue)


I have Vue.js project I've setup previously that dynamically adds defined .scss files to my .vue template files, so I can access my variables, mixins, etc. in the templates without @importing them, or having them duplicate code from imports.

My problem is I'm setting up a NativeScript/Vue.js project with vue-cli-plugin-nativescript-vue and was curious if anyone has successfully setup their webpack to allow the same functionality. It's my understanding that the plugin replaces webpack with the latest when you run, as specified in the docs https://cli.vuejs.org/guide/webpack.html#replacing-loaders-of-a-rule.

Below is my vue.config.js (which compiles with no error) but doesn't seem to be working. I'm probably missing something or don't understand exactly how this is working, any help is appreciated.


const path = require('path')

module.exports = {
    chainWebpack: config => {
        const ofs = ['vue-modules', 'vue', 'normal-modules', 'normal']
        const cssRules = config.module.rule('css')
        const postRules = config.module.rule('postcss')

        const addSassResourcesLoader = (rules, type) => {
            rules
                .oneOf(type)
                .use('sass-resoureces-loader')
                .loader('sass-resources-loader')
                .options({
                    resources: './src/styles/_global.scss', // your resource file or patterns
                })
        }
        ofs.forEach(type => {
            addSassResourcesLoader(cssRules, type)
            addSassResourcesLoader(postRules, type)
        })
        return config
    },
}

Solution

  • Vue CLI provides a config to augment your CSS loaders:

    // vue.config.js
    module.exports = {
      css: {
        loaderOptions: {
          scss: {
            // sass-loader@^8.0.0
            prependData: `import "~@/styles/_global.scss";`,
    
            // sass-loader@^9.0.0 or newer
            additionalData: `import "~@/styles/_global.scss";`,
          }
        }
      }
    }