


Teach you step by step how to deploy a TS Node.js project correctly and quickly!
How to deploy a TS Node.js project correctly and quickly? The following article will teach you how to deploy a TS Node.js application in a few minutes. I hope it will be helpful to you!
As a full-stack developer, it is very interesting to create projects. You can design the architecture, brainstorm, and develop, but after the development is completed, we have to deploy or release application. So how to deploy a TS Node.js project correctly and quickly? Let’s get it done today. [Recommended learning: "nodejs Tutorial"]
Create a TS Node.js application
If you are already familiar with creating a TS Node.js project , you can jump directly to the "Deploy and Release Application" section
Initialize the Node.js project:
In our team, we really like TS and use it in all our new projects TS is used in every project, so creating a TS project is nothing new.
Let’s start with the basics:
npm init
Initialize a Node.js project using-y
Parameters can quickly skip step-by-step configuration##npm install express @types/express
Install express dependencies, and express types file for TS development
npm install typescript --save-dev
Install typescript as a development dependency
mkdir my-app && cd my-app npm init -y npm install express @types/express --save npm install typescript --save-dev
TS configuration
- npx tsc --init
will create a typescript default configuration file tsconfig.json
- declaration
used to specify whether to compile After completion, the corresponding *.d.ts file is generated. The default is false
- outdir
Define the directory after TS compilation. If there is no declaration, the default compiled file location will be the same as the ts source file. In the same location
npx tsc --initModify the following configuration
"compilerOptions": { ... "outDir": "dist", // 编译后输出目录 "declaration": true // 生成 d.ts }
Create the project entry file
Createserver.tsFile
import express from 'express' const app = express() const PORT = 3000 app.use(express.json()) app.get('/', (req, res) => { res.send(‘Hello World!’) }) app.listen(PORT, () => { console.log(`Server is listening on port ${PORT}`) })After completing the above steps, our file directory structure is as follows
. ├── node_modules ├── package-lock.json ├── package.json ├── server.ts └── tsconfig.json
Compile TS
Our next step is to build and deploy our TS Node.js application. Since in the production environment, we do not run the TS version, but the compiled JS. Now let’s compile the projectModify the package.json file and add the following commandnpm run tsc
will be compiled according to the configuration of our tsconfig.json Our project and output to the specified directory
- ##npm run start:prod
will run our compiled JS file
"scripts": { "tsc": "tsc", "start:prod": "node dist/server.js" }
Then test locally
npm run tsc npm run start:prod # 服务启动成功,运行端口:3000
Access http://localhost:3000/ through the browser, the access is successful, then we deploy and publish our application
Here we mainly use two methods to distribute and deploy the compiled TS project to various environments
The form of npm dependency package- docker container method
NPM life cycle hook
Some special life cycle hooks will be triggered when the specified operation is triggered. Here we will use the "prepare" hook, which will be triggered once before executing the npm publish command to publish to NPM. So we can compile the TS application at this time.
Specify publishing filesThrough the "files" field we can define which files should be included when publishing the NPM package. If this attribute is omitted, the default will be ["*" ], all files will be uploaded.
The following is the modified package.json
"name": "my-app-xiaoshuai", // 我们发布到NPM上的名字 "main": "dist/server.js", // 修改入口文件地址 "types": "dist/server.d.ts", // 指定TS类型文件 "files": [ "dist", "package.json", "package-lock.json", "README.md" ], "scripts": { "tsc": "tsc", "prepare": "npm run tsc" // 编辑typescript }npm publish
After modifying the package.json configuration, we run the npm publish command, Publish our application to NPM
npm publish
Output
After successful publishing, you can see that there is an additional
Package
To publish our TS Node.js application as a container, we need Create a docker configuration file Dockerfile in the project root directory.
Let’s write the Dockerfile step by step
- Copy the compiled file into the container
- Copy package.json and package-lock.json into the container
- Use
- npm install
Install dependencies
Use - node build/ server.js
Run our application
# Node 版本 FROM node:14.18.0-alpine ARG NODE_ENV=production ENV NODE_ENV $NODE_ENV COPY ./dist /dist COPY ./package.json /package.json COPY ./package-lock.json /package-lock.json RUN NODE_ENV=$NODE_ENV npm install EXPOSE 3000 CMD ["node", "dist/server.js"]
现在我们可以在根目录中构建docker镜像,运行 docker build --tag my-app:test .
命令
docker build --tag my-app:test .
成功后输出如下
接着我们运行容器,使用docker run -p 3000:3000 -it my-app:test
命令来运行我们的应用,可以看到程序成功运行在3000端口
docker run -p 3000:3000 -it my-app:test # 服务启动成功,运行端口:3000
通过浏览器访问http://localhost:3000/,访问成功
源码
https://github.com/cmdfas/ts-node-express-deploy
总结
今天我们介绍了创建TS Node.js项目和部署它的基础知识,希望对大家有所帮助,能够用在现在或未来的项目中。
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of Teach you step by step how to deploy a TS Node.js project correctly and quickly!. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor

Zend Studio 13.0.1
Powerful PHP integrated development environment