Ari Seyhun
Ari Seyhun

Reputation: 12511

Remove require statement from JavaScript files made in TypeScript

I'm developing a website and I am using TypeScript.

I use the tsc compiler and all my JavaScript compiles correctly, but if I use an import statement in my TypeScript, then it compiles into the JavaScript files as a require statement which is not usable in the web.

I am aware I can use something like browserify to fix this issue, but that includes the code of other JavaScript files when it see's a require statement. I'd prefer to just include each JavaScript file in my HTML with <script src="..."></script>.


How can I prevent TypeScript from generating require statements in the compiled JavaScript code?


Here are the contents of my tsconfig.json file:

{
    "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "lib": [
            "es6",
            "dom"
        ],
        "sourceMap": true,
        "outDir": "./typescript/compiled",
        "removeComments": true,
        "noImplicitAny": true,
        "noImplicitThis": true,
        "strictNullChecks": true,
        //"noEmit": true,
        "forceConsistentCasingInFileNames": true
    },
    "include": [
        "./typescript/**/*.ts"
    ]
}

main.ts

import { Helper } from "./helper";

var helper = new Helper();

helper.ts

export class Helper {
    // ...
}

main.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const helper_1 = require("./helper");
var helper = new helper_1.Helper();
//# sourceMappingURL=main.js.map

Upvotes: 3

Views: 1337

Answers (1)

Daniel Tran
Daniel Tran

Reputation: 6171

If you are not using modules in your javascript application. You don't even use import in your typescript file. Because using import mean you imports that file into your code.

If you want to have javascript file separately, use

/// <reference path=".. definition you want to refer ..." />

instead.

UPDATED

Since TypeScript 1.5 if you have your files in

"include": [
        "./typescript/**/*.ts"
    ]

You don't have to do reference ... any more.

Upvotes: 2

Related Questions