The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum. When exporting a module using export = , TypeScript-specific import module = require("module") must be used to import the module.
"The marker property __esModule lets importing modules know that this is a transpiled ES module (which matters especially for default exports)." 2ality.com/2017/01/babel-esm-spec-mode.html.
The error "Module is not defined in ES module scope" occurs when we try to use the module. exports CommonJS syntax in ES modules. To solve the error, use the export keyword to export a member from a file, e.g. export const num = 42 .
If I write a .ts with any kind of import or export instruction the resulting .js will generate the following error when loaded in an HTML page: "ReferenceError: exports is not defined"
How to reproduce:
http-server -g [port]
) and reach your HTMLI tried:
"module": "commonjs"
from tsconfig.json`tsc
My .ts (can be anything if it has an import instruction):
import { setTimeout } from "timers"; setTimeout(() => console.log("asdf"), 1000);
The HTML just has a simple body referencing the script
My package.json
{ "name": "nodejs-web-app4", "version": "0.0.0", "description": "NodejsWebApp4", "main": "server.js", "author": { "name": "" }, "devDependencies": { "@types/node": "^8.0.14" } }
tsconfig.json
{ "compilerOptions": { "module": "commonjs", "target": "es6", "lib": ["es6"], "sourceMap": true }, "exclude": [ "node_modules" ] }
Resulting .js:
From VS build (results in ReferenceError: exports is not defined
):
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const timers_1 = require("timers"); timers_1.setTimeout(() => console.log("asdf"), 1000); //# sourceMappingURL=home-script.js.map
From command tsc [filename].ts
(results in ReferenceError: exports is not defined
):
"use strict"; exports.__esModule = true; var timers_1 = require("timers"); timers_1.setTimeout(function () { return console.log("asdf"); }, 1000);
From VS Build but removing "module": "commonjs"
from tsconfig (results in SyntaxError: import declarations may only appear at top level of a module
):
import { setTimeout } from "timers"; setTimeout(() => console.log("asdf"), 1000); //# sourceMappingURL=asdf.js.map
All the HTML and ts will be called as "static" (no MVC)
Is it wrong to use http-server
to see static HTML from my VS project? Is that the issue?
Should build any other way? Use a different setup?
I have a workaround (i.e., keep everything I need in the same TypeScript file), but it confuses me that I can't create and visualize a simple project with Node/TS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With