I have following directory structure for a library which will be imported by other node js project.
my-lib/
├─ dist/
│ ├─ index.js
│ ├─ foo.js
├─ src/
│ ├─ index.ts
│ ├─ foo.ts
├─ package.json
I have following package.json
{
"name": "my-lib",
"version": "1.0.0",
"description": "",
"main": "dist/index.js"
}
I have specified main
as dist/index.js
, so if I understand correctly, members exported from index.ts (js) can be imported as import abc from 'my-lib'
. If I have to access exported members from foo.ts (js) file then I might end up doing import foo from 'my-lib/dist/foo'
. So here I have to specify the dist
folder name in import path. Is there way to specify just 'my-lib/foo'
omitting dist
folder name? (just like importing dist/index.js
file.)
If installed with package from Nodejs.org js main executables files -- node and npm -- are located on the /usr/local/bin folder. With this installation method the files will be be available to all users.
The syntax for importing modules in ES6 looks like this. The reason for this error is that Node js doesn't support ES6 import directly. If you try to use import for importing modules directly in node js it will throw out that error. Do not worry about the error!
This can be accomplished with subpath exports in package.json.
"main": "./dist/index.js",
"exports": {
".": "./dist/index.js",
"./foo": "./dist/foo.js"
}
As explained in node.js documentation, it is possible to add subpath exports. Check it out here.
In your case it should look similar to following
{
"name": "my-lib",
"version": "1.0.0",
"description": "",
"main": "./dist/index.js",
"exports": {
".": "./dist/index.js",
"./foo": "./dist/foo.js"
}
}
After exporting like this you can import as follows
import foo from 'my-lib/foo'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With