相信我,我一直在梳理 Stackoverflow 过去的问题,看看是否有解决方案可以解决我的问题,但是没有运气。
这里正在尝试将两个文件导入到React应用(css和scss)中。这些文件位于 node_modules 目录中。
如果使用 @ 参数导入它,它将显示错误未知令牌
@import '~react-toastify/dist/ReactToastify.css';
@import '~react-toastify/dist/main.scss';
如果按照下面的代码导入时没有 @ 参数,它将显示错误找不到模块。无法解决
import '~react-toastify/dist/ReactToastify.css';
import '~react-toastify/dist/main.scss';
在我的webpack配置中。我已经设置了扩展解析
resolve: {
extensions: ['.js', '.jsx', '.css', '.scss']
},
获取CSS和CSS的文件名,但无法正常工作
这是我完整的 webpack配置文件。
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.jsx',
output: {
path: path.resolve('dist'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.jsx', '.css', '.scss']
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-3']
}
}
]
},
plugins: [new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
inject: 'body'
})],
devServer: {
port: 4200,
historyApiFallback: true
},
externals: {
// global app config object
config: JSON.stringify({
apiUrl: 'http://localhost'
})
}
}
这是 package.json 文件
{
"name": "importing css example",
"version": "1.0.0",
"repository": {
"type": "",
"url": ""
},
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --open"
},
"dependencies": {
"history": "^4.6.3",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-redux": "^5.0.5",
"react-router-dom": "^4.1.2",
"react-toastify": "^4.4.0",
"redux": "^3.7.2",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.2.0"
},
"devDependencies": {
"babel-core": "^6.21.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"babel-preset-stage-3": "^6.24.1",
"html-webpack-plugin": "^2.26.0",
"path": "^0.12.7",
"webpack": "^3.6.0",
"webpack-dev-server": "^2.8.2"
}
}
答案 0 :(得分:0)
您的Webpack配置缺少用于加载CSS或CSS扩展样式的加载器。由于您尚未为具有CSS或SCSS扩展名的文件(可能是您的情况)指定了任何加载程序,因此默认情况下,webpack会将其视为JS。还可以如下修改webpack配置中的模块加载规则:
module:{
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-3']
}
},
{
test: /\.(s?)css$/,
use: [
"style-loader",
"css-loader",
"sass-loader"
]
}]
}
将上述代码添加到webpack配置中,然后尝试加载scss或css文件。希望能帮助到你。 :)