如何在Vuejs + Webpack中包含外部sass目录?

时间:2017-06-13 00:50:51

标签: webpack vue.js webpack-2 material-components

初学者Vuejs在这里提问。我正在尝试使用Vuejs和Webpack编译sass个文件。我安装the instructions之后:

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

然后,我可以在我的组件中使用sass处理:

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

问题在于我想使用sass中生成的第三方模块中定义的node_modules文件。特别是,我想使用Material Components Web。现在,当我想在组件中导入sass文件时:

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

发生以下错误:

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

问题

如何在sass处理器配置中包含文件夹node_modules/@material

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
}

2 个答案:

答案 0 :(得分:2)

告诉webpack / sasss-loader应该将@import路径解析为node_module而不是本地文件,你必须添加一个代字号:

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

所以这与vue-loader无关,但是一般的sass-loader-pitfall。

编辑:如此css lib的文档中所述:

  

注意:组件&#39; Sass文件期望包含@material范围文件夹的node_modules目录存在于Sass包含路径中。

所以我们必须为sass-.loader / node-sass添加inlcudePaths:

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')
}

答案 1 :(得分:0)

您是否安装了各个组件?

npm install --save @material/button @material/card @material/textfield @material/typography