首页 > 解决方案 > 通过编译器 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;
}

标签: typescripttypescript-compiler-api

解决方案


您需要为 使用不同的值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;
}

推荐阅读