reactjs - 无法在 reactjs 中使用 webpack 4 在 body 上加载背景图片
问题描述
在我的 react js 应用程序中,我想在主体上添加背景图像。当我在开发模式下工作时它工作正常,但在生产时它不工作。
对于生产,我使用单独的文件夹可能会产生一些路径问题。
这是我的scssdist
body {
font-family: Helvetica,Arial,sans-serif;
font-size: $m-size;
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
background-image: url(/images/bg4.png);
background-attachment: fixed;
background-repeat: no-repeat;
background-position: top;
background-size:cover;
}
我的webpack.config
module.exports = {
entry:{
vendor: VENDOR_LIBS,
main: './src/app.js',
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].bundle.js',
chunkFilename: '[name].bundle.js',
publicPath: '/',
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{ test: /\.bundle\.js$/, use: { loader: 'bundle-loader', options: {lazy: true} } },
{
test: /\.s?css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader?url=false',
options: {
sourceMap: true,
}
},
{
loader: 'sass-loader',
options: {
sourceMap: true
}
}
]
},{
test: /\.(gif|svg|jpg|png|ttf|eot|woff(2)?)(\?[a-z0-9=&.]+)?$/,
loader: "file-loader?name=[name].[ext]",
}
]
},
plugins: [
new CleanWebpackPlugin('dist', {} ),
new MiniCssExtractPlugin({
filename: 'style.[contenthash].css',
}),
new HtmlWebpackPlugin({
inject: true,
hash: true,
template: './src/index.html',
filename: 'index.html',
favicon: './public/images/fav.ico'
}),
new WebpackMd5Hash(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
],
optimization: {
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
chunks: 'all',
minChunks: 2
},
}
},
runtimeChunk: true,
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: true,
uglifyOptions: {
compress: {
inline: false
}
}
}),
new OptimizeCSSAssetsPlugin({})
],
},
};
webpack 将其他图像生成到base64中,但不适用于此图像。并且它在dist
文件夹中不可用。
任何人都可以帮助我,我搜索了很多问题但无法解决。
我不希望任何外部链接加载图像。
解决方案
在生产中,您的当前目录将更改为,/dist/index.html
这就是您用于开发的路径/images/bg4.png
找不到文件的原因。
解决方案是将静态图像文件(如背景)/dist
复制到构建过程中的文件夹中。
假设您的项目目录类似于以下内容:
...
/images/bg4.png
package.json
然后将这些命令添加到您的 webpack 构建脚本中,以将图像复制到您的生产目录/dist
中。
// in package.json
"scripts": {
...
"build": "...your webpack build commands... && cp -a images\\. dist\\images",
...
},
您的新文件目录将如下所示
/dist/...your index.html, bundles, etc...
/images/bg4.png
/images/bg4.png
package.json
并且您的图像路径现在应该可以找到图像文件。
推荐阅读
- java - 如何从 android 中的 pom.xml 文件创建 gradle 依赖项?
- python - 如何将图像作为参数从 ac# 应用程序传递给 python 脚本,而无需从磁盘写入/读取它?
- css - 在 div 中添加元素会使其他元素消失
- reactjs - 如何使用 turfjs 和 mapbox js 从方形网格中选择和突出显示单元格?
- leaflet - 在传单中显示关系(轨迹)
- python - NEAT 的 TypeError
- python - tkinter框架内的网格?
- python - 过滤掉多维numpy数组中的行
- angular - 为什么会出现类型错误:对象可能为“空”?
- python-3.x - ?: (staticfiles.E002) 错误 STATICFILES_DIRS 设置不应包含 STATIC_ROOT 设置。如何解决这个错误?