From ab1279d03a2fb510c565eb49e17cd116c3145d2e Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Wed, 16 Feb 2022 10:54:08 -0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E2=9C=A8=20add=20`cwd`=20option?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I want to use esbuild-runner in contexts where the current directory is not the directory containing the package.json whose dependencies should be used to chose externals. This makes the location for package.json configurable. It's roughly equivalent to the `cwd` option from ts-node: https://github.com/TypeStrong/ts-node/blob/abc616ece2a8cdb066439a4e5c6fc7d493aa4612/src/index.ts#L191-L196. --- src/esbuild.ts | 36 ++++++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/src/esbuild.ts b/src/esbuild.ts index 4ad43c4..c76d10f 100644 --- a/src/esbuild.ts +++ b/src/esbuild.ts @@ -14,6 +14,7 @@ import cache from "./cache" export type TranspileOptions = { type: "bundle" | "transform" debug: boolean + cwd?: string esbuild?: CommonOptions & TransformOptions & BuildOptions } const defaultOptions: TranspileOptions = { type: "bundle", debug: false } @@ -26,18 +27,6 @@ const commonOptions: CommonOptions = { sourcemap: "inline", } -const pkgPath = path.resolve(".", "package.json") -let externals: string[] = [] -if (fs.existsSync(pkgPath)) { - const pkg = JSON.parse( - fs.readFileSync(pkgPath, { encoding: "utf-8" }) - ) as PackageJson - externals = [ - ...Object.keys(pkg.dependencies ?? {}), - ...Object.keys(pkg.devDependencies ?? {}), - ] -} - export const loaders: Record = { ".js": "js", ".mjs": "js", @@ -101,7 +90,6 @@ function _bundle( resolveDir: path.dirname(filename), loader: loaders[ext], }, - external: [...externals, ...(options?.esbuild?.external ?? [])], write: false, }) .outputFiles.map((f) => f.text) @@ -113,7 +101,27 @@ export function transpile( filename: string, _options?: Partial ): string { - const options: TranspileOptions = { ...defaultOptions, ..._options } + const pkgPath = path.resolve(_options?.cwd ?? ".", "package.json") + let externals: string[] = [] + if (fs.existsSync(pkgPath)) { + const pkg = JSON.parse( + fs.readFileSync(pkgPath, { encoding: "utf-8" }) + ) as PackageJson + externals = [ + ...Object.keys(pkg.dependencies ?? {}), + ...Object.keys(pkg.devDependencies ?? {}), + ] + } else if (_options?.cwd) { + throw new Error(`No package.json found in ${_options?.cwd}`) + } + const options: TranspileOptions = { + ...defaultOptions, + ..._options, + esbuild: { + ..._options?.esbuild, + external: [...externals, ...(_options?.esbuild?.external ?? [])], + }, + } if (options.type == "bundle") { // eslint-disable-next-line no-console if (options.debug) console.log(`📦 ${filename}`)