node.jstypescripttypescript1.7

Why is typescript failing to import a module?


Typescript is not able to import the js-yaml package. It is actually happening with more packages for me, but this is an easy way to reproduce the problem.

In a new directory, type:

npm install js-yaml

Then in that same directory add the following ts file:

import * as y from 'js-yaml';
console.log(y);

When I compile using this command:

$ tsc --version
message TS6029: Version 1.7.5
$ tsc --module commonjs file.ts 
file.ts(2,20): error TS2307: Cannot find module 'js-yaml'.

And if I change import style to commonjs, like so:

declare var require: any;  // need to declare require, or else tsc complains
let y = require('js-yaml');
console.log(y);

All is compiled happily. Furthermore, I see that even though tsc had a compile failure, it does output a file. And in this file, there is exactly the same require call as in the version that compiles properly:

var y = require('js-yaml');
console.log(y);

Is this a bug, or am I doing something silly?


Solution

  • Silly of me. With help from the Typescript gitter room, I realized that I was missing the typings file. So, I ran this:

    tsd install js-yaml
    

    And then added the typings reference at the top of the ts file, like this:

    /// <reference path="./typings/js-yaml/js-yaml.d.ts"/>
    import * as y from 'js-yaml';
    console.log(y);
    

    And compilation worked.