Skip to content

Instantly share code, notes, and snippets.

@TravisMullen
Last active October 10, 2019 00:39
Show Gist options
  • Save TravisMullen/16dfabca0db4bb4c32fb4f5ef297b25a to your computer and use it in GitHub Desktop.
Save TravisMullen/16dfabca0db4bb4c32fb4f5ef297b25a to your computer and use it in GitHub Desktop.
Loader for Node ESM support.
import path from 'path'
import process from 'process'
import Module from 'module'
/**
*
* # Experimental Modules Loader
*
* @see {@link https://nodejs.org/api/esm.html#esm_loader_hooks}
*
*
* With this loader, running:
*
* @example `NODE_OPTIONS='--experimental-modules --loader ./js-ext.loader.mjs' node x.js`
*
* A dummy loader to load JavaScript restricted
* to browser resolution rules with only JS file extension
* and Node.js builtin modules support could be written:
*/
const builtins = Module.builtinModules
const JS_EXTENSIONS = new Set(['.js', '.mjs'])
const baseURL = new URL('file://')
baseURL.pathname = `${process.cwd()}/`
export function resolve (specifier, parentModuleURL = baseURL, defaultResolve) {
if (builtins.includes(specifier)) {
return {
url: specifier,
format: 'builtin'
}
}
if (/^\.{0,2}[/]/.test(specifier) !== true && !specifier.startsWith('file:')) {
// For node_modules support:
// return defaultResolve(specifier, parentModuleURL);
throw new Error(
`imports must begin with '/', './', or '../'; '${specifier}' does not`)
}
const resolved = new URL(specifier, parentModuleURL)
const ext = path.extname(resolved.pathname)
if (!JS_EXTENSIONS.has(ext)) {
throw new Error(
`Cannot load file with non-JavaScript file extension ${ext}.`)
}
console.count('loader resolved')
return {
url: resolved.href,
format: 'esm'
}
}
{
"name": "js-ext-loader",
"version": "1.0.1",
"bin": "js-ext.loader.mjs",
"description": "To exec and load ESM files with '.js' ext in addition to '.mjs'.",
"main": "js-ext.loader.mjs",
"module": "js-ext.loader.mjs",
"scripts": {
"test":"NODE_OPTIONS='--experimental-modules --loader ./js-ext.loader.mjs' node test.js"
},
"repository": {
"type": "git",
"url": "git+https://gist.github.com/TravisMullen/16dfabca0db4bb4c32fb4f5ef297b25a"
},
"author": "Travis Mullen",
"license": "ISC"
}
import {
platform,
arch,
cpus,
userInfo
} from 'os'
import {
inspect
} from 'util'
for (const method of [platform, arch, cpus, userInfo]) {
console.assert(typeof(method) !== 'undefined', 'modules should be loaded and defined.')
const test = method()
console.assert(typeof(test) !== 'undefined', 'module methods should return data.')
console.log(inspect(test, { colors: true }))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment