From f9644fe150f0ce988e27b64e51776e0abb6ac841 Mon Sep 17 00:00:00 2001 From: Dylan Piercey Date: Fri, 13 Oct 2023 10:57:48 -0700 Subject: [PATCH] perf: optimize check for cjs marko files in dev --- .changeset/weak-walls-kneel.md | 5 ++++ src/index.ts | 48 +++++++++++++--------------------- 2 files changed, 23 insertions(+), 30 deletions(-) create mode 100644 .changeset/weak-walls-kneel.md diff --git a/.changeset/weak-walls-kneel.md b/.changeset/weak-walls-kneel.md new file mode 100644 index 0000000..9825ed4 --- /dev/null +++ b/.changeset/weak-walls-kneel.md @@ -0,0 +1,5 @@ +--- +"@marko/vite": patch +--- + +Optimize check for if a Marko module is in a cjs package. diff --git a/src/index.ts b/src/index.ts index b1fbaa8..9dafb8a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -533,11 +533,7 @@ export default function markoPlugin(opts: Options = {}): vite.Plugin[] { } if (!query) { - if ( - !isBuild && - /[\\/]node_modules[\\/]/.test(id) && - getModuleType(id) === "cjs" - ) { + if (!isBuild && isCJSModule(id)) { // For Marko files in CJS packages we create a facade // that loads the module as commonjs. const { ast } = await compiler.compile(source, id, { @@ -818,34 +814,26 @@ function isEmpty(obj: unknown) { return true; } -function findPackageJson( - file: string, - root: string = process.cwd() -): string | null { - let currentDir = path.dirname(file); - while (currentDir !== root && currentDir.length > root.length) { - const pkgPath = path.join(currentDir, "package.json"); - if (fs.existsSync(pkgPath)) { - return pkgPath; +const cjsModuleLookup = new Map(); +function isCJSModule(id: string): boolean { + const modulePath = + /^.*[/\\]node_modules[/\\](?:@[^/\\]+[/\\])?[^/\\]+[/\\]/.exec(id)?.[0]; + if (modulePath) { + let isCJS = cjsModuleLookup.get(modulePath); + if (isCJS === undefined) { + const pkgPath = modulePath + "package.json"; + try { + const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8")); + isCJS = pkg.type !== "module" && !pkg.exports; + } catch { + isCJS = false; + } + cjsModuleLookup.set(modulePath, isCJS); } - currentDir = path.dirname(currentDir); + return isCJS; } - return null; -} -const moduleTypeMap = new Map(); -function getModuleType(file: string): "esm" | "cjs" { - const pkgPath = findPackageJson(file); - if (pkgPath) { - let moduleType = moduleTypeMap.get(pkgPath); - if (!moduleType) { - const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8")); - moduleType = pkg.type === "module" || pkg.exports ? "esm" : "cjs"; - moduleTypeMap.set(pkgPath, moduleType); - } - return moduleType; - } - return "esm"; + return false; } function stripVersionAndTimeStamp(id: string) {