首页 > 解决方案 > 如何在 Typescript 中导入 Javascript 模块

问题描述

我想知道在 Typescript 中导入 Javascript 模块。

项目

  1. 模块是“amd”。
  2. 对单个文件使用 outFile 选项。
  3. 控制内部模块从///<reference path=''/>

代码

应用程序.js

export function func(a, b) {
    return a+b;
}

MainApp.ts

import Stats from "../app";    

class MainApp {

    foo() {
        const f = func(1, 2); // not define (runtime error)
    }
}

错误

SyntaxError: Unexpected token export
ReferenceError: define is not defined
Main.js:6667
    at d:\...\Main.js:6667:2
ReferenceError: MainApp is not defined
    at window.onload (d:\...\index.html:18:24)

未找到定义。

标签: javascripttypescript

解决方案


默认导出可能存在错误。这是适合您的代码结构的工作示例。

tsconfig.json:

{
    "compilerOptions": {
        "strict": true,
        "allowJs": true,

        "target": "es6",
        "module": "commonjs"
    }
}

app.js:

export function sum(a, b) {
    return a + b;
}

MainApp.ts:

import {sum} from './app';

class MainApp {
    foo() {
        const a = 1;
        const b = 2;

        const result = sum(1, 2);
    }
}

global.d.ts:

declare module '*.js';

推荐阅读