Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing files in node package without including dist folder name

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.)

like image 326
Pavan Kumar Avatar asked Aug 24 '21 04:08

Pavan Kumar


People also ask

Where are node files located?

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.

Can I use import in node?

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!


2 Answers

This can be accomplished with subpath exports in package.json.

  "main": "./dist/index.js",
  "exports": {
    ".": "./dist/index.js",
    "./foo": "./dist/foo.js"
  }
like image 197
Trott Avatar answered Oct 21 '22 07:10

Trott


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'
like image 33
mayank1513 Avatar answered Oct 21 '22 08:10

mayank1513