Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

javascript - Root directory in package.json

My question concerns an existing library that I wish to publish as an NPM module. The library is already in use, and currently required via the local file system.

How can I specify the root directory of my module's files?

If I have a structure like:

.
├── package.json
├── src
|   ├── js
|   └────── lib
|   └───────── my
|   └───────────── thing.js
|   └───────────── that.js

How do I specify that the root of my module, and accessible files is src/js/lib/my/?

I would like to use as follows from an outside project:

var thing = require('my/thing'),
    that = require('my/that');

I saw the "files" property in package.json, is this the right way to go?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

UPDATE 2020

The issue suggesting mainDir is now closed. Instead there is a new field called exports which can be used almost like es import maps to map a folder to an export alias:

// ./node_modules/es-module-package/package.json
{
  "exports": {
    "./my/": "./src/js/lib/my/"
  }
}
import thing from 'es-module-package/my/thing.js';
// Loads ./node_modules/es-module-package/src/js/lib/my/thing.js

As suggested in the issue linked in the original answer below it may be possible to map the root to a folder to access import thing from pkg/thing.js as so:

{
  "type": "module",
  "main": "./dist/index.js",
  "exports": {
    "./": "./src/js/lib/my/"
  }
}

Original Answer

For a native solution, see this node issue https://github.com/nodejs/node/issues/14970

The feature request suggests a mainDir field in the package.json next to main.

The more people that vote, the faster/more likely it will be implemented


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...