使 webpack 5 资产加载器与 webpack-dev-server 一起工作

问题描述

我的项目结构是

├──images  
|  └─cat.jpg
├──components
|  └─App.jsx
├──webpack.prod.js
├──webpack.dev.js

在 webpack.dev,dev-server 设置中我有 contentBase: path.resolve(__dirname,'images')

在 webpack.prod 中:

rules: {  
           test: /\.jpg/,type: 'asset/resource',},

现在,如果我尝试将我的图像在 App.jsx 中显示<img src='cat.jpg'/>,那么它可以在 dev 中运行,但不能在 prod 中运行 404。这是有道理的,因为我没有导入图像,而且 webpack 没有在包中“看到”它,而 contentBase 只是开发者。

我也试过

import cat from '../images/cat.jpg';
...
      <img src={cat}></img>

但这在 prod 中有效,但在 dev 中崩溃,这也是有道理的,因为 dev 中没有资产加载器。我也可以在 dev 中添加加载器,但我觉得这违背了具有 contentBase 设置的目的,然后可以完全删除

所以我的问题是:是否可以在 dev 中使用 contentBase 来显示图像,而只在 prod 中使用资产加载器?感觉它应该以某种方式......

谢谢!

解决方法

我没有在我的 webpack 上在 Failed building wheel for cryptacular Running setup.py clean for cryptacular Failed to build cryptacular Installing collected packages: cryptacular Running setup.py install for cryptacular ... error Complete output from command /home/saves/savespy3/bin/python3 -u -c "import setuptools,tokenize;__file__='/tmp/pip-install-jru69lmn/cryptacular/setup.py';f=getattr(tokenize,'open',open)(__file__);code=f.read().replace('\r\n','\n');f.close();exec(compile(code,__file__,'exec'))" install --record /tmp/pip-record-v8w0pkm2/install-record.txt --single-version-externally-managed --compile --install-headers /home/saves/savespy3/include/site/python3.7/cryptacular: scons: Reading SConscript files ... scons: done reading SConscript files. scons: Building targets ... scons: *** Do not know how to make File target `install' (/tmp/pip-install-jru69lmn/cryptacular/install). Stop. scons: building terminated because of errors. 处使用 contentBase。但它同时适用于开发和生产,如下所示:

结构

devServer

网络包

├──images  
|  └─logo.png
├──components
|  └─App.jsx

App.jsx

...
output: {
  ...
  assetModuleFilename: 'images/[hash][ext][query]'
},module: {
  rules: {
    test: /\.(?:ico|gif|png|jpg|jpeg)$/i,type: 'asset/resource'
  },...
,

我在 Electron 中使用 webpack 5 时也遇到了这个问题,assetModuleFilename: 'images/[hash][ext][query]' 对我来说并不完全适用。尝试将导入演示从 './assets/demo.png' 导入 * 作为演示从 './assets.png'。终于成功了