From 70cf9832c9d8f7e8038e1fd81741cd577bc0bd85 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Thu, 21 Mar 2024 20:13:11 +0100 Subject: [PATCH] fix(raw): allow importing relative paths (#2289) --- src/rollup/plugins/import-meta.ts | 2 +- src/rollup/plugins/raw.ts | 16 ++++++++++++---- test/fixture/routes/assets/md.ts | 6 ++++++ test/tests.ts | 11 +++++++++-- 4 files changed, 28 insertions(+), 7 deletions(-) create mode 100644 test/fixture/routes/assets/md.ts diff --git a/src/rollup/plugins/import-meta.ts b/src/rollup/plugins/import-meta.ts index 2e11db9724..e539aa85ac 100644 --- a/src/rollup/plugins/import-meta.ts +++ b/src/rollup/plugins/import-meta.ts @@ -15,7 +15,7 @@ export function importMeta(nitro: Nitro): Plugin { return; } const url = - nitro.options.node && isEntry + nitro.options.node && isEntry && !code.includes("ROLLUP_NO_REPLACE") ? "_import_meta_url_" : '"file:///_entry.js"'; const envImport = nitro.options.node diff --git a/src/rollup/plugins/raw.ts b/src/rollup/plugins/raw.ts index 871541f99d..8dcda3126c 100644 --- a/src/rollup/plugins/raw.ts +++ b/src/rollup/plugins/raw.ts @@ -22,7 +22,7 @@ export function raw(opts: RawOptions = {}): Plugin { return { name: "raw", - resolveId(id) { + async resolveId(id, importer) { if (id === HELPER_ID) { return id; } @@ -38,10 +38,18 @@ export function raw(opts: RawOptions = {}): Plugin { isRawId = true; } - // TODO: Support reasolving. Blocker is CommonJS custom resolver! - if (isRawId) { - return { id: "\0raw:" + id }; + if (!isRawId) { + return; + } + + const resolvedId = (await this.resolve(id, importer, { skipSelf: true })) + ?.id; + + if (!resolvedId || resolvedId.startsWith("\0")) { + return resolvedId; } + + return { id: "\0raw:" + resolvedId }; }, load(id) { if (id === HELPER_ID) { diff --git a/test/fixture/routes/assets/md.ts b/test/fixture/routes/assets/md.ts new file mode 100644 index 0000000000..6de27f6fe5 --- /dev/null +++ b/test/fixture/routes/assets/md.ts @@ -0,0 +1,6 @@ +export default eventHandler(async (event) => { + const md = await import("../../assets/test.md" as string).then( + (r) => r.default + ); + return md; +}); diff --git a/test/tests.ts b/test/tests.ts index 7707a6e2f2..b3bc6dd9f7 100644 --- a/test/tests.ts +++ b/test/tests.ts @@ -332,13 +332,20 @@ export function testNitro( const { data: html, status: htmlStatus } = await callHandler({ url: "/file?filename=index.html", }); + expect(htmlStatus).toBe(200); + expect(html).toContain("

nitro is amazing!

"); + const { data: txtFile, status: txtStatus } = await callHandler({ url: "/file?filename=test.txt", }); - expect(htmlStatus).toBe(200); - expect(html).toContain("

nitro is amazing!

"); expect(txtStatus).toBe(200); expect(txtFile).toContain("this is an asset from a text file from nitro"); + + const { data: mdFile, status: mdStatus } = await callHandler({ + url: "/assets/md", + }); + expect(mdStatus).toBe(200); + expect(mdFile).toContain("# Hello world"); }); if (ctx.nitro!.options.serveStatic) {