javascript - 如何在 Typescript 中导入 Javascript 模块
问题描述
我想知道在 Typescript 中导入 Javascript 模块。
项目
- 模块是“amd”。
- 对单个文件使用 outFile 选项。
- 控制内部模块从
///<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)
未找到定义。
解决方案
默认导出可能存在错误。这是适合您的代码结构的工作示例。
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';
推荐阅读
- java - 如何强制 Java 的 jSerialComm 在通过串行连接发送的消息之间短时间空闲?
- python - 如何使用 Python / Scipy 平滑地缩放信号中的特定区域?
- linux - 如何在windows中设置makefile
- c++ - posix中强大的rwlock
- android - 我使用 putExtra() 意向方法传递给另一个活动的数据存储在哪里?
- image-processing - 在连续随机生成的训练数据上训练神经网络是个好主意吗?
- javascript - 根据 div 中的行数显示“阅读更多”按钮
- android - 调用需要权限,这可能会被 android API 28 中的用户拒绝
- visual-studio-code - vscode 跳转到当前文件的 git/源代码控制快捷方式/命令
- c# - Azure 移动服务器 SDK:何时评估 IQueryable?