Skip to content

Commit

Permalink
Support comments & trailing commas in require/import package.json (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
Jarred-Sumner authored Apr 26, 2024
1 parent 7f0b810 commit 189aa22
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/fs.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1672,6 +1672,10 @@ pub const Path = struct {

pub fn isJSONCFile(this: *const Path) bool {
const str = this.name.filename;
if (strings.eqlComptime(str, "package.json")) {
return true;
}

if (!(strings.hasPrefixComptime(str, "tsconfig.") or strings.hasPrefixComptime(str, "jsconfig."))) {
return false;
}
Expand Down
2 changes: 1 addition & 1 deletion src/js/builtins/ImportMetaObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ export function internalRequire(this: ImportMetaObject, id) {
}

// TODO: remove this hardcoding
if (last5 === ".json") {
if (last5 === ".json" && !id.endsWith?.("package.json")) {
var fs = (globalThis[Symbol.for("_fs")] ||= Bun.fs());
var exports = JSON.parse(fs.readFileSync(id, "utf8"));
$requireMap.$set(id, $createCommonJSModule(id, exports, true, undefined));
Expand Down
29 changes: 29 additions & 0 deletions test/cli/run/require-and-import-trailing.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { test, expect, describe } from "bun:test";
import { bunEnv, bunExe, isWindows, tempDirWithFiles } from "harness";
import { join } from "path";

test("require() with trailing slash", () => {
const requireDir = tempDirWithFiles("require-trailing", {
"package.json": `
{
// Comments!
"name": "require-and-import-trailing",
"version": "1.0.0",
},`,
});

expect(require(requireDir + "/package.json").name).toBe("require-and-import-trailing");
});

test("import() with trailing slash", async () => {
const importDir = tempDirWithFiles("import-trailing", {
"package.json": `
{
// Comments!
"name": "require-and-import-trailing",
"version": "1.0.0",
},`,
});

expect((await import(importDir + "/package.json")).default.name).toBe("require-and-import-trailing");
});

0 comments on commit 189aa22

Please sign in to comment.