【发布时间】:2019-04-22 05:51:42
【问题描述】:
在我的 react js 应用程序中,我想在 body 上添加 背景图片。当我在开发模式下工作时它工作正常,但在生产时它不工作。
对于生产,我使用 dist 单独的文件夹可能会造成一些路径问题。
这里我的 scss
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 文件夹后,您可以创建 dist/images/bg4.png 然后只运行您的服务器并查看它是否找到图像吗?如果是这样,我可以告诉你一个更永久的解决方案
-
我无法创建
dist/images/bg4.png,但应用程序中的其他图像生成并正常工作...... -
我不明白。您不能进入 dist 文件夹,创建一个名为 images 的文件夹,然后将 bg4.png 复制到其中进行测试吗?其他相对图像路径也可以用于生产,还是仅用于开发?
-
@ShawnAndrews 是的,在创建和粘贴图像后它工作正常,但是每当我需要构建新的生产代码时,每次都清理该文件夹。
标签: reactjs webpack sass webpack-4 webpack-style-loader