0

I have a node script where I want to compile a ts file with a exported function to javascript that can be used on the web / embedded into a script tag.

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
    }
});

However even with ts.ModuleKind.None used in the compile options the program still outputs a script that attempts to bind the function to exports. Exports is not valid on the web. Value of result:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function add(a, b) {
    return a + b;
}
exports.add = add;

How can I only transpile to this / make result be:

function add(a, b) {
    return a + b;
}
3
  • What if you remove the export from the function ? Since you don't want modules you should not use module features such as imports and exports Commented Feb 15, 2020 at 21:44
  • I think you might be looking for something like the answer to this: stackoverflow.com/q/58793176/188246 (there is a transformers property on TranspileOptions). Commented Feb 15, 2020 at 22:06
  • @TitianCernicova-Dragomir Unfortunately that export is required by a separate process. I think my best bet is to remove export keywords from typescriptCode via regex replace before transpile. Commented Feb 15, 2020 at 22:09

1 Answer 1

1

You need to use a different value for module:

const source = `export function add(a: number, b: number): number {
  return a + b;
}`;

transpile(source, { module: 'ESNext', target: 'ESNext' });

Will yield:

export function add(a, b) {
  return a + b;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.