关于node.js:具有Webpack,React和Babel的Sass-loader无法正常工作

Sass-loader with Webpack, React and Babel not working

我为代码繁重的帖子表示歉意。

我既是Node,React和Webpack的新手,也是第一次使用sass-loader。 我遇到了一些看似微不足道的问题,但并非如此。

ERROR in ./app/index.js Module not found: Error: Can't resolve
'waterbottle.scss' in '/Volumes/500GB/Webs/waterbottle/app' @
./app/index.js 4:13-40

我尝试将.scss文件放置在app文件夹中,以及摆弄.scss路径。

安装:

我安装了sass-loader

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

webpack.config.js看起来像这样

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var path = require('path');
var webpack = require('webpack');
var HTMLWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
    template: __dirname + '/app/index.html',
    filename: 'index.html',
    inject: 'body'
});

module.exports = {
    entry: __dirname + '/app/index.js',
    module: {
        loaders: [
            {
                test: /\\.js$/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ],
        rules: [
            {
                test: /\\.scss$/,
                use: ['style-loader', 'css-loader', 'sass-loader']
            }
        ]
    },
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: 'app.build.js'
    },
    plugins: [HTMLWebpackPluginConfig],
    stats: {
        colors: true
    },
    devtool: 'source-map',
    watch: true
};

package.json将其包含在devDependencies中

1
"node-sass":"^4.5.3",

index.js包含

1
const scss = require("waterbottle.scss");

文件结构:

enter image description here

我的理解是,sass-loader应该自动将CSS注入dom。 提前谢谢了。


Sass loader文档显示如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// webpack.config.js

module.exports = {
    ...
    module: {
        rules: [{
            test: /\\.scss$/,
            use: [{
                loader:"style-loader" // creates style nodes from JS strings
            }, {
                loader:"css-loader" // translates CSS into CommonJS
            }, {
                loader:"sass-loader" // compiles Sass to CSS
            }]
        }]
    }
};

解决了。 我需要安装:

1
2
npm install style-loader --save
npm install css-loader --save

以及.scss文件的路径:

1
const scss = require("../scss/waterbottle.scss");

我很好奇为什么在sass-loader网站上没有提到它,或者更好的是为什么它在运行时自动安装

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