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'
]
}
]
}
};
작동하지만 이미지를 변수로 가져옵니다.
import Image from './img/1.jpg';
const body = document.querySelector('body');
body.style.backgroundImage = `url(${Image})`;
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다