您需要在 webpack.config.js
中使用 style-loader 和 css-loader
首先,通过 npm 安装这两个包:
npm install style-loader, css-loader --dev
然后,在您的 src 文件夹中创建一个 styles.css 并将以下样式附加到文件中(仅用于演示目的,因此您知道它可以正常工作):
body {
background-color: #ff4444;
}
不要忘记在 src/index.js 中导入 css 文件:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.js';
import './styles.css'; // <- import the css file here, so webpack will handle it when bundling
ReactDOM.render(<App />, document.getElementById('app'));
并在你的 webpack.config.js 中使用 style-loader 和 css-loader:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: { loader: 'babel-loader' },
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
}),
],
};
如果你没有看到正确的输出,你可能需要再次重启 webpack 开发服务器。我已经克隆了你的 repo 并进行了我上面提到的更改,它有效。
至于ExtractTextPlugin,您将在捆绑生产构建时需要它,您可以从他们的Repo 了解更多信息
希望对你有帮助!