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

feat: support import.meta.ROLLUP_FILE_URL_(referenceId) #3488

Merged
merged 10 commits into from
Feb 5, 2025

Conversation

hi-ogawa
Copy link
Member

@hi-ogawa hi-ogawa commented Feb 4, 2025

Description

Reviving #1928. I came across import.meta.url.ROLLUP_FILE_URL_xxx in one of my plugins (hi-ogawa/vite-plugins#673) and I think having the compat in rolldown is nice to have (though it's also possible to have a compat in rolldown-vite or user land level via a custom plugin's renderChunk replacing).

Sapphi also mentioned that Astro uses this feature #819 (comment). I'm hoping the complexity required on rolldown side is low and it's worth the inclusion. Let me know what you think.

Example user-land plugin to replace "import.meta.ROLLUP_FILE_URL_xxx"

From hi-ogawa/vite-plugins#673

import path from "node:path";
import MagicString from "magic-string";
import type { Plugin } from "vite";

// import.meta.ROLLUP_FILE_URL_xxx on rolldown
// https://github.com/rolldown/rolldown/pull/1928
export function rolldownPluginRollupFileUrl(): Plugin {
  return {
    name: rolldownPluginRollupFileUrl.name,
    renderChunk: {
      order: "pre",
      handler(code, chunk) {
        if (!code.includes("import.meta.ROLLUP_FILE_URL_")) {
          return;
        }
        const matches = code.matchAll(/import.meta.ROLLUP_FILE_URL_(\w+)/dg);
        const output = new MagicString(code);
        for (const match of matches) {
          const referenceId = match[1]!;
          const assetFileName = this.getFileName(referenceId);
          const relativePath =
            "./" +
            path.relative(
              path.resolve(chunk.fileName, ".."),
              path.resolve(assetFileName),
            );
          const replacement = `new URL(${JSON.stringify(relativePath)}, import.meta.url)`;
          const [start, end] = match.indices![0]!;
          output.update(start, end, replacement);
        }
        if (output.hasChanged()) {
          return {
            code: output.toString(),
            map: output.generateMap({ hires: "boundary" }),
          };
        }
        return;
      },
    },
  };
}

let importer_dir = importer_chunk
.absolute_preliminary_filename
.as_ref()
.unwrap()
Copy link
Contributor

@IWANABETHATGUY IWANABETHATGUY Feb 4, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should either add SAFETY comments or expect instead of unwrap, attend to give a more friendly panic message.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replaced unwrap with expect 👍
FYI, I referenced the code from Chunk::import_path_for, which computes relative chunk path. I'll try to refactor some repeated code separately later.

pub fn import_path_for(&self, importee: &Chunk) -> String {
let importer_dir =
self.absolute_preliminary_filename.as_ref().unwrap().as_path().parent().unwrap();
let importee_filename = importee.absolute_preliminary_filename.as_ref().unwrap();
let import_path = importee_filename.relative(importer_dir).as_path().expect_to_slash();

@hi-ogawa hi-ogawa marked this pull request as ready for review February 5, 2025 01:00
@IWANABETHATGUY IWANABETHATGUY added this pull request to the merge queue Feb 5, 2025
Merged via the queue into rolldown:main with commit 18af1ba Feb 5, 2025
24 checks passed
@hi-ogawa hi-ogawa deleted the feat-rollup-file-url-2 branch February 5, 2025 23:56
github-merge-queue bot pushed a commit that referenced this pull request Feb 6, 2025
<!-- Thank you for contributing! -->

### Description

Follow up to #3488. I forgot to
test `emitFile({ type: "chunk" })` case and I just realized it's not
working on
hi-ogawa/vite-environment-examples#154.

Currently, `FileEmitter::emitted_chunks` is not defined during scope
hoisting finalizer, but it looks possible to define it earlier right
after `generate_chunk_name_and_preliminary_filenames` instead of waiting
until `instantiate_chunks`.
IWANABETHATGUY pushed a commit that referenced this pull request Feb 7, 2025
### Description

Minor cleanup as I mentioned in
#3488 (comment)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants