Hacker News new | past | comments | ask | show | jobs | submit login

Perhaps I’m missing something, but when I’ve done this in the past, I get weird package resolution because my index.js isn’t in the root (`npm publish` publishes the root and doesn’t support alternate paths to my knowledge) - in the end people have to `import x from “mylib/dist”`.

I got round this with some funky step where I copy the package.json into the dist folder and rewrite some paths. Is there a better way to do this?




You can specify those exports in package.json.

  {
    "exports": "dist/index.js"
  }
or

  {
    "exports": {
      ".": "dist/index.js",
      "./*": "dist/*.js"
    }
  }
https://nodejs.org/api/packages.html#subpath-exports

Many packages do this.


EDIT: main and module properties are precursors to exports. exports is the recommended replacement.


Note that jest before v27, and some other runtimes, don't support export maps.


Jest and every other major runtime/bundler has supported exports for a couple years.

I.e. if you're releasing a package today, you probably don't have to worry about support.


A package I help maintain was released about a month ago, and we've had bug reports related to this: https://github.com/openai/openai-node/issues/304#issuecommen...

We simply chose to mark Jest 27 as unsupported in this case, but it did cost some debugging time.


You can use subpath exports like paulddraper suggested or in your `main` key in `package.json` you just point to whatever file you want to be served when `import X from 'Y'`.

It doesn't have to be `index.js` in the root of your package. That's the fallback if no `main` or subpath exports exist in `package.json`


It should work as you expect if you set “main” to “dist/index.js” in your package.json. If you tried that, some other strange thing must have been going wrong. Your workaround sounds fine but ideally you shouldn’t need it, yeah.


You missed a step in this article’s package.json. The “main” (or “module” for ESM) property defines the entry point. I’ve published dozens of packages and they all point to dist/index.js with zero issues.


Yup, we have a script which does exactly the same, copies to the main folder and then pushes.


I’ve experienced this as well.

For some projects I just configure publishConfig.directory directly at the dist folder.

While this may not look as clean, it is a lot easier for me to manage everything that’s published under a single directory.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: