2

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?

Halkichi
  • 57
  • 5
  • What makes you think this works at all, let alone with JSON? – Aluan Haddad Feb 23 '20 at 05:16
  • I correct it a little words. I hope providing example can also work it. because the programming languages should be easier words. – Halkichi Feb 23 '20 at 05:23
  • Possible duplicate of [Is it possible to import modules from all files in a directory, using a wildcard?](https://stackoverflow.com/questions/29722270/is-it-possible-to-import-modules-from-all-files-in-a-directory-using-a-wildcard) – palaѕн Feb 23 '20 at 05:24
  • How about creating a helper function to get all data from json files instead of import them? – hoangdv Feb 23 '20 at 05:33
  • @hoangdv: Actually, helper function as what you said is good. – Halkichi Feb 23 '20 at 06:07

2 Answers2

2

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/"
Alex Fallenstedt
  • 2,040
  • 1
  • 18
  • 34
  • 2
    The second form is proper, the first isn't. – Aluan Haddad Feb 23 '20 at 05:42
  • Thank you for answer but your providing code doesn't work... I got an error msg [error TS1005: 'from' expected.] after compile within the upper code. and second code (export {default as a} from "./a.json") is no error msg. but some other js file provide console.log(a)//undefined – Halkichi Feb 23 '20 at 06:00
1

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
}
Halkichi
  • 57
  • 5