我有一个使用RequireJS编写的模块,我需要在Angular4中工作。为了理解这个过程,我创建了一个简化的Realjs模块,我试图为它创建一个.D.TS文件,但是我很难让代码编译。
我的目录结构看起来像

.
+--index.html
+--lib
|  +-require
|    +--require.js
|
+--js
|  +-bootstrap.ts
   +-test.js
   +-test
     +-index.d.ts

我的index.html文件如下所示
<html>
<body>
    ...
    <script type="text/javascript" src="lib/require/require.js" data-main="js/bootstrap"></script>
</body>
</html>

我的bootstrap.js
import test from 'test';
add(5,6);

我的test.js
define(function(){
    return {
       add: function(x, y){
           console.log(x + y);
       return x+y;
       }
    };
});

我的测试/索引
export function add(a:number, b:number):number;

当我试图编译bootstrap.ts时,会出现此错误
bootstrap.ts(2,18): error TS2307: Cannot find module 'test'.
bootstrap.ts(3,1): error TS2304: Cannot find name 'add'.

最佳答案

javascript中有3种常见的模块系统类型:node.js中的AMD(require.js)、Common.js(node使用)和ES6 modules(node.js中仍然不可用,没有标志,但typescript使用,即使typescript可以编译到所有3个模块系统)。
AMD是异步的..意思是,当你require某事时,这个东西,当可用时,将在回调中提供。
例子:

// AMD
require("x", (x) => { /* x is available here */ })

另外两个是同步的
// CommonJS
var x = require("x")
// x is available here, synchronously (no callback)

// ES6 Modules
import x from "x"
// x is available here, synchronously (no callback)

在这个介绍之后,现在回到你的问题…
首先,您的test.d.ts中存在问题。如果test.js看起来像这样:
define(function(){
    return {
       add: function(x, y){
           console.log(x + y);
       return x+y;
       }
    };
});

否则,该模块不会像您假设的那样返回函数add。它实际上是返回一个包含函数add的对象。因此,这个JavaScript文件的声明应该是:
declare module "test" {
    const math: {
        add: (a:number, b:number) => number
    }
    export default math
}

注意,我完全忽略了define函数,在这里创建了test的声明。为什么?因为typescript总是使用es6模块,但是在语法上,在编译时,可以使用compilerOptions.module中的tsconfig.json来指定要使用的模块系统。
现在,当您import这个test模块时,您再次使用es6模块并让typescript编译它到amd,如果您愿意的话。
您的bootstrap文件就是这样的:
import test from "test"
console.log(test.add(3,4))

再说一遍,你的假设是错的。如果要导入模块,则不能调用“空”中的“空”。你必须打电话给
现在,如果使用test作为typescript模块系统,则编译的add文件将如下所示:
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
define(["require", "exports", "test"], function (require, exports, test_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    test_1 = __importDefault(test_1);
    console.log(test_1.default.add(3, 4));
});

07-24 09:47
查看更多