Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import ES6 Modules with absolute paths in NodeJS without using Babel/Webpack

I have a plain old NodeJS project (with Typescript) and I'm really struggling to find out how to do ES6 imports for local files without having to do "../../../foo/bar" all the time.

There are loads of similar questions but all seem to revolve around babel/Webpack which I'm not using.

If I do the following:

import foo from `/bar`

it looks for it in the root folder of my PC (e.g. c:/bar) and fails.

I have tried using a .env file with NODE_PATH set to various hings ("/", "." etc) but no luck. I have also tried setting "type: 'module'" in my package.json and my tsconfig.json file has {"baseUrl": "."}

So I think I've tried every answer I can find. Am I just doing them in the wrong combination or is the solution something different?

like image 698
jonhobbs Avatar asked Nov 27 '20 15:11

jonhobbs


People also ask

Do I need Webpack for ES6 modules?

For most browsers, yes, you can accomplish getting all needed code to the browser with just ES6 modules, without Webpack.

Can Webpack work without Babel?

No unless all dependencies of your project supports ES6. There is one serious incompatibility: import is asynchronous while require() is synchronous.

Can I use import without Webpack?

It's time to fully embrace import/export With JavaScript modules fully supported in every major browser, savvy developers can now deliver production-ready apps without Webpack.

Is it possible to use ES6 modules instead of the Nodejs modules system?

ES6 doesn't allow this, but there is an API in development for that. Since ES6 modules are part of the standard, I would use them.


1 Answers

Here are two tricks I've used for this, with Node.js and native ES modules.

  1. file: dependencies

If you want to access <project root>/bar from a sub package two levels down, adding this to the package.json dependencies:

    "@local/bar": "file:../../bar",

..makes bar available to the said subpackage as @local/bar.

While relative paths are still present, they are now all in the package.json files and the sources never need to know..

  1. Use dynamic import()

Pick the root folder's path to a constant and do this:

const foo = await import(`${rootPath}/bar`);
like image 104
akauppi Avatar answered Sep 24 '22 13:09

akauppi