简体   繁体   中英

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.

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.

// 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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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