如何在webpack中的index.js中包含sass文件?

时间:2017-05-01 19:24:17

标签: webpack

这是我的webpack配置文件

var path = require('path');
var MDC_DIR = path.resolve(__dirname, 'node_modules', '@material');

module.exports = {
    entry: "./index.js",
    output: {
        path: __dirname,
        filename: "bundle.js"
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                loader: "babel-loader",
            },
            {
                test: /\.scss$/,
                loader: "sass-loader!style-loader!css-loader",
                include: [
                    MDC_DIR
                ],
            }
        ],
    }
};

这是我的index.js文件

import * as mdc from 'material-components-web';
require('material-components-web/material-components-web.scss');

当我运行webpack时,它会抛出以下错误:

ERROR in ./~/material-components-web/material-components-web.scss
Module parse failed: /Users/Me/project/mdc-babel-attempt/node_modules/material-components-web/material-components-web.scss Unexpected character '@' (17:0)
You may need an appropriate loader to handle this file type.
| //
|
| @import "@material/animation/mdc-animation";
| @import "@material/button/mdc-button";
| @import "@material/card/mdc-card";
 @ ./index.js 9:0-63

这让我觉得它没有通过装载机。

我甚至试过require('sass-loader!style-loader!css-loader!material-components-web/material-components-web.scss');没有运气:

ERROR in ./~/sass-loader/lib/loader.js!./~/style-loader!./~/css-loader!./~/material-components-web/material-components-web.scss
Module build failed:
//
^
      Invalid CSS after "...load the styles": expected 1 selector or at-rule, was "var content = requi"
      in /Users/Me/project/mdc-babel-attempt/node_modules/material-components-web/material-components-web.scss (line 1, column 1)
 @ ./index.js 9:0-99

现在试图这样做一个星期,请帮忙。提前谢谢。

1 个答案:

答案 0 :(得分:1)

您在规则中包含的MDC_DIR与实际模块不匹配。该模块为material-components-web(就像导入它和错误一样),但您只应用@material的规则。您可以完全删除include选项,因为您始终需要处理Sass文件才能将它们与webpack一起使用。

另一个问题是您的加载程序订单错误。在你的情况下,加载器以相反的顺序(从右到左)应用:

css-loader -> style-loader -> sass-loader

您肯定希望在sass-loader之前应用css-loader,因为它会将Sass转换为CSS,否则在任何无效CSS的Sass语法上都会出错。即使您只使用CSS语法(没有额外的Sass功能),您也会收到错误,因为style-loader会将CSS转换为JavaScript,并且会传递给sass-loadersass-loader期望Sass和JavaScript不是有效的Sass语法,因此会抛出错误。

你的规则应该是:

{
    test: /\.scss$/,
    loader: "style-loader!css-loader!sass-loader",
}

或者使用更好的webpack 2语法:

{
    test: /\.scss$/,
    use: ["style-loader", "css-loader", "sass-loader"],
}