我正在尝试通过一个简单的练习项目来解决Webpack文件加载器的问题。
我在icon.png
中放入了./src
,以及index.js
和style.css
(按照https://webpack.js.org/guides/asset-management/)。
运行webpack(通过yarn build or watch scripts
)后,我没有收到任何错误,实际上在a0cadc7b7cbb7dd92495c1d9567c52e7.png
中得到了一个名为./dist
的文件。
但是,在dev-tools(dista0cadc7b7cbb7dd92495c1d9567c52e7.png
)中检查时,结果包所引用的文件是不同的,因此根本不会加载。
这真令人困惑……有解决此问题的想法吗?
webpack.config.js
const path = require("path");
module.exports = {
mode: 'development',entry: './src/index.js',output: {
filename: 'bundle.js',path: path.resolve(__dirname,'dist'),publicPath: 'dist',},module: {
rules: [
{
test: /\.css$/,use: [
'style-loader','css-loader'
],{
test: /\.(png|jpg|svg|gif)$/,use: [
'file-loader'
],],};
index.js
import sayHello from './hello';
import './style.css';
import icon from './icon.png';
sayHello();
function component() {
const element = document.createElement("div");
element.innerHTML = "Hello from webpack!";
element.classList.add("hello");
const myIcon = new Image();
myIcon.src = icon;
element.appendChild(myIcon);
return element;
}
document.body.appendChild(component());
style.css
.hello {
color: red;
background-image: url('./icon.png');
}
也: package.json
{
"name": "webpack-practice","version": "1.0.0","main": "index.js","scripts": {
"build": "webpack --progress -p","watch": "webpack --progress --watch","server-c9": "webpack-dev-server --host 0.0.0.0 --port 8080 --progress"
},"license": "MIT","private": true,"devDependencies": {
"css-loader": "^3.4.0","file-loader": "^5.0.2","style-loader": "^1.1.2","webpack": "^4.41.5","webpack-cli": "^3.3.10","webpack-dev-server": "^3.10.1"
}
}
更新:
我在publicPath
中注释了webpack.config.js
并使其正常工作...但是没有,我失去了webpack-dev-server中的Live Reloading ...现在,这是我遇到这种意外行为的第一个主题。