Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: optimize check for cjs marko files in dev #88

Merged
merged 1 commit into from
Oct 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/weak-walls-kneel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@marko/vite": patch
---

Optimize check for if a Marko module is in a cjs package.
48 changes: 18 additions & 30 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, {
Expand Down Expand Up @@ -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<string, boolean>();
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<string, "esm" | "cjs">();
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) {
Expand Down