按照文档抄的webpack.config.js配置,可是在浏览器打开html发现css可以被import进来,图片则没被加载
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: './src/index.js',
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']
}
]
}
};
目录结构
index.js
import './style.css';
import ys from './ys.jpg';
var element = document.createElement('div');
element.innerHTML = "导入图片和css";
element.classList.add('hello');
var myIcon = new Image();
myIcon.src = ys;
element.appendChild(myIcon);
document.body.appendChild(element)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>导入图片</title>
</head>
<body>
<script src="./dist/bundle.js"></script>
</body>
</html>
路径问题
webpack
默认publicPath=''
所以myIcon.src = ys;
编译后类似于myIcon.src = publicPath + '[hash].jpg';
output.path
是编译后文件存放路径(即 dist 目录),因此编译后的图片([hash].jpg
)是存放在这个目录下index.html
文件,相当于根目录是index.html
所在目录,而这个目录是没有图片文件的所以报 404 错误有两种解决方式:
设置 publicPath 为 dist (不推荐这样)
webpack-dev-server
相应的 html 改为<script src="bundle.js"></script>
,然后开启 server,访问 http://localhost:port/