nodejs / node

Node.js JavaScript runtime ✨🐢🚀✨
https://nodejs.org
Other
107.6k stars 29.59k forks source link

Add `mainDir` to module resolution algorithm #14970

Closed davewasmer closed 4 years ago

davewasmer commented 7 years ago

First off, I realize that the Module API is frozen, so I understand if this proposal will be rejected outright. However, I figured I'd give it a shot anyway.

Many node packages today are written in a source language other than JavaScript, and compiled before publishing. The main field in the package.json file allows these compiled packages to specify a different file as the entry point (i.e. dist/index.js).

However, the module resolution algorithm allows for loading files within a module via path syntax, i.e. require('foo/bar/quux') would load bar/quux.js from the foo module. Currently, the only way to ensure this kind of path syntax works (without needing to include dist/ in the path) is to publish only the dist folder. This approach requires the author to remember to publish the subdirectory every time, which can be mistake prone.

I'd like to propose supporting a new field in the package.json spec called mainDir. If present, the module resolution algorithm would treat that mainDir path as the root path for that package, so compiled packages could specify "mainDir": "dist", and easily support sub-path module loading (i.e. require('foo/bar/quux')) without having to remember to publish from the subdirectory every time.

I think this would be a relatively straightforward change on the implementation side, happy to PR it, but I wanted to test the waters first. The only trouble I can see is if people are already using mainDir in package.json files for something else. However, a quick Github search reveals zero public instances of using mainDir in a package.json file. This of course doesn't preclude it's use in private repos, but I think it's a strong indicator that we wouldn't be trampling on too much, if any, existing code.

sitatec commented 2 years ago

@chathu-novade, use ./* instead

mayank1513 commented 7 months ago

This approach does not work. At least with the turbo repo setup - trying to use this approach to export from dist forlder in this repo - https://github.com/react18-tools/turborepo-template/blob/main/lib/fork-me/package.json