standard-things / esm

Tomorrow's ECMAScript modules today!
Other
5.26k stars 147 forks source link

import url via http or https expected per esm spec, but crashes #884

Open cdaringe opened 3 years ago

cdaringe commented 3 years ago

Problem

import [url] syntax is my interest is ESM vs other module systems, and brought me to this fancy project! on attempt to import a url:

$ node --trace-warnings -r esm
> import("https://localhost:4200/some.js.filejs")
undefined
> (node:67661) UnhandledPromiseRejectionWarning: Error [ERR_INVALID_PROTOCOL]: Protocol 'https:' not supported. Expected 'file:'
    at processImmediate (internal/timers.js:456:21)
    at createWarningObject (internal/process/warning.js:152:9)
    at process.emitWarning (internal/process/warning.js:122:15)
    at process.<anonymous> (/my/super/disk/node_modules/esm/esm.js:1:289642)
    at process.<anonymous> (/my/super/disk/node_modules/esm/esm.js:1:289518)
    at process.<anonymous> (/my/super/disk/node_modules/esm/esm.js:1:284879)

Dang. Node has an experimental https loader: https://nodejs.org/api/esm.html#esm_https_loader

Is that shimmable into standard-things/esm?

romane-echino commented 3 years ago

Did anyone got a solution for that? Tried with --experimental-loader ./https-loader.mjs but nothing happens

romane-echino commented 2 years ago

When launching

node --experimental-loader ./https-loader.mjs ./index.js

index.js code seems to route all require to https-loader but after

require = require("esm")(module)

everything is handled by ESM require function.

I tried to override the require function with the following code

require = function (file) {
        console.log(file);
        if (file.startsWith('https://')){
            console.log('HTTPS')
            return https_require(file);
        }
        else{
            console.log('ESM')
            return esm_require(file);
        }
    };

but all files imported via esm seems to ignore that change. I'm not an expert in the "module" variable but can't we override the resolve function for all ESM requires?