-1

我无法弄清楚如何设置我的 webpack 以便能够在我的组件中使用 scss 模块,例如:

import styles from './ComponentStyles.scss'

到目前为止,我尝试将 webpack 配置为sass-loader一起使用,postcss-loader但没有运气:

  {
    test: /\.scss$/,
    loaders: [
      'isomorphic-style-loader',
      'css-loader?modules&localIdentName=[name]_[local]_[hash:base64:3]',
      'postcss-loader',
      'scss-loader'
    ]
  }

注意isomorphic-style-loader是我使用的库,而不是style-loader由于服务器渲染要求,在其 github 页面文档中,他们实际上使用带有 .scss 扩展名的 postcss-loader,但在我的情况下,如果我遵循他们的示例,则不会编译 scss。

4

1 回答 1

2

我不得不自己做一些修补,但最终落在了以下位置

包.json

"autoprefixer": "^6.3.1",
"css-loader": "^0.23.1",
"extract-text-webpack-plugin": "^1.0.1",
"node-sass": "^3.8.0",
"sass-loader": "^3.1.2",
"style-loader": "^0.13.0"

网络包配置

...
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const autoprefixer = require('autoprefixer');
...

const config = {
    ...
    postcss: [
        autoprefixer({
            browsers: ['last 2 versions']
        })
    ],
    plugins: [
        new ExtractTextPlugin('css/bundle.css'),
    ],
    module: {
        loaders: [
            {
                test: /\.scss$/,
                loader: ExtractTextPlugin.extract('style', 'css!postcss!sass')
            }
        ]
    }
    ...
};

引导程序.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import App from './app';
import style from './scss/style.scss';

ReactDOM.render(
    <App/>,
    document.getElementById('my-app')
);

对于那些感兴趣的人:这里发生的bootstrap.jsx是 webpack 入口点,通过导入我们的原始scss文件(通过相对路径),我们告诉 webpack 在构建过程中包含它。

此外,由于我们loader在配置 () 中为此文件扩展名指定了 a .scss,webpack 能够style.scss通过定义的加载器从右到左解析和运行它:sass --> post-css --> css.

然后,我们使用extract-text-webpack-plugin将编译后的 CSS 从bundle.js它通常所在的位置拉出,并将其放置在css/bundle.css相对于我们的输出目录的位置 () 中。

此外,extract-text-webpack-plugin在这里使用是可选的,因为它只会从 bundle.js 中提取 CSS 并将其放入单独的文件中,如果您使用服务器端渲染,这很好,但我也发现它在调试过程中很有帮助,因为我有一个scss我对编译感兴趣的特定输出位置。

如果您希望看到这一点,这里有一个使用它的小样板:https ://github.com/mikechabot/react-boilerplate

于 2016-06-25T02:11:46.417 回答