Home > Mobile >  How to disable subfolder importing from my npm package
How to disable subfolder importing from my npm package

Time:05-26

I develop an npm package with:

  • typescript
  • webpack

webpack.config:

{...
entry: './src/index.ts
}

library tree:

- package.json
- src
- - index.ts
- - ...all_my_code...

and I export all my library functionality and types from this index.ts file.

The problem is that my /dist directory that is eventualy installed in someone's node_modules, contains sub folders of my library src which I don't want my library's users to use (it is garbage for them).

How can I not export these subfolders?

CodePudding user response:

and I export all my library functionality and types from this index.ts file.

-- You cannot simply export from index.ts file. You must compile your TypeScript project into JavaScript and then consumer of your library should consume your compiled JavaScript. It means there will always be dist folder.

You should publish your package.json file along with dist folder, excluding the src folder. You can use typescript to generate declaration files and put them in dist folder.

No the make topic is how to hide the dist folder so that consumers do not directly import from those dist folder.

You have three options - Traditional Bundler, Barrel pattern or package exports.

Bundler approach: Bundle everything into just one file using a bundler like Webpack or Rollup. Assuming you have one entry point:

{ 
  // ...webpack config
  entry: './src/index.ts'
}

This would generate just one file like bundle.js or similar depending on your configuration. Then use the main field of package.json and provide the path of this generated file. This is the most traditional approach that is usually followed.

Barrel exports: The second variation is to use a Barrel Pattern. You would then compile your package using plain Typescript and put generated files in a dist folder. But using barrel pattern, you would use the barrel export file as main file configuration. The cons of this is that if you have custom lodaders like CSS, SCSS, Raw loaders, then plain TS compiler is not enough.

Package.json exports: Finally, you can use newly introduced Node.js package exports. This is the recommended approach going forward as it is future proof and supporting starting Node version 16.x.x onwards. This is also the most bulletproof way of hiding your internal modules compiled in dist. The drawback is this won't work if you intend to use this library with older version of Node.js. Also, the tooling support is rough around the edge.

Finally, you can mix-n-match all the three approaches. I recommend that you use Barrel exports with package.json exports.

On a side note, as a good practice, Rollup is a bundler to use when you intend to bundle a library. Webpack should be used when you plan to bundle an application.

  • Related