Search code examples
node.jstypescriptnpmimportdecimal.js

TypeScript cannot find module decimal.js - but absolute path works


I am using typescript with node. I can write this without any problems:

import * as $ from "jquery";

The definition file for jquery is in node_modules/@types/jquery. However, neither of the following works with the definition file for decimal.js being in node_modules/decimal.js:

import { Decimal } from "decimal";
import { Decimal } from "decimal.js";

If I however include the file with its absolute path it works like a charm:

import { Decimal } from "/path/to/project/node_modules/decimal.js/decimal";

I'm using the latest version available in npm and these command line parameters:

--removeComments --inlineSourceMap --inlineSources --allowSyntheticDefaultImports --charset UTF-8 --module amd --target ES6 --newLine LF --moduleResolution classic


Solution

  • Considering that your module is in node_modules, you want to use the node style of module resolution. Replace --moduleResolution classic with --moduleResolution Node.

    See here

    However, resolution for a non-relative module name is performed differently. Node will look for your modules in special folders named node_modules. A node_modules folder can be on the same level as the current file, or higher up in the directory chain. Node will walk up the directory chain, looking through each node_modules until it finds the module you tried to load.

    The classic style resolves modules differently. According to the linked source:

    This used to be TypeScript’s default resolution strategy. Nowadays, this strategy is mainly present for backward compatibility.