为什么打字稿无法导入模块? [英] Why is typescript failing to import a module?

查看:104
本文介绍了为什么打字稿无法导入模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Typescript无法导入js-yaml包.实际上,对于我来说,更多的软件包正在发生,但这是重现此问题的简便方法.

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.

在新目录中,键入:

npm install js-yaml

然后在同一目录中添加以下ts文件:

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'.

如果我将导入样式更改为commonjs,就像这样:

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);

所有内容都可以愉快地编译.此外,我看到即使tsc编译失败,它也会输出文件.在此文件中,与正确编译的版本完全相同的require调用:

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?

推荐答案

我很傻.在打字稿散布室的帮助下,我意识到我缺少打字文件.所以,我跑了这个:

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

然后在ts文件顶部添加类型输入引用,如下所示:

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);

编译成功了.

这篇关于为什么打字稿无法导入模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆