How to set up a JavaScript/TypeScript project

Running a Javascript file Suppose you have a javascript file that you want to run from the command line. Install node or deno Run the file with node <filepath.js> or deno <filepath.js> or deno run <filepath.js> Running a TypeScript file Suppose you have a typescript file that you want to run from the command line. Install node. npm comes bundled with node. Install the typescript compiler with npm install -g typescript. Note that this will install the latest version of typescript compiler globally. Compile the file with tsc <filepath.ts> Run the file with node <comiled-filepath.js> Alternatively, you can install the ts-node package with npm install -g ts-node. This will install the latest version of ts-node globally. ts-node compiles the file on the file and executes it. ts-node <filepath.ts> Running a Javascript project The project directory must have a package.json file. This file is used by npm and can also be used to define additional information if you plan to publish the module to npm registry. Install the dependencies mentioned in the package.json file with npm install, more details about package.json The package.json file have a scripts section, this defines the commands that can be run with npm run <command>. In this section, you can define commands like start: node index.js; test: jest ., then if you run npm run test it will run the tests. Note, npm defines three commands which can be run without using the run command, npm start, npm test and npm stop. The start command defaults to using index.js file The package.json file has a main field, this is the file that is executed when you import the package in another file. By default, npm treats the imports as CommonJS modules, if you are using ES modules, you need to add the type key in your package.json with value module. Then all files must use import/export syntax. { name: "my-package", version: "1.0.0", main: "index.js", scripts: { start: "node index.js", test: "jest .", }, type: "module", dependencies: { jest: "^27.5.1", }, } Running a TypeScript project Using ts-node [!NOTE] You can avoid using ts-node and use tsx which supports TypeScript out of the box. No need to add additional support for esm modules ...

November 14, 2024 · 3 min · 621 words · Mohit Sharma