This guide covers common issues and their fixes for TypeScript projects, particularly when publishing as NPM packages.
Add "use strict"; after the shebang (if exists) in all TypeScript files:
#!/usr/bin/env node // only for entry files that need to be executable
"use strict";
import { ... } from "...";Files that typically need this:
- src/index.ts
- src/services/*.ts
- src/tools/*.ts
- src/types/*.ts
- src/config/*.ts
{
"name": "your-package",
"version": "1.0.0",
"type": "commonjs", // Add this line
"main": "dist/index.js",
"bin": {
"your-package": "./dist/index.js" // Use relative path
}
}In your main entry file (e.g., src/index.ts):
#!/usr/bin/env node // Add this for executable packages
"use strict";
// Your imports and codeIn tsconfig.json:
{
"compilerOptions": {
"module": "CommonJS",
"moduleResolution": "node",
"target": "ES2020",
"esModuleInterop": true,
"isolatedModules": true,
"noEmit": false, // Add this
"declaration": true,
"outDir": "./dist",
"rootDir": "./src"
}
}Before publishing, always do a clean build:
rm -rf dist/
npm run buildEnsure you have these scripts:
{
"scripts": {
"build": "tsc",
"prepare": "npm run build",
"start": "node dist/index.js",
"dev": "tsx src/index.ts"
}
}If you see: "Support for loading ES Module in require() is an experimental feature"
- Add
"type": "commonjs"to package.json - Ensure all imports use CommonJS syntax
- Use
.jsextensions in import paths after compilation
If you see: "use strict: not found" or "Syntax error: word unexpected"
- Add shebang line to entry file
- Ensure correct bin path in package.json
- Make sure the built file has execute permissions
If TypeScript can't find modules:
- Add
"moduleResolution": "node"to tsconfig.json - Add
"esModuleInterop": trueto tsconfig.json - Ensure all dependencies are listed in package.json
Before publishing:
npm pack
npm install -g .
your-package # Test the commandAfter publishing:
npx -y your-package@versionIf issues persist, try:
node --trace-warnings $(which your-package)- Update version in package.json
- Clean the dist directory
- Run build
- Test locally
- Ensure all files are included in "files" field
- Publish with
npm publish
- Always use explicit types
- Avoid mixing ESM and CommonJS
- Keep dependencies up to date
- Test on different Node.js versions
- Use proper error handling
- Include proper TypeScript declarations