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?
CodePudding user response:
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"
]
}
CodePudding user response:
You need a module bundler. Luckily you don't need to do that your self, you can use vite. Vite will basically create you a development environment, where you don't need to do all that stuff like module bundling etc..., also it's blazingly fast.
Just type in your terminal: npm create vite@latest
and now you can choose your project setup.