In this article, we will review how to load your config file regardless what module format it is, using bundle-require.
What is bundle-require?
bundleRequire usage in Tsup source code.
What is bundle-require?
Projects like Vite need to load config files provided by the user, but you can’t do it with just require()
because it's not necessarily a CommonJS module, it could also be a .mjs
or even be written in TypeScript, and that's where the bundle-require
package comes in, it loads the config file regardless what module format it is.
How it works
Bundle your file with esbuild,
node_modules
are excluded because it's problematic to try to bundle it__filename
,__dirname
andimport.meta.url
are replaced with source file's value instead of the one from the temporary output fileOutput file in
esm
format if possible (for.ts
,.js
input files)Load output file with
import()
if possibleReturn the loaded module and its dependencies (imported files)
Install
npm i bundle-require esbuild
Usage
import { bundleRequire } from 'bundle-require'
const { mod } = await bundleRequire({
filepath: './project/vite.config.ts',
})
bundleRequire usage in Tsup source code.
At line 70 in a file named load.ts in Tsup source code, you will find the below code:
const config = await bundleRequire({
filepath: configPath,
})
bundle-require is imported as shown below:
import { bundleRequire } from 'bundle-require'
config path is resolved using Joycon as shown below:
const configPath = await configJoycon.resolve({
files: configFile
? [configFile]
: [
'tsup.config.ts',
'tsup.config.cts',
'tsup.config.mts',
'tsup.config.js',
'tsup.config.cjs',
'tsup.config.mjs',
'tsup.config.json',
'package.json',
],
cwd,
stopDir: path.parse(cwd).root,
packageKey: 'tsup',
})
About me
Hey, my name is Ramu Narasinga. I study codebase architecture in large open-source projects.
Top comments (0)