Halkichi
Halkichi

Reputation: 65

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?

Upvotes: 2

Views: 4970

Answers (2)

Halkichi
Halkichi

Reputation: 65

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
}

Upvotes: 2

Alex Fallenstedt
Alex Fallenstedt

Reputation: 2093

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

Upvotes: 2

Related Questions