Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import an npm module that has a Typescript main file in Typescript?

I can't figure out what's the proper way of importing a Typescript npm module.

Here's how I'm trying to do it:

module package.json

{
  "name": "my-module",
  "main": "src/myModule.ts"
}

module src/myModule.ts

export module MyModule {
  // Code inside
}

code using the npm module

import { MyModule } from 'my-module'; // Doesn't work
import { MyModule } = require('my-module'); // Doesn't work.

The module is installed as a dependency in the package.json, and for example I can do

import { MyModule } from '../node_modules/my-module/src/myModule.ts';

But obviously this isn't great. What I want is a way to just import any exports that are in the main module file, but it doesn't seem possible.

like image 235
nialna2 Avatar asked Jan 29 '23 11:01

nialna2


2 Answers

The 'main' in package.json is useful only to packaging tools like webpack or the build tool of angular-cli. It is used to select different bundles according to the user's needs: ES6, ES5, UMD...

TypeScript ignores that. You need to specify the file you want, exactly as if you were refering to your own project:

import { MyModule } from 'my-module/src/myModule';

What other libraries like Angular do is to create a barrel, a file usually called 'index.ts' or 'index.d.ts', that imports and exports all types in the library.

The advantage of this is that, if you create a index.d.ts file in the root of my-module:

export { MyModule } from './src/myModule';
// other exports

You can simply do this:

import {MyModule} from 'my-module'

As typescript, when importing from a folder, automatically uses a index.ts or index.d.ts file.

like image 126
Oscar Paz Avatar answered Jan 31 '23 09:01

Oscar Paz


You should use "types" property instead of "main" property with typescript modules. How TypeScript resolves modules

like image 21
Jaime Avatar answered Jan 31 '23 08:01

Jaime