Typescript is the current industry standard for creating JavaScript applications. It enhances our JavaScript code by adding types, enabling us to build large-scale products that are more maintainable and less error-prone.
In this article, we will discuss how to set up a TypeScript project for an Express app in a few simple steps.
package.json
file
mkdir typescript-express-server
cd typescript-express-server
npm init -y
The npm init -y prompt creates a new package.json file with the following content:
{
"name": "article",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
...
}
There are two ways to do this:
If you install TypeScript globally, you don't have to reinstall it for every project. To install TypeScript globally, run the following command:
npm i -g typescript
You can also install TypeScript locally for only the current project using the following command:
npm i -D typescript
npm i express; npm i -D ts-node @types/express
The -D
flag indicates that we're going to need ts-node
and @types/express
only in development mode. We'll use it to compile and run our TypeScript code.
If you installed TypeScript globally, generate the tsconfig.json
file with the following command:
tsc --init
If you installed it locally, use the following command instead:
npx tsc --init
The ts.config
serves as the configuration file for the TypeScript compiler. You can modify this file to customize the compiler settings for your project. It comes with a lot of commented-out options. Comment out and edit the following options:
{
"compilerOptions": {
....
"module": "NodeNext",
"rootDir": "./src",
"moduleResolution": "NodeNext",
"outDir": "./dist",
....
}
}
In the tsconfig.json
file above, the settings:
"rootDir": "./src"
specifies that the TypeScript compiler will look for source files in the ./src
directory."outDir": "./dist"
specifies that the compiled JavaScript files will be output in the ./dist
directory.
Later, we'll set up an npm run build
command in our package.json
that will trigger the compilation process, using these settings to transform our TypeScript code into JavaScript files in the ./dist
directory.Currently, here's a recommended file structure for your project, omitting the node_modules
directory:
├── .env
├── .gitignore
├── package-lock.json
├── package.json
├── src
│ └── index.ts
└── tsconfig.json
package.json
file
{
"name": "article",
"version": "1.0.0",
"main": "dist/index.js",
"type": "module",
"scripts": {
"dev": "node --loader=ts-node/esm --env-file=.env --watch src/index.ts",
"build": "tsc",
"start": "node dist/index.js"
},
...
}
Here's a summary of the changes made in the package.json
file:
"main": "dist/index.js"
to point to the compiled JavaScript file."type": "module"
to enable ES6 imports and exports.“dev”
: Runs the development server with node
and:
—-loader=ts-node/esm
for compiling and running
TypeScript code.--env-file=.env
to load environment variables from the
.env
file.--watch
to reload code after every change.src/index.ts
as the entry point.“build”
: Compiles TypeScript code to JavaScript and outputs
it to the ./dist
folder using tsc
(or npx tsc
if
installed TypeScript locally on the current project).“start”
: Starts the server in production mode.In your src/index.ts
file, write the following lines of code:
import express, { urlencoded, json } from "express";
const port = process.env.PORT || 8000;
const app = express();
app.use(urlencoded({ extended: true }));
app.use(json());
app.get("/", (req, res) => {
res.status(200).json({ msg: "Server is up and running" });
});
app.listen(port, () => {
console.log(`Server is listening at port ${port}`);
});
In your .env file, write the following line:
PORT=3000
npm run dev
If everything is working fine you should see Server is listening at port 3000
on your terminal.
Now that your application is running, you can verify that it's working by accessing the URL: http://localhost:3000/
.
You can use:
This article has guided you through setting up a TypeScript project with Node.js and Express.js, minimizing unnecessary package installations. You've learned to create a efficient development workflow, leveraging TypeScript's benefits while keeping your project lightweight.
I hope you found this tutorial helpful in getting started with TypeScript and Express.js. Happy coding!
Источник: dev.to
Наш сайт является информационным посредником. Сообщить о нарушении авторских прав.
typescript express webdev javascript