[英]webpack: SASS loader fails “Module build failed (from ./node_modules/sass-loader/lib/loader.js)”
I've been trying to use sass-loader
on webpack v4, but it fails to load scss
files in a React
component with TypeScript
. 我一直在尝试在webpack v4上使用
sass-loader
,但是它无法使用TypeScript
在React
组件中加载scss
文件。
Here is a simplified snippet of the code. 这是代码的简化片段。
//index.tsx
import * as React from 'react';
import './styles.scss';
const Navigation = () => {
return (<div className="app-bar"></div>)
}
//styles.scss
.app-bar {
background-color: #2196f3;
}
The following code is from my webpack config. 以下代码来自我的webpack配置。
module: {
rules: [
//loaders for jsx, tsx etc
{
test: /\.(css|scss)$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: true
}
},
{ loader: 'sass-loader' }
]
}]
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
new CleanWebpackPlugin(),
]
I followed the official doc's example , but it fails to load the styles.scss
. 我遵循了官方文档的示例 ,但是无法加载
styles.scss
。
Just in case, I re-installed style-loader
, css-loader
, sass-loader
(and node-sass
), but it didn't solve the error. 以防万一,我重新安装了
style-loader
, css-loader
, sass-loader
(和node-sass
),但是并没有解决错误。
The error message is ... 错误消息是...
Module build failed (from ./node_modules/sass-loader/lib/loader.js):
模块构建失败(来自./node_modules/sass-loader/lib/loader.js):
I'm running webpack via Laravel Mix
, but don't know if Laravel has anything to do with it. 我正在通过
Laravel Mix
运行webpack,但是不知道Laravel是否与此有关。
What caused this issue? 是什么引起了这个问题? Any advice will be appreciated.
任何建议将被认真考虑。
You dont need to put css in the test section because the sass-loader and css-loader will take care for you and it will transform your scss to css file 您无需将css放在test部分中,因为sass-loader和css-loader将为您服务,并将您的scss转换为css文件
Below is my config 下面是我的配置
{
test: /\.scss$/,
use: [
//'style-loader' was the culprit, so I just needed to remove it
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
minimize: true,
sourceMap: true
}
},
{
loader: "sass-loader"
}
]
I seem to remember having the same issues with webpack. 我似乎记得webpack也有同样的问题。 I switched from SASS to Styled Components, it's a css-in-js library.
我从SASS切换到样式化组件,这是一个css-in-js库。 I was wary at first but it's great.
刚开始我很警惕,但这很棒。
https://www.styled-components.com/ https://www.styled-components.com/
It allows you to change CSS styles programmatically using React props. 它允许您使用React道具以编程方式更改CSS样式。 For example if I want to change the opacity of a menu when a button is clicked I can do it like this:
例如,如果我想在单击按钮时更改菜单的不透明度,则可以这样做:
opacity: ${props => (props.menuOpen ? 1 : 0)};
That's just one benefit, check the docs to see others. 那只是一个好处,请查看文档以查看其他内容。 I find using React with styled-components is a great way to work.
我发现将React与样式化组件一起使用是一种很好的工作方式。 You have your JS, CSS and HTML all being generated in one place.
您可以在一处生成JS,CSS和HTML。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.