When you need to export multiple ES6 modules from an NPM package, the recommended approach is to utilize ES6's named export feature. This allows you to export multiple variables or functions from the same file and import only the required parts selectively when importing.
Here is a simple example demonstrating how to export multiple modules from an NPM package.
Suppose you have a file named utils.js that contains multiple utility functions:
javascript// utils.js // Export function multiply export const multiply = (a, b) => { return a * b; }; // Export function sum export const sum = (a, b) => { return a + b; }; // Export constant PI export const PI = 3.14159;
In the above utils.js file, we utilized named exports (using the export keyword) to export three modules: two functions multiply and sum, and a constant PI.
When other developers wish to use this NPM package in their projects, they can selectively import these modules. For example:
javascript// otherFile.js // Import specific functions import { multiply, sum } from 'your-npm-package/utils'; // Use the imported functions const resultMultiply = multiply(2, 3); const resultSum = sum(2, 3);
Alternatively, if they wish to import all named exports, they can use the star (*) operator and assign a name to these exports:
javascript// anotherFile.js // Import all exports from utils import * as Utils from 'your-npm-package/utils'; // Use the imported modules const resultMultiply = Utils.multiply(4, 5); const resultSum = Utils.sum(4, 5); const valueOfPI = Utils.PI;
The benefit of this approach is that it enables maintainers to clearly identify which features are utilized, while allowing them to selectively import modules as needed, which helps minimize the final bundled file size.
Note that to make the above utils.js module usable within an NPM package, you must ensure that your package.json file correctly specifies the entry point. For instance:
json{ "name": "your-npm-package", "version": "1.0.0", "main": "index.js", "type": "module", // ... other settings ... }
In this context, ""main": "index.js"" specifies the entry point file for the NPM package. Ensure that all necessary modules are correctly exported from the entry point, or re-export the contents of utils.js in the entry point file. For example, if your entry file is index.js, you can export the modules defined in utils.js within it:
javascript// index.js export { multiply, sum, PI } from './utils';
In this manner, other developers can directly import these modules using your NPM package name:
javascript// example.js import { multiply, sum } from 'your-npm-package';
Note: The path 'your-npm-package' is a placeholder and should be replaced with your actual NPM package name when used.