Last active
January 15, 2020 17:33
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foo from '@/modules/Foo'; // This will import `src/modules/Foo.js` | |
import * as Modules from '@/modules'; // This will import `src/modules/index.js` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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