【问题标题】:Using SASS with ReactJS and Webpack将 SASS 与 ReactJS 和 Webpack 一起使用
【发布时间】:2018-04-08 11:39:20
【问题描述】:

在让 Sass 与我的 React 设置一起工作时,我遇到了难以置信的困难。我已经安装了css-loadersass-loaderstyle-loader,我看到它们是需要的。我还安装了extract-text-webpack-plugin,它将.scss 转换为.css。目前,我关心这些文件:

index.js

import React from 'react'
import ReactDOM from 'react-dom'

import App from './app.jsx'
require('./app.scss');

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

app.scss

@import 'styles/container.scss'

container.scss (./styles/container.scss)

body {
    color: green;
}

webpack.config.js

const path = require("path")
const webpack = require("webpack")
const ExtractTextPlugin = require("extract-text-webpack-plugin")

module.exports = {
    entry: './index.js',
    output: {
        filename: 'bundle.js'
    },
    plugins: [
        new ExtractTextPlugin({ filename: 'app.css', allChunks: true })
    ],
    module: {
        rules: [
            { test: /\.jsx?/, loader: 'babel-loader' },
            {
  test: /\.css$/,
  include: /node_modules/,
  exclude: /app/,
  loaders: ['style-loader', 'css-loader'],
}, {
  test: /\.s[ac]ss$/,
  exclude: /node_modules/,
  use: ExtractTextPlugin.extract({
    fallback: 'style-loader',
    use: ['css-loader', 'sass-loader']
  })
}
        ]
    },
    devServer: {
        contentBase: path.join(__dirname, "."),
        port: 9000
    }
}

当我使用 Webpack 捆绑它时,它运行良好并创建了“app.css”文件,但样式并未应用于 React 组件。使用 dev webpack 服务器,开发者工具给了我这个错误:

./app.scss
Module parse failed: Unexpected character '@' (1:0)
You may need an appropriate loader to handle this file type.

这可能是我缺乏 React 知识,或者此设置所需的任何其他东西。谁能告诉我为什么 Sass 不能正常工作?

【问题讨论】:

    标签: node.js reactjs npm webpack sass


    【解决方案1】:

    我不熟悉您提到的 extract-text-webpack-plugin,但是要在 Webpack 中设置 sass 加载器,我会这样做:

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

    请注意,您需要 sass-loader、css-loader 和 style-loader。

    有了这个,您可以将您的 SCSS 文件导入为 require('./app.scss') 或导入 './app.scss',如果您使用的是 es6。

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-02
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-19
      相关资源
      最近更新 更多