简体   繁体   English

从 JSON 文件中的 src 动态创建导入语句,用于 webpack 构建

[英]Dynamically create import statements from src's inside a JSON file for webpack build

I have an example JSON file like the following:我有一个示例 JSON 文件,如下所示:

menu.json菜单.json

{
  "0":{
      "img":"./101 cup noodles.png"
  },
  "1":{
      "img":"./102 cup noodles with beef.png"
  },
  "2":{
      "img":"./103 cup noodles with egg.png"
  },
  "3":{
      "img":"./104 cup noodles with shrimp.png"
  }
}

Is there any way to dynamically create import statements for each of the image links inside the JSON file for webpack to build?有什么方法可以为 JSON 文件中的每个图像链接动态创建导入语句,以供 webpack 构建?

I would like to avoid having to write an individual import for each image at the top of my javascript file especially if there are hundreds of items.我想避免在我的 javascript 文件顶部为每个图像编写单独的导入,尤其是在有数百个项目的情况下。 Eg:例如:

menu.js菜单.js

import img0 from './101 cup noodles.png'
import img1 from './102 cup noodles with beef.png'
import img2 from './103 cup noodles with egg.png'
import img3 from './104 cup noodles with shrimp.png'

I have tried dynamically making the import statements with named fields and a for loop but learned that import statements need to be top level so unfortunately the following did not work:我尝试使用命名字段和 for 循环动态地制作导入语句,但了解到导入语句需要是顶级的,所以不幸的是,以下方法不起作用:

menu.js菜单.js

import data from './menu.json'

for (let i = 0; i < Object.keys(data).length; i++) {
    import ['img' + Object.keys(data)[i]] from data[i]['img'];
}

At the moment I am using the loop above to console log all of my import statements and just copy+pasting them into the top of my code but that seems extremely inelegant and I am wondering if there is a better way.目前我正在使用上面的循环来控制台记录我所有的导入语句,并将它们复制粘贴到我的代码顶部,但这似乎非常不雅,我想知道是否有更好的方法。

In this post you have a collection of strategies that may help you.在这篇文章中,您有一系列可能对您有所帮助的策略。 I would consider, to put all images in the same folder and write the path once for all.我会考虑将所有图像放在同一个文件夹中并一劳永逸地编写路径。

You can get the properties of the object with Object.keys , then map through the array and construct the string.可以通过 Object.keys 获取Object.keys的属性,然后通过数组获取 map 并构造字符串。

 const obj = { "0":{ "img":"./101 cup noodles.png" }, "1":{ "img":"./102 cup noodles with beef.png" }, "2":{ "img":"./103 cup noodles with egg.png" }, "3":{ "img":"./104 cup noodles with shrimp.png" } } const res = Object.keys(obj).map(e => `import ${Object.keys(obj[e])[0] + e} from '${obj[e].img}'`).join('\n') console.log(res)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM