TypeScript exports is not defined

I now use Parcel to do the ugly stuff of transcoding etc. My easiest config is the following:

tsconfig.json

{
    "compilerOptions": {
        "target": "es5",
        "sourceMap": true,
        "noImplicitAny": true,
        "noImplicitReturns": true,
        "lib": [
            "es2015",
            "es5",
            "es6",
            "dom"
        ],
        "noUnusedLocals": true,
        "module": "commonjs",
        "strict": false
    },
    "include": [ "lib/*", "./main.ts" ]
}

and in your HTML file, instead of importing the '.js', simply import the '.ts', like this:

<script src="main.ts"></script>

then, run Parcel with this command line:

parcel index.html

the Parcel bundler will create a dist directory containing all your needed files (html and transcoded JavaScript) and it will run a local webserver at:

http://localhost:1234

with hot module reloading (in your browser window).

When you finish your work, you just have to deploy the dist directory ;-)


TypeScript by default uses node module resolution. Node.js / CommonJS uses exports keyword. However, CommonJS doesn't run in browser without a module loader or module bundler. Hence, you need browserify or webpack to get it running in browser.

Check out this link https://www.typescriptlang.org/docs/handbook/gulp.html

You can also set module setting to none in compiler options section in tsconfig.json:

{ "compilerOptions": { "target": "es5", "module": "none" } }


try the following changes

HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    @RenderBody()

    <!-- <script src="~/scripts/user.js"></script> --> <!-- not longer needed -->
    <script src="~/scripts/main.js"></script>
</body>
</html>

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "outFile": "~/scripts/main.js",
    "lib": [
      "dom",
      "es2015",
      "es5",
      "es6"
    ]
  }
}

with this config your output is only one js file what can be uglified wunderfull, containing all referenced files in the main.ts. i just don't know if ~/ works or if you have to set the path relative to the config file, i'm not working with linux.

User.ts

class User {
    firstName: string;
    lastName: string;
}

Main.ts:

/// <reference path="User.ts" />

// import { User } from "./user"; // not needed if referenced
console.log(new User());

all reference declarations have to be written at the beginning of the file


You have a couple of options:

Option 1: Use a module loader like Webpack, Browserify, etc.

Option 2: If you just want to compile *.ts to *.js without any module imports or exports, set compilerOptions.module to "none" in your tsconfig.json. Note that you won't be able to export/import modules when you set compilerOptions.module to "none".