Skip to content

data-url modules fail to import #207

Closed

Description

@LorisSigrist

Environment

Node.js v21.2.0

Reproduction

Self contained snippet:

import jiti from 'jiti'

const moduleAsText = "export default 42"
const dataUrl = "data:text/javascript;base64," + btoa(moduleAsText)

const nativeImport = await import(dataUrl)
console.log(nativeImport.default) // prints 42

const withJiti = jiti(import.meta.filename)(dataUrl)//Throws "MODULE_NOT_FOUND" error
console.log(withJiti.default)

Describe the bug

jiti fails to import modules from data-urls, which is supported by node's native import

Additional context

I tested both base64 encodings and text/javascript encoding, neither worked.
Peering at the source-code there doesn't seem to be any handling for this yet. Would you be interested in supporting this?

We discovered this in generaltranslation/inlang#2133, where a vite-plugin broke because of this.

Logs

node:internal/modules/cjs/loader:1144
  const err = new Error(message);
              ^

Error: Cannot find module 'data:text/javascript;base64,ZXhwb3J0IGRlZmF1bHQgNDI='
Require stack:
- /Users/***/dev/jiti-debug/index.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1144:15)
    at Function.resolve (node:internal/modules/helpers:187:19)
    at _resolve (/Users/***/dev/jiti-debug/node_modules/.pnpm/[email protected]/node_modules/jiti/dist/jiti.js:1:251148)
    at jiti (/Users/***/dev/jiti-debug/node_modules/.pnpm/[email protected]/node_modules/jiti/dist/jiti.js:1:253746)
    at file:///Users/***/dev/jiti-debug/index.js:11:13 {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '/Users/***/dev/jiti-debug/index.js' ]
}

Activity

  1. bohjak commented on Sep 21, 2024

    @bohjak
    Contributor

    As a temporary workaround, you can add an extension not in the extensions array[0] to the end of the URI.
    This will make JITI think that it's an unsupported file type and will use the native import/require instead.

    [0]: The default extensions array is: [".js", ".mjs", ".cjs", ".ts", ".mts", ".cts", ".json"]

    Example

    const script = `
    export default 0;
    // For JITI support when used as data: .unknown
    `;
    import(`data:text/javascript;charset=utf-8,${encodeURIComponent(script)}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions