简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM