我有一个带有索引的项目。 我正在使用WebPack将React代码捆绑在此项目中,但是它还包含一些骨干代码和其他我将随着时间的推移而替换的东西,因此CSS此刻需要保持链接。 我不是在我的React组件中导入此CSS文件。
当我编辑说,示例。我已经做了很多挖掘,似乎找不到解决方案。一切似乎都涉及将CSS导入到JS组件中。该项目的先前设置使用了咕unt声,这很容易完成。我想知道我是否需要两个过程。一个用于编译React代码,另一个是为了编译SCSS并生成新的CSS文件。
提前感谢!
您可以使用
html-bundler-webpack-plugin
。 该插件解决了直接在HTML中引用的资产的所有源文件,并确保生成的HTML包含WebPack处理后的正确输出资源URL。
,例如,有一个
<!doctype html>
<html lang="en">
<head>
<title>React App</title>
<!-- use relative path or webpack alias to source file -->
<link href="./images/favicon.ico" rel="shortcut icon" />
<!-- use relative path or webpack alias to source file -->
<link href="./scss/style.scss" rel="stylesheet" />
</head>
<body>
<div id="root"></div>
<!-- use relative path or webpack alias to source file -->
<script src="./index.jsx"></script>
</body>
</html>
Webpack配置:
const path = require('path');
const HtmlBundlerPlugin = require('html-bundler-webpack-plugin');
module.exports = {
mode: 'development',
output: {
path: path.join(__dirname, 'dist/'),
clean: true,
},
plugins: [
new HtmlBundlerPlugin({
entry: {
// add here your pages
index: './src/index.html', // => dist/index.html
},
js: {
filename: 'js/[name].[contenthash:8].js', // JS output filename
},
css: {
filename: 'css/[name].[contenthash:8].css', // CSS output filename
},
}),
],
module: {
rules: [
// compile to JS
{
test: /\.(m?js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: [['@babel/preset-react']],
},
},
},
// compile to CSS
{
test: /\.(scss)$/,
use: ['css-loader', 'sass-loader'],
},
// handles images
{
test: /\.(ico|png|jpe?g|svg)/,
type: 'asset/resource',
generator: {
filename: 'img/[name].[hash:8][ext]',
},
},
],
},
// enable live reload
devServer: {
static: path.join(__dirname, 'dist'),
watchFiles: {
paths: ['src/**/*.*'],
options: {
usePolling: true,
},
},
},
};
<!doctype html>
<html lang="en">
<head>
<title>React App</title>
<link href="img/favicon.edda23bf.ico" rel="shortcut icon" />
<link href="css/style.0859dc84.css" rel="stylesheet" />
</head>
<body>
<div id="root"></div>
<script src="js/index.0022c990.js"></script>
</body>
</html>
the是在stackblitz上使用webpack进行工作的示例。
P.S。您可以在github上创建一个仓库,然后我可以帮助您配置WebPack。