【问题标题】:How to make webpack bundle my assets/image/ although i call them from a url, into the component如何让 webpack 将我的 assets/image/ 捆绑到组件中,尽管我从 url 调用它们
【发布时间】:2021-12-08 14:05:50
【问题描述】:

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. 但是当我用publicPath 伪造js & css 输出时:config.output.publicPath = http://www...;,
    图像也可以这样做吗?

捆绑图片的sn-p,到目前为止:


// 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, althougt 到反应文件 我从一个 url 导入它们

【问题讨论】:

    标签: javascript node.js reactjs webpack webpack-4


    【解决方案1】:

    您可以使用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/

    【讨论】:

    • 嗨马里奥,谢谢,我知道 copy-webpack-plugin。不同之处在于 copy-webpack-plugin 复制所有文件夹,而其他功能仅将使用的图像复制到文件中。在我的情况下,这将是有用的。
    • 啊,我明白了。如果没有看到更多您的代码,我无法想象这是如何工作的。似乎导入位置仅在运行时解析,那么编译器/捆绑器/插件如何在构建时知道要复制哪些资产?
    • 是的,也许那是不可能的,我现在想不出任何其他的解决方案。但在我去copy-webpack-plugin 之前,我将探索条件导入,以便在构建时从本地获取图像,并在运行时获取 env.url...我们会看到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 2018-08-23
    • 1970-01-01
    相关资源
    最近更新 更多