Skip to content

Instantly share code, notes, and snippets.

@sstackus
Last active January 15, 2020 17:33
Show Gist options
  • Save sstackus/8c724d82c590f97c41b1cce5983d1df1 to your computer and use it in GitHub Desktop.
Save sstackus/8c724d82c590f97c41b1cce5983d1df1 to your computer and use it in GitHub Desktop.
Import aliases with the new ES Modules (Node.js 13.6) and dotenv
import Foo from '@/modules/Foo'; // This will import `src/modules/Foo.js`
import * as Modules from '@/modules'; // This will import `src/modules/index.js`
{
"type": "module",
"main": "./app.js",
"scripts": {
"start": "node --experimental-specifier-resolution=node --loader=./resolve.js ./app.js",
"with-dotenv": "node -r dotenv/config --experimental-specifier-resolution=node --loader=./resolve.js ./app.js dotenv_config_path=./config/${NODE_ENV}.env"
},
"engines": {
"node": ">=13.6.0"
}
}
import { URL, pathToFileURL } from 'url';
import fs from 'fs';
const baseURL = pathToFileURL(process.cwd()).href;
export async function resolve(s, parentModuleURL = baseURL, defaultResolve) {
let specifier = s;
if (specifier.indexOf('@/') === 0) {
let path = `${process.cwd()}/src/${specifier.slice(2)}`;
try {
fs.statSync(path);
// Must be a directory if no error
path += '/index.js';
} catch (e) {
path += '.js';
}
specifier = new URL(path, parentModuleURL).href;
}
// Defer to Node.js for all other specifiers
return defaultResolve(specifier, parentModuleURL, defaultResolve);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment