首页 > 解决方案 > 如何让 webpack 将我的 assets/image/ 捆绑到组件中,尽管我从 url 调用它们

问题描述

Webpack 正在复制png,jpg,svg导入到每个组件文件中的静态文件。
托管图像的文件,它是固定的,路径是静态的。

组件文件是这样的: mycomponent.ts


import img from 'assets/img/aa.png

.... <img src={img} alt="" />

下面是一个更复杂的案例。

  1. 从 url 导入图像:import imgurl from ${url}
  2. 将其用于<img src={imgurl} />
  3. 和 webpack,仍然将图像移动到static文件夹中!(这是我的目标)

我需要 webpack 做什么: .


  1. 捆绑图像assets/img并将它们移动到static/img,就好像图像是从 导入的assets/img,而不是 url。
  2. 到目前为止,webpack 忽略了从url导入的图像,可能是因为它在构建过程中找不到它们
  3. 但是当我使用以下方法伪造js & css输出时publicPathconfig.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 导入它们

标签: javascriptnode.jsreactjswebpackwebpack-4

解决方案


您可以使用copy-webpack-plugin来复制图像assets/imgstatic/media如下所示:

const CopyPlugin = require("copy-webpack-plugin");

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        { from: "assets/img", to: "static/media" }
      ],
      options: {
        concurrency: 100,
      },
    }),
  ],
};

文档copy-webpack-pluginhttps ://webpack.js.org/plugins/copy-webpack-plugin/


推荐阅读