typescript + lodash - 找不到模块

时间:2016-06-22 20:00:54

标签: javascript typescript lodash

我正在尝试使用typescript和lodash在我的应用中运行,但是当我运行时

  

tsc --module commonjs lodash-test.ts

我总是得到

  

lodash-test.ts(2,20):错误TS2307:找不到模块'lodash'。

这仍然会产生一个lodash-test.js文件

"use strict";
//lodash test that will be injected in index.html
var _ = require("lodash");
console.log('This is your lodash ts file');
console.info(_.chunk(['a', 'b', 'c', 'd'], 2));

现在,当我在浏览器中运行index.html文件时,我正在

  

lodash-test.js:3未捕获的ReferenceError:未定义require

在文件的第3行。

Index.html 文件

<!DOCTYPE html>
<html>    
<head>
    <meta charset=utf-8 />
    <title></title>
    <script type="text/javascript" src="bower_components/lodash/dist/lodash.min.js"></script>
    <script type="text/javascript" src="lodash-test.js"></script>    
</head>    
<body>
    <h3>Hey</h3>
</body>    
</html>

我的typings文件夹中有lodash类型定义。我怎样才能确保Typescript可以找到这个lodash / index.d.ts文件?另外我如何修复“require is not defined”错误?

这是我的文件结构:

enter image description here

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

var _ = require("lodash");对于加载脚本的方式没有必要。

在你的<head>中,你有一行:

<script type="text/javascript" src="bower_components/lodash/dist/lodash.min.js"></script>

_加载到全局命名空间中。 require("lodash")是一个在运行时加载lodash的模块加载器。

所以

A)删除require语句,只使用var _,就像它已经加载一样(因为它已经加载)。您可能需要使用declare关键字做一些棘手的事情,以使tsc不抱怨_未定义。

B)在<script>中移除<head> lodash并正确设置require,以便知道"lodash"是什么。否则,可能能够简单地执行var _ = require('bower_components/lodash/dist/lodash.min');

之类的操作
相关问题