Search code examples
webpackvue.jswebpack-2material-components

How to include external sass directory with Vuejs+Webpack?


beginner Vuejs question here. I'm trying to compile sass files with Vuejs and Webpack. Following the instructions I installed:

npm install sass-loader node-sass --save-dev

and then, I can use sass processing in my components:

<style lang="sass">
  /* This works with my local components */
</style>

The problem is when I want to use sass files defined in 3rd party modules living in node_modules. In particular, I want to use Material Components Web. Now, when I want to import sass files in a component:

<style lang="scss" scoped>
    @import '@material/card/mdc-card';
</style>

the following error happens:

Module build failed: 
    @import '@material/card/mdc-card';
    File to import not found or unreadable: @material/card/mdc-card.

The Question

How can I include the folder node_modules/@material in the sass processor config?

webpack.base.conf.js

var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')

function resolve(dir) {
    return path.join(__dirname, '..', dir)
}

module.exports = {
    entry: {
        app: './src/main.js'
    },
    output: {
        path: config.build.assetsRoot,
        filename: '[name].js',
        publicPath: process.env.NODE_ENV === 'production'
            ? config.build.assetsPublicPath
            : config.dev.assetsPublicPath
    },
    resolve: {
        extensions: ['.js', '.vue', '.json'],
        alias: {
            'vue$': 'vue/dist/vue.esm.js',
            '@': resolve('src')
        }
    },
    module: {
        rules: [
            {
                test: /\.(js|vue)$/,
                loader: 'eslint-loader',
                enforce: 'pre',
                include: [resolve('src'), resolve('test')],
                options: {
                    formatter: require('eslint-friendly-formatter')
                }
            },
            {
                test: /\.vue$/,
                loader: 'vue-loader',
                options: vueLoaderConfig
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                include: [resolve('src'), resolve('test')]
            },
            {
                test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                loader: 'url-loader',
                options: {
                    limit: 1000,
                    name: utils.assetsPath('img/[name].[hash:7].[ext]')
                }
            },
            {
                test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
                loader: 'url-loader',
                options: {
                    limit: 10000,
                    name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
                }
            },
            {
                test: /\.s[a|c]ss$/,
                loader: 'style!css!sass',

                /* ADDED THIS LINE, BUT NOT LUCK */ 
                options: {
                  includePaths: [resolve('node_modules')],
                },

                /* THIS DON'T WORK EITHER */ 
                include: [resolve('node_modules')],

            }
        ]
    }
}

vue-loader.conf.js

var utils = require('./utils')
var config = require('../config')
var isProduction = process.env.NODE_ENV === 'production'

module.exports = {
  loaders: utils.cssLoaders({
    sourceMap: isProduction
      ? config.build.productionSourceMap
      : config.dev.cssSourceMap,
    extract: isProduction
  })
}

utils.js

var path = require('path')
var config = require('../config')
var ExtractTextPlugin = require('extract-text-webpack-plugin')

exports.assetsPath = function (_path) {
  var assetsSubDirectory = process.env.NODE_ENV === 'production'
    ? config.build.assetsSubDirectory
    : config.dev.assetsSubDirectory
  return path.posix.join(assetsSubDirectory, _path)
}

exports.cssLoaders = function (options) {
  options = options || {}

  var cssLoader = {
    loader: 'css-loader',
    options: {
      minimize: process.env.NODE_ENV === 'production',
      sourceMap: options.sourceMap
    }
  }

  // generate loader string to be used with extract text plugin
  function generateLoaders (loader, loaderOptions) {
    var loaders = [cssLoader]
    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        options: Object.assign({}, loaderOptions, {
          sourceMap: options.sourceMap
        })
      })
    }

    // Extract CSS when that option is specified
    // (which is the case during production build)
    if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader'
      })
    } else {
      return ['vue-style-loader'].concat(loaders)
    }
  }

  // https://vue-loader.vuejs.org/en/configurations/extract-css.html
  return {
    css: generateLoaders(),
    postcss: generateLoaders(),
    less: generateLoaders('less'),
    sass: generateLoaders('sass', { indentedSyntax: true }),
    scss: generateLoaders('sass'),
    stylus: generateLoaders('stylus'),
    styl: generateLoaders('stylus')
  }
}

// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
  var output = []
  var loaders = exports.cssLoaders(options)
  for (var extension in loaders) {
    var loader = loaders[extension]
    output.push({
      test: new RegExp('\\.' + extension + '$'),
      use: loader
    })
  }
  return output
}

Solution

  • To tell webpack/sasss-loader that an @import path should be resolved as a node_module rather than a local file, you have to prepend a tilde:

    @import '~@material/card/mdc-card';
    

    So this has nothing to do with vue-loader but is a general sass-loader-pitfall.

    Edit: as noted in the docs for this css lib:

    NOTE: The components' Sass files expect that the node_modules directory containing the @material scope folder is present on the Sass include path.

    So we have to add the inlcudePaths for sass-.loader/node-sass:

    return {
      css: generateLoaders(),
      postcss: generateLoaders(),
      less: generateLoaders('less'),
      sass: generateLoaders('sass', { indentedSyntax: true, includePaths: [path.resolve(__dirname, '../node_modules'] }),
      scss: generateLoaders('sass' { includePaths: [path.resolve(__dirname, '../node_modules'] }),
      stylus: generateLoaders('stylus'),
      styl: generateLoaders('stylus')
    }