How can I read the configuration file (e.g. mypkg.config.ts
) from the root of the project in my npm module built on ESM?
I found this, and figured out how to do it for .json
, but not for .ts
.
CodePudding user response:
After a few hours of searching, I found what I needed in the sources of vite.
All you have to do is convert your config file into js using esbuild for example, and then import it using
const config = await import(`file://${absolutePathToTranspiledConfig}`)
And then just delete the generated js file.
EDIT: Specifically `vite' uses the following transpilation script:
await build({
entryPoints: [/*path to config with .ts extension*/],
bundle: true,
minify: true,
platform: 'node',
outfile: /*path to transpiled config*/,
sourcemap: 'inline',
metafile: true,
format: 'esm',
plugins: [
{
name: 'externalize-deps',
setup(build) {
build.onResolve({ filter: /.*/ }, args => {
const id = args.path
if (id[0] !== '.' && !path.isAbsolute(id)) {
return {
external: true
}
}
})
}
},
{
name: 'replace-import-meta',
setup(build) {
build.onLoad({ filter: /\.[jt]s$/ }, async args => {
const contents = await fs.readFile(args.path, 'utf8')
return {
loader: args.path.endsWith('.ts') ? 'ts' : 'js',
contents: contents
.replace(
/\bimport\.meta\.url\b/g,
JSON.stringify(`file://${args.path}`)
)
.replace(
/\b__dirname\b/g,
JSON.stringify(path.dirname(args.path))
)
.replace(/\b__filename\b/g, JSON.stringify(args.path))
}
})
}
}
]
})
However, I can't understand the meaning of these plugins here