应用是通过“ create-react-app”命令创建的。 (通过webpack捆绑)JavaScript代码在我的React App中正常工作,但似乎没有从SASS获得任何样式。控制台或任何地方都没有错误,只是被忽略。要启动webpack,我正在运行“ npm run start”。 回购以防万一:https://github.com/ankeris/challengefriend
这是代码:
package.json
"scripts": {
"start": "webpack-dev-server --open --mode development --hot | react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"css-loader": "^1.0.0",
"html-webpack-plugin": "^3.2.0",
"node-sass": "^4.9.3",
"sass-loader": "^7.1.0",
"style-loader": "^0.22.1",
"webpack": "^4.17.1",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5"
}
webpack.config.js
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve('dist'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.scss$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
"sass-loader" // compiles Sass to CSS, using Node Sass by default
]
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
}
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import './styles/scss/index.scss';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
答案 0 :(得分:1)
应该是装载程序,因为您正在使用Webpack 4。
请在Webpack中添加以下规则,然后尝试
{
test: /\.scss$/,
loaders: ["style-loader", "css-loader", "sass-loader"]
}
答案 1 :(得分:1)
要使其工作,我遵循了此link,它告诉您如何在react-create-app
中添加css预处理程序,这是要运行的命令:
npm install --save node-sass-chokidar
npm install --save npm-run-all
然后将这些行添加到package.json
(在scripts
部分中):
"build-css": "node-sass-chokidar src/ -o src/",
"watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",
"start-js": "react-scripts start",
"start": "npm-run-all -p watch-css start-js",
"build-js": "react-scripts build",
"build": "npm-run-all build-css build-js",
在文件index.js
中将import './styles/scss/index.scss';
替换为import './styles/scss/index.css';
最后,您可以通过运行npm start
正如我在评论中所说,react-create-app
使用其自己的webpack配置,因此您的webpack.config.js
毫无用处,您可以将其从项目中删除
如果您确实要导入scss
文件,则需要修改默认的react-create-app
Webpack配置,您需要运行npm run eject
来提取配置,然后修改文件/config/webpack.config.{env}.js