2

Writing a PacMan game in TypeScript, my app.ts file has in import for the PacMan class like this:

import { PacMan } from "./pacman"

Using TypeScript 4.9.4 and for some reason unknown to me, I needed to configure NodeJS 18.12.1, this gets compiled in WebStorm 2022.3 to a line

var pacman_1 = require("./pacman");

For that line, my browser (Firefox 108.0) throws an exception

ReferenceError: require is not defined

I read some stuff but honestly, I hardly understand anything.

I tried suggestions for changes in tsconfig.json, so I set "target": "es5", and "esModuleInterop": true, but that didn't result in any better in the browser. My full config is currently

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "inlineSources": true,
    "esModuleInterop": true,
  },
  "compileOnSave": true,
  "exclude": [
    "node_modules"
  ]
}

I think the problem lies in the choice of the module. I don't know what CommonJS or RequireJS or an AMD is, nor how I would configure that correctly. I don't know the difference between ES5 and ES6, so it's guesswork for me, or "trial and error".

I thought TypeScript would compile to JavaScript. Can I configure "module" to VanillaJS maybe? Or do I really have to go with a dependency like RequireJS? If so, why doesn't the TypeScript compiler compile that dependency into the resulting JavaScript?

4
  • The native JavaScript module system is ES6. Alternatively, you can bundle your code. CommonJS is a module system specific to Node.js. There wasn't any VanillaJs module system before ES6. Commented Dec 16, 2022 at 21:16
  • @jabaa: oh, you mean I should put "es6" into "module", not "target"? Holy cow ... Commented Dec 16, 2022 at 21:28
  • 1
    target and module should be set to ES6. Commented Dec 16, 2022 at 21:29
  • sh§$%&, yes, that works. I get some other errors now, but that's ok. I can look into those. Commented Dec 16, 2022 at 21:30

1 Answer 1

1

I can't believe that it so simple and not documented in module. Thanks to @jabaa, I simply used "module": "es6" in my tsconfig.json and that fixed it.

{
  "compilerOptions": {
    "module": "es6",
    "target": "es6",
    "sourceMap": true,
    "inlineSources": true,
    "esModuleInterop": true,
  },
  "compileOnSave": true,
  "exclude": [
    "node_modules"
  ]
}
Sign up to request clarification or add additional context in comments.

1 Comment

The section in your link describes TypeScript modules. You have to read the section about the transpiler configuration: typescriptlang.org/tsconfig#module

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.