Reputation: 28128
I am figuring out how to build a typescript app where all classes are saved in separate .ts files. I am using VS Code. The compile task seems to be working correctly (.ts files get transpiled to .js files), but when I load my main.js file into my HTML page I get this javascript error:
Can't find variable: require
My typescript code:
// __________ car.ts __________
class Car {
color: string;
constructor(color: string) {
this.color = color;
console.log("created a new " + color + " car");
}
}
export = Car;
// __________ main.ts __________
import Car = require('car');
class Startup {
public static main(): number {
console.log('Hello World');
var c = new Car("red");
return 0;
}
}
My tsconfig file:
{
"compilerOptions": {
"module": "commonjs",
"sourceMap": true
},
"files": [
"car.ts",
"main.ts"
]
}
What step am I missing here? Why does javascript need something called 'require' ? Or is there another way to work with classes in separate files?
Upvotes: 2
Views: 5629
Reputation: 13211
EDIT: TypeScript-Handbook: Splitting Across Files:
To reference the file to each other while coding use ///<reference path="someOtherScript.ts" />
at the very top of each file
First, we can use concatenated output using the
--out
flag to compile all of the input files into a single JavaScript output file:tsc --out sample.js Test.ts
Put "outFile": "app.js"
in "compilerOptions": {
You can have all .ts
files compiled in one .js
file. That's what I'm using all the time. One JS-File but clean TypeScript-Code.
In Visual Studio it's <TypeScriptOutFile>myfile.js</TypeScriptOutFile>
. Might be similar in Visual Code?
Upvotes: 0
Reputation: 28656
require
function is a part of NodeJS. In order to make require
work in browsers, you need to install requirejs.
If you want to use internal modules, add outFile
to your tsconfig.json
:
{
"compilerOptions": {
"module": "commonjs",
"sourceMap": true,
"outFile": "app.js"
},
"files": [
"car.ts",
"main.ts"
]
}
and add <script src="app.js"></script>
in your index.html
file.
Upvotes: 1