1

I have a configuration object that I need to use in multiple files

const config = {test: true}

can I import the JSON and assign it directly to a variable or I need to create a new file and export a function that returns the object?

handsome
  • 2,335
  • 7
  • 45
  • 73
  • 3
    `export const config = {test: true}` and then `import { config } from "file.js"` – Jeremy Thille May 26 '21 at 06:19
  • 1
    Ultimately, it all depends on if you want the object to be mutable. The different export methods serve different purposes: you could export the object itself and use it as-is; or export a function that returns an original copy of the object if you want to reset it each time it's used; or pass the object through [`Object#freeze()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze). With the current object, you could call `config.test = false` in any file that consumes it and potentially cause problems elsewhere in your code. – samthecodingman May 26 '21 at 06:27

1 Answers1

3

You can export it like this -

const config = { test: true }
export default config

and then you can simply import like this -

import config from "filePath"

Or you can include an actual JSON-File like this:

config.json

{"test": true}

app.js

const config = require('./config.json');
// Do your operations