typescript - 通过编译器 api 将 typescript 模块编译为纯 web javascript
问题描述
我有一个节点脚本,我想将一个带有导出函数的 ts 文件编译为 javascript,该函数可以在 Web 上使用/嵌入到脚本标签中。
const ts = require("typescript");
// hard coded for demonstration
const typescriptCode = `
export function add(a: number, b: number): number {
return a + b;
}`;
let result = ts.transpile(typescriptCode, {
compilerOptions: {
module: ts.ModuleKind.None,
target: ts.ScriptTarget.ES5
}
});
然而,即使ts.ModuleKind.None
在编译选项中使用,程序仍然会输出一个脚本,试图将函数绑定到导出。导出在网络上无效。的价值result
:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function add(a, b) {
return a + b;
}
exports.add = add;
我怎样才能只转换到这个/使result
成为:
function add(a, b) {
return a + b;
}
解决方案
您需要为 使用不同的值module
:
const source = `export function add(a: number, b: number): number {
return a + b;
}`;
transpile(source, { module: 'ESNext', target: 'ESNext' });
将产生:
export function add(a, b) {
return a + b;
}
推荐阅读
- java - 如何运行启动画面,然后是介绍滑块,然后是主要活动
- javascript - 如何在 SharePoint 上处理 JavaScript 预订系统的同时请求
- node.js - 猫鼬在哪里,我无法过滤数组
- javascript - 如何按单个页面对 Firestore 数据集进行分页?
- docker - 无法使用凭证存储在 Ubuntu 18 上登录 Docker
- javascript - 字符串中变量的值不变
- sql - 在 SQL (SSMS) 中通过 LIKE 运算符传递列表
- java - java.util.logger - FileHandler 没有创建文件,所以 Logger 可以写入它
- angular - Angular 2-6 中子组件的两种方式数据绑定和更改检测
- date - 如何使用matplotlib绘制自纪元以来以10秒为步长1小时的高分辨率日期时间?