Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure TypeScript npm package

Tags:

typescript

Is it possible to create and use a 100% TypeScript npm package without building to JavaScript?

I tried so and added "main": "index.ts" into package.json but when I import my modules I get:

export * from './lib/my-module';
SyntaxError: Unexpected token 'export'

The reason why I don't want to compile is that it is a private package and will be used in TypeScript projects only. Also I want to keep all decorators and comments as they are but when I tsc they get removed.

like image 477
Mick Avatar asked Jul 15 '26 23:07

Mick


1 Answers

Yes, it possible to create a pure typescript package.

  1. In package you need to add "main": "index.ts". index.ts should contain all types/components that should be available outside. For example:
export * from './model'
export * from './data-table'
export * from './context'
export * from './external-kit'
  1. Exclude your package from source-map-loader in webpack.config.js
{
  enforce: 'pre',
  exclude: /PACKAGE_NAME/,
  test: /\.(js|mjs|jsx|ts|tsx|css)$/,
  loader: require.resolve('source-map-loader'),
}
  1. Add the path to your package in the loader, which is responsible for transpiling TS to JS. For me, this is babel-loader:
{
  test: /\.(js|mjs|jsx|ts|tsx)$/,
  include: [paths.appSrc, path.resolve(appDirectory, 'node_modules/PACKAGE_NAME')],
  loader: require.resolve('babel-loader'),
  ...
}
like image 78
Yakov Algaev Avatar answered Jul 17 '26 19:07

Yakov Algaev