d.ts文件导出模块

时间:2017-03-15 13:19:32

标签: javascript typescript webpack

我从Typescript开始,我尝试创建一个新模块,但我遇到了一些问题。

我想将一个js文件导入到我的index.ts中,所以我知道我必须创建一个d.ts文件才能创建和解释typescript的函数。进入我的index.ts我把它:



import Toto from "./toto";




这是我的d.ts文件:



declare module 'Toto' {

    function myfunction(callback : Function);

    export default myfunction;

}




但是在我的d.ts文件中我有这个错误:

TS1128:预期声明或声明

我不明白为什么,因为我的测试很容易。

我使用webpack构建代码,这是我的webpack.config.js



module.exports = {
    entry: "./index.ts",
    output: {
        path: "bundle/",
        filename: "bundle.js"
    },
    resolve: {
        extensions : [".ts", ".tsx", ".js"]
    },
    module: {
        loaders: [
            { test: /\.tsx?$/, loader: "ts-loader" }
        ]
    }
};




我的tsconfig.json



{
  "compilerOptions": {
    "target" : "es5"
  }
}




如果您有任何想法:)

问候

3 个答案:

答案 0 :(得分:0)

如果你想直接加载.js文件,只需设置" allowJS"标志在编译器选项中。然后,TS将尝试使用基于JS的类型推断。 TS Compiler options

因此,在您的情况下,只需将allowJS标志添加到编译器选项并跳过d.ts文件。

答案 1 :(得分:0)

这个设置对我有用

//toto.js
function myfunction(callback) {
    callback("42")
}    
exports.default=myfunction


//toto.d.ts
export default function myfunction(callback : Function);


//main.ts
import myfunc from './toto'    
myfunc((res) => console.log(res) )


//tsconfig.json
{
    "compilerOptions": {
        "target" : "es5"
    }
 }

正确运行node main.js记录42

或者使用allowJs

  • 从上面的设置中删除toto.d.ts定义文件
  • 在tsconfig compilerOptions
  • 中添加"allowJs":true

=>第一个解决方案需要制作定义文件,但在myfunc中使用main.ts时,您会受益于打字。

答案 2 :(得分:0)

最后我发现了我的问题,我的EDI(phpStorm)太旧了,它在Typescript 1.4中编译代码,而我在的是Typescript 2.2.1 ......

感谢您的反馈,我不知道我可以使用此选项allowJs,但对我来说不推荐,因为我想用typedoc记录我的代码,我需要创建这个d.ts文件才能做到这一点。