Compare commits

...

1 Commits

Author SHA1 Message Date
Jarred Sumner
51e4866f9d Support comments and trailing commas when requiring or importing package.json 2024-04-25 20:10:35 -07:00
3 changed files with 34 additions and 1 deletions

View File

@@ -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;
}

View File

@@ -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));

View File

@@ -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");
});