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?
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!
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.
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.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With