gpt4 book ai didi

css - 无法在 react 中导入css文件

转载 作者:行者123 更新时间:2023-12-02 11:19:48 25 4
gpt4 key购买 nike

在 App.js 中,我想导入 App.css 文件或任何 css 文件。 import './App.css'在这里不起作用并给出错误“./src/shared/App.css 1:0 中的错误”
模块解析失败:意外 token (1:0)您可能需要适当的加载程序来处理此文件类型,目前没有配置加载程序来处理此文件。见 https://webpack.js.org/concepts#loaders "
目录结构 -

 1. public
- bundle.js
2. src
- browser (folder) > index.js
- server (folder) > index.js
- server (folder) > App.js , App.css
这是我的 webpack.config.js 文件 -

var path = require('path')
var webpack = require('webpack')
var nodeExternals = require('webpack-node-externals')
var combineLoaders = require('webpack-combine-loaders');

var browserConfig = {
entry: './src/browser/index.js',
output: {
path: path.resolve(__dirname, 'public'),
filename: 'bundle.js',
publicPath: '/'
},
module: {
rules: [
{ test: /\.(js)$/, exclude: /node_modules/, use: ['babel-loader']},
{
test: /\.css$/,
exclude: /node_modules/,
loader: combineLoaders([
{
loader: 'style-loader'
}, {
loader: 'css-loader',
query: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
},
])
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx', '.css']
},
mode: 'production',
plugins: [
new webpack.DefinePlugin({
__isBrowser__: "true"
})
]
}

var serverConfig = {
entry: './src/server/index.js',
target: 'node',
externals: [nodeExternals()],
output: {
path: __dirname,
filename: 'server.js',
publicPath: '/'
},
mode: 'production',
module: {
rules: [
{ test: /\.(js)$/, exclude: /node_modules/, use: ['babel-loader']},
{
test: /\.css$/,
exclude: /node_modules/,
loader: combineLoaders([
{
loader: 'style-loader'
}, {
loader: 'css-loader',
query: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
}
])
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx', '.css']
},
plugins: [
new webpack.DefinePlugin({
__isBrowser__: "false"
})
]
}

module.exports = [browserConfig, serverConfig]

最佳答案

要在 ReactJS 元素中加载 CSS 文件,请为 ReactJS 安装 css-loader ...

npm install --save-dev style-loader css-loader
另外,请务必修改您的 webpack.config.js 文件,该文件位于我的元素中: ./node_modules/webpack-dev-server/client/webpack.config.js .你需要添加加载器,看起来像......
module.exports = {
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loaders: 'babel', query: { presets: ['react', 'es2015', 'stage-1'] } },
{ test: /\.css$/, loader: "style-loader!css-loader" }
]
},
...
}
最后,确保您在 webpack.config.js 中有 CSS 的解析规则...
resolve: {
extensions: ['', '.js', '.css',...]
}

关于css - 无法在 react 中导入css文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62933838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com