1

I'm trying to load a config inside a node module but I'm not sure which is a good practice to do it, I have this scenario:

A config my.config.js:

module.exports = {
  content: [
    './src/**/*.{tsx,ts}',
  ],
}

Then I have a module cli.mjs is supposed to load it:

import arg from 'arg'
import { readFile } from 'fs/promises'
import path from 'path'

let configPath = './my.config.js'

const args = arg({
  '--config': String,
  '-c': '--config',
})

if (args['--config']) {
  configPath = args['--config']
}

console.log(readFile(path.resolve(configPath), { encoding: 'utf8' }))

This will just return a simple string with my config inside, not a javascript object:

`
module.exports = {
  content: [
    './src/**/*.{tsx,ts}',
  ],
}
`

How should I load my config in the right way?

I've saw basically everyone use configs like that in TypeScript or CJS projects, but it's hard to me see how and where they parse these configs, probably I'm missing some basic information about this?

vitto
  • 19,094
  • 31
  • 91
  • 130
  • 2
    Why are are you writing your config file as a CJS module if you're otherwise using ECMAScript modules? – Quentin Jan 21 '22 at 16:18
  • I'm not used to work with node so probably this is not a good response, I would write it as CJS module cause I'll use it with postcss and I've saw the standard configs passed to it are CJS modules. – vitto Jan 21 '22 at 16:25
  • Have you read https://nodejs.org/api/esm.html#interoperability-with-commonjs? Don't read the configuration as a text file, but `import` or [`require`](https://nodejs.org/api/module.html#modulecreaterequirefilename) it. – Bergi Jan 21 '22 at 23:57

0 Answers0