javascript - 如何让 webpack 将我的 assets/image/ 捆绑到组件中,尽管我从 url 调用它们
问题描述
Webpack 正在复制png,jpg,svg
导入到每个组件文件中的静态文件。
托管图像的文件,它是固定的,路径是静态的。
组件文件是这样的: mycomponent.ts
import img from 'assets/img/aa.png
.... <img src={img} alt="" />
下面是一个更复杂的案例。
- 从 url 导入图像:
import imgurl from ${url}
- 将其用于
<img src={imgurl} />
- 和 webpack,仍然将图像移动到
static
文件夹中!(这是我的目标)
我需要 webpack 做什么: .
- 捆绑图像
assets/img
并将它们移动到static/img
,就好像图像是从 导入的assets/img
,而不是 url。 - 到目前为止,webpack 忽略了从url导入的图像,可能是因为它在构建过程中找不到它们
- 但是当我使用以下方法伪造
js & css
输出时publicPath
: config.output.publicPath =http://www...
;,
同样可以为图像完成吗?
到目前为止的捆绑图像片段:
// so, this changes copy the imported, into react components, images, into
// static/media
// but it copies ONLY the images that are imported from `assets/img`
// it ignores if i import an image from a url e.g. import img from ${url}
function addMedia(config, outputPath){
const media = {
test: /\.(woff(2)?|ttf|eot|svg|png)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[hash:8].[ext]',
outputPath: 'static/media',
}
}
]
};
config.module.rules.push( media );
}
所以我想知道是否有办法将图像从assets/img
-->捆绑/复制static/media
到反应文件中,我从 url 导入它们?
解决方案
您可以使用copy-webpack-plugin
来复制图像assets/img
,static/media
如下所示:
const CopyPlugin = require("copy-webpack-plugin");
module.exports = {
plugins: [
new CopyPlugin({
patterns: [
{ from: "assets/img", to: "static/media" }
],
options: {
concurrency: 100,
},
}),
],
};
文档copy-webpack-plugin
:https ://webpack.js.org/plugins/copy-webpack-plugin/
推荐阅读
- javascript - 如何在 Javascript 中的一个函数中返回两个函数 - NodeJS 和 ExpressJS
- templates - In HUGO - 如何读取模板中的查询参数
- android - UI 线程的几个处理程序
- html - 用页面高度增加 div 高度
- android - 如何从页面底部到页面顶部?
- javascript - Javascript如何记录应该是特定类型的对象的变量
- delphi - delphi TIdUdpClient接收数据的问题
- android - 在特定设备上加载本机库时找不到符号
- python - 在 django rest 框架中通过 Browsable Api 添加文件
- laravel - 如何在刀片 laravel 中显示数据库中的照片