Morris
Morris

Reputation: 601

Import/export modules - Typescript

when i try to import an external module and when a try to compile my code, appear this error message: app.ts:1 Uncaught ReferenceError: require is not defined at app.ts:1 . The typescript version is: 2.1.6 .

my app.ts file:

import {PI, calcCircumference } from "./math/circle";

console.log(PI);
console.log(calcCircumference(10));
//console.log();

my circle.ts file

export const PI: number = 3.14;

export function calcCircumference(diameter: number) {

    return diameter * PI;
};

my tsconfig.json file

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": true
    }
}

Thanks all

Upvotes: 0

Views: 125

Answers (1)

Amid
Amid

Reputation: 22352

I assume you are trying to run your code in the client environment - your browser. In this case you have to configure module loader because unlike server environment like node.js browsers do not (yet) support module loading by default and do not know how to 'require' particular module.

You have several options here:

  1. Bundling tools like browserify / webpack
  2. Loaders like requirejs / systemjs

Google and you will find lots of tutorials on how to setup typescript with one of the above (for example: systemjs, webpack)

My personal preference is systemjs (with jspm as package manager) - but your choice will greatly depend on the specific requirements for the application you build.

Upvotes: 1

Related Questions