我想将一个纯 css 文件导入到我的 React Web 应用程序中,到目前为止我已经尝试过这种方式:
在我的 index.tsx 中我有:
import * as React from "react"
import '../assets/styles.css';
在我的 webpack.config.js 中我有:
var webpack = require("webpack");
var path = require("path");
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: [
"./src/index.tsx"
],
output: {
filename: "bundle.js",
publicPath: "/",
path: path.resolve(__dirname, "dist")
},
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
new ExtractTextPlugin('app.css')
],
module: {
rules: [
// All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
{ test: /\.tsx?$/, use: ["awesome-typescript-loader"] },
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{ test: /\.js$/, enforce: "pre", use: "source-map-loader" }
],
loaders: [ {
test: /\.js|.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
}, {
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
},
{ test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') }
]
}
};
错误:
ERROR in ./src/assets/styles.css Module parse failed: Unexpected character '@' (1:11) You may need an appropriate loader to handle this file type.
我是否也可以直接从 index.html 引用样式?如果是这样,我将如何引用我的 styles.css?我已经尝试过这样的事情:
但这是行不通的,我不知道 styles.css 的路径是什么,你在我的目录中将它作为 src/assets/styles.css。
最佳答案
您需要将此添加到您的规则中:
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
]
}
关于javascript - 无法在 React Web App 中导入 css 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52910571/