Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NPM package: best practices and exposing multiple import paths

I created an NPM package that uses Webpack and Babel for transpiling/bundling.

In my package.json, I've got main set to "main": "build/index.js". And in my Webpack config, I have entry set to entry: { app: './src/index.js' }. My entry file is shown below.

Everything works fine when the package is installed. However, with this setup, two import paths are exposed for every helper:

This is a problem for editors that support auto imports, since they will sometimes auto import from 'my-package/build/utils/helper1' rather than the preferred path of 'my-package'.

So, two questions:

  1. Is there any way to prevent the longer import path from being exposed?
  2. What is considered best practice when creating NPM packages. Is my setup acceptable, or should I be doing something different?

Entry File:

import helper1 from './utils/helper1';
import helper2 from './utils/helper2';

export {
  helper1,
  helper2,
};

const myPackage = {
  helper1,
  helper2,
};

export default myPackage;
like image 419
jabacchetta Avatar asked Feb 15 '19 16:02

jabacchetta


People also ask

How to choose the right npm package?

Here are some of the best practises that we can follow while choosing a NPM package — Checking the license type of the package is the most important thing. It gives you the details about terms and conditions on the package use.

How to clean your npm package before publishing it?

Use Packito to clean your package before publishing it I created this tool to go further in packaging npm module. It is a superset of previous step 3. In a dist folder, it will copy mandatory and selected files, but also refactor package.json to remove/change some fields.

How to install a module automatically with npm?

The most common way of doing that is by using npm install request. If you’d like to take that one step forward and automatically add it to your package.json file, you can do: npm will save your dependencies with the ^ prefix by default. It means that during the next npm install the latest module without a major version bump will be installed.

How to run NPM Link package-name from another location?

You can run npm link package-name from another location, to create a symbolic link from the globally installed package-name to the /node_modules directory of the current folder. Let’s see it in action! The next article in the Node.js at Scale series will be a SemVer deep dive with how to publish Node.js modules.


1 Answers

  1. you can utilize Webpack resolve
  2. I often use the first way:
export {
  helper1,
  helper2,
};

Recently, I found that we can use Object.freeze() to export. This is a good article.

like image 87
Vu Luu Avatar answered Nov 09 '22 23:11

Vu Luu