Question:
I’m working on a TypeScript npm package and I’m trying to customize the import paths for convenience. After building my package, the structure looks like this:
File Structure:
- dist
- utils
- index.js
- index.d.ts
- index.js
- index.d.ts
Code:
Before building, my index.ts
file looks like this:
import { UtilityFunction } from './utils';
export { UtilityFunction };
Currently, I can import the module like this:
import { UtilityFunction } from '@mypackage/name';
However, I want to be able to import it using a more specific path, like this:
import { UtilityFunction } from '@mypackage/name/utils';
Here is my current tsconfig.json
:
{
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"baseUrl": "./",
"module": "commonjs",
"target": "es6",
"lib": ["es6"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"declaration": true,
"declarationDir": "./dist/types"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
My package.json
includes the following:
{
"name": "@mypackage/name",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/types/index.d.ts",
"exports": {
"./utils": "./dist/utils/index.js"
},
"scripts": {
"build": "tsc",
"prepare": "npm run build"
},
"files": [
"dist/**/*"
],
"devDependencies": {
"typescript": "^4.3.2"
}
}
Expected Outcome:
I want users to be able to import modules using:
import { UtilityFunction } from '@mypackage/name/utils';
Questions:
- What changes are needed in my configuration to achieve the desired import paths?
- How can I ensure that TypeScript can find the module and its type declarations without running into the aforementioned errors?
Any guidance or suggestions would be greatly appreciated. Thank you!
2