Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't TypeScript find modules that are installed into 'node_modules'?

Given the following directory structure:

{project}/
  |-- node_modules/
  |    |-- lodash
  |-- src/
  |    |-- index.ts
  |-- lib/ (output)
  |    |-- index.js
  |    |-- index.d.ts
  |-- package.json
  |-- tsconfig.json

Whilst the built output functions properly; the tsc command complains that it cannot resolve the lodash module when I use any of the following:

import _ from "lodash";
import _ = require("lodash");
import * as _ from "lodash";

Inside my 'tsconfig.json' file I have included the following things:

...

"target": "es6",
"sourceMap": true,
"module": "commonjs",
"moduleResolution": "node",

...

But despite this it's still not finding any of the modules that are installed using npm.

Am I missing something that is required to make TypeScript find these modules?

I realize that without a TypeScript definition file TypeScript is unable to provide additional type checks; however, surely these should just default to the any type right?

like image 600
Lea Hayes Avatar asked Mar 04 '16 19:03

Lea Hayes


People also ask

Can not find TypeScript module?

To solve the cannot find module 'typescript' error, make sure to install typescript globally by running the npm i -g typescript command and create a symbolic link from the globally-installed package to node_modules by running the npm link typescript command. Copied!

Can not find module TSC?

The "Cannot find module or its corresponding type declarations" error occurs when TypeScript cannot locate a third-party or local module in our project. To solve the error, make sure to install the module and try setting moduleResolution to node in your tsconfig. json file.

Where can I find node modules?

On Unix systems they are normally placed in /usr/local/lib/node or /usr/local/lib/node_modules when installed globally. If you set the NODE_PATH environment variable to this path, the modules can be found by node. Non-global libraries are installed the node_modules sub folder in the folder you are currently in.

How do I use TypeScript modules?

A module can be created using the keyword export and a module can be used in another module using the keyword import . In TypeScript, files containing a top-level export or import are considered modules. For example, we can make the above files as modules as below. console.


1 Answers

Since lodash doesn't have a definition file in the node_modules/lodash folder, that won't work. You'll have to download it using typings or use an ambient declaration instead of an import:

declare var _: any;

For node.js you'd have to use:

var _ = require('lodash');
like image 151
rgvassar Avatar answered Sep 29 '22 11:09

rgvassar