3

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
7
  • Can you post your tsconfig file? Commented Nov 30, 2017 at 7:32
  • I think your target should be ES5. Can you try this, if that can solve your issue? Commented Nov 30, 2017 at 7:44
  • @VinodBhavnani I just tried, the require statement remains. Commented Nov 30, 2017 at 7:45
  • try "target: "es5" and "module": "ES2015" Commented Nov 30, 2017 at 7:49
  • @Crappy that removed the require statement, but replaced it with a regular TypeScript import { } from "./helper" statement which wouldn't work on a website. Commented Nov 30, 2017 at 7:52

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Updated answer, tested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.