[英]typescript/javascript: How to do it that import all json from specific dir
Now in trouble that I don't know how to work.现在陷入困境,我不知道如何工作。 I wanna to import all json from specific dir.
我想从特定目录导入所有 json。
import a from '../context/a.json'
import b from '../context/b.json'
import c from '../context/c.json'
↓ ↓
import {a, b, c} '../context/' // but like..This code doesn't work.
Is there how to fix it?有没有办法解决?
You could create an index.js
file in your context
directory which exports a, b, and c.您可以在导出 a、b 和 c 的
context
目录中创建一个index.js
文件。
// context/index.js
export {default as a} from "./a.json"
export {default as b} from "./b.json"
export {default as c} from "./c.json"
Then when you need to import it, you could do然后当你需要导入它时,你可以这样做
// some other js file
import { a, b, c} from "../context/index/"
Thank you for answer.谢谢你的答案。 I make in order toas much as possible easier understand file.
我为了尽可能容易理解文件而制作。 After all, creating a helper function to get all json from specific dir.
毕竟,创建一个辅助函数来从特定目录中获取所有 json。
import * as fs from 'fs'
const readPath = './context/'
interface TypeList {
[key: string]: string[] // adjusting require this in order to some json data type
}
export function DeclareEachJSON(): TypeList {
const fileNames = fs.readdirSync(readPath).filter(file => file.match(/\.json$/))
const typeList: TypeList = {}
fileNames.forEach((fileName: string)=> {
let typeName = fileName.match(/(^.*?)\.json/)
if(typeName){
typeList[typeName[1]] = JSON.parse(fs.readFileSync(readPath + fileName, 'utf8').toString())
}
})
return typeList
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.