9

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.

3
  • have you tried using import 'my-module/src/myModule' ?? Commented Mar 16, 2018 at 12:29
  • Is this a node module? If you build it as npm package you can just create an index.ts in the root that exports the library. Then you can just do import { MyModule } from 'MyModule' Commented Mar 16, 2018 at 12:31
  • Yes, this actually worked. Commented Mar 16, 2018 at 14:29

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.