For a while now, I've been quite at ease creating and utilizing NPM packages with Typescript. However, these packages have typically been provided and consumed as a single module. Now, I'm interested in publishing packages that contain more than one module without requiring the consumer to import unnecessary parts of the package into their code.
Let's say I have two typescript modules in my package src folder: one.ts and two.ts:
one.ts:
export function talk() { console.log("Hello World"); };
two.ts:
export function talk() { console.log("Goodbye World"); };
In accordance with best practices for creating an NPM package in Typescript, I also create an index.ts file in the src folder:
index.ts:
import * as one from "./one";
import * as two from "./two";
export { one, two };
This setup generates index.js, index.d.ts, one.js, one.d.ts, two.js, and two.d.ts files in the dist folder of my package (as well as possibly some source mapping files not relevant to this query).
The somewhat condensed package.json looks like this:
{
"name": "my-package",
"version": "0.0.5",
"description": "",
"license": "UNLICENSED",
"main": "dist/",
"types": "dist/",
"scripts": {
"build": "tsc --skipLibCheck",
"prepublish": "yarn run build",
},
"keywords": [],
"dependencies": {},
"files": [
"src",
"dist"
]
}
Similarly, the truncated tsconfig.json is as follows:
{
"compilerOptions": {
"target": "es6",
"module": "es6",
"moduleResolution": "node",
"noImplicitAny": true,
"noEmitOnError": true,
"removeComments": false,
"declaration": true,
"outDir": "./dist",
"allowJs": false,
"sourceMap": true,
"typeRoots": [
"./node_modules/@types"
]
},
"include": [ "src/**/*" ],
"exclude": [ "node_modules" ],
"compileOnSave": false
}
After publishing the package and consuming it in typescript, suppose I want to import only the one.ts module. I never need the "goodbye" part in my consuming code. How can I achieve this without unnecessarily importing the other module?
I'd like to be able to do something like this:
import * as greeting from "my-package.one";
greeting.talk();
Or even better:
import { talk } from "my-package.one";
talk();
I've managed to accomplish this before by writing javascript and creating my own header files with ambient modules. But this time, I want to keep things simple and use modules as they are intended in the package installed in node-modules.
If you have any suggestions on how I can modify my approach to building the multi-module package or how I consume it, I would greatly appreciate your input. Thank you!