我正在使用Webpack 3.如果我在CSS中设置背景图像,它可以正常工作:
body {
background: url('./img/1.jpg');
}
然而,当我使用JavaScript做同样的事情时,图像不会出现在页面上,我收到错误:
const body = document.querySelector('body');
body.style.backgroundImage = 'url("./img/1.jpg")';
Failed to load resource: the server responded with a status of 404 (Not Found)
我认为这是因为文件加载器识别CSS中的图像资源而不是我的JavaScript。它是否正确?如果是这样,我该如何解决?
这是我的webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: './src/script.js',
devServer: {
contentBase: './dist'
},
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'Swipe time'
})
],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
}
]
}
};
答案 0 :(得分:0)
我已经开始工作但是将图像作为变量导入。
import Image from './img/1.jpg';
const body = document.querySelector('body');
body.style.backgroundImage = `url(${Image})`;