当前位置: 代码网 > it编程>前端脚本>Node.js > NodeJs从头到尾构建一个Typescript项目的全过程

NodeJs从头到尾构建一个Typescript项目的全过程

2025年04月24日 Node.js 我要评论
前言试想一下这么一个情况,你想要对一些数据或文件进行批量处理,但是你用的编程语言比较顺手的或者工作使用的编程语言是typescript或者javascript,因此想要使用typescript来实现这

前言

试想一下这么一个情况,你想要对一些数据或文件进行批量处理,但是你用的编程语言比较顺手的或者工作使用的编程语言是typescript或者javascript,因此想要使用typescript来实现这些操作。

当然,要想完成这个工作,哪怕你使用python,shell也是可以完成的,但是这里只谈论使用typescript.

现在就是这个情况,我想要写一个nodejs的ts项目,能够编译我写的代码,并且执行代码,得到我想要的结果。

一、明确需求

既然知道了目标,那么就要先明确一下需求。

现在就是这个情况,我想要写一个nodejs的ts项目,能够编译我写的代码,并且执行代码,得到我想要的结果。

从这里可得到以下信息:

  • 项目是使用nodejs,编程语言是typescript
  • 要能编译ts代码
  • 最后执行ts代码,得到想要的输出结果。

粗略设计

  • 首先定义一个build输出目录,遵从一般的项目标准,使用./dist
  • 定义一个入口文件,ts编译后是js,那么入口文件就是./dist/index.js
  • 使用命令来执行操作,一个build用来编译代码,一个dev来编译和执行。
  • 源码的入口文件是src/index.ts

二、创建项目

使用你的包管理工具(我使用的是pnpm,如果你使用的是npmyarn或者其他包管理工具,则执行相同的操作即可),初始化一个项目

1. 新建文件夹

mkdir my_project
cd my_project

2. 初始化项目

pnpm init

然后就是输入各种项目信息,创建完毕后当前目录会多出一个package.json文件,内容如下

{
  "name": "my_project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "isc"
}

3. 安装依赖

这里主要是安装typescript的编译依赖和支持nodejs库的一些依赖。

pnpm install typescript @types/node

然后使用npx来初始化一下typescript的配置文件

npx tsc --init

此时当前目录下会多出一个tsconfig.json,这个是全局的ts配置文件,内容如下

{
  "compileroptions": {
    /* visit https://aka.ms/tsconfig to read more about this file */

    /* projects */
    // "incremental": true,                              /* save .tsbuildinfo files to allow for incremental compilation of projects. */
    // "composite": true,                                /* enable constraints that allow a typescript project to be used with project references. */
    // "tsbuildinfofile": "./.tsbuildinfo",              /* specify the path to .tsbuildinfo incremental compilation file. */
    // "disablesourceofprojectreferenceredirect": true,  /* disable preferring source files instead of declaration files when referencing composite projects. */
    // "disablesolutionsearching": true,                 /* opt a project out of multi-project reference checking when editing. */
    // "disablereferencedprojectload": true,             /* reduce the number of projects loaded automatically by typescript. */

    /* language and environment */
    "target": "es2016",                                  /* set the javascript language version for emitted javascript and include compatible library declarations. */
    // "lib": [],                                        /* specify a set of bundled library declaration files that describe the target runtime environment. */
    // "jsx": "preserve",                                /* specify what jsx code is generated. */
    // "experimentaldecorators": true,                   /* enable experimental support for legacy experimental decorators. */
    // "emitdecoratormetadata": true,                    /* emit design-type metadata for decorated declarations in source files. */
    // "jsxfactory": "",                                 /* specify the jsx factory function used when targeting react jsx emit, e.g. 'react.createelement' or 'h'. */
    // "jsxfragmentfactory": "",                         /* specify the jsx fragment reference used for fragments when targeting react jsx emit e.g. 'react.fragment' or 'fragment'. */
    // "jsximportsource": "",                            /* specify module specifier used to import the jsx factory functions when using 'jsx: react-jsx*'. */
    // "reactnamespace": "",                             /* specify the object invoked for 'createelement'. this only applies when targeting 'react' jsx emit. */
    // "nolib": true,                                    /* disable including any library files, including the default lib.d.ts. */
    // "usedefineforclassfields": true,                  /* emit ecmascript-standard-compliant class fields. */
    // "moduledetection": "auto",                        /* control what method is used to detect module-format js files. */

    /* modules */
    "module": "commonjs",                                /* specify what module code is generated. */
    // "rootdir": "./",                                  /* specify the root folder within your source files. */
    // "moduleresolution": "node10",                     /* specify how typescript looks up a file from a given module specifier. */
    // "baseurl": "./",                                  /* specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* specify a set of entries that re-map imports to additional lookup locations. */
    // "rootdirs": [],                                   /* allow multiple folders to be treated as one when resolving modules. */
    // "typeroots": [],                                  /* specify multiple folders that act like './node_modules/@types'. */
    // "types": [],                                      /* specify type package names to be included without being referenced in a source file. */
    // "allowumdglobalaccess": true,                     /* allow accessing umd globals from modules. */
    // "modulesuffixes": [],                             /* list of file name suffixes to search when resolving a module. */
    // "allowimportingtsextensions": true,               /* allow imports to include typescript file extensions. requires '--moduleresolution bundler' and either '--noemit' or '--emitdeclarationonly' to be set. */
    // "resolvepackagejsonexports": true,                /* use the package.json 'exports' field when resolving package imports. */
    // "resolvepackagejsonimports": true,                /* use the package.json 'imports' field when resolving imports. */
    // "customconditions": [],                           /* conditions to set in addition to the resolver-specific defaults when resolving imports. */
    // "nouncheckedsideeffectimports": true,             /* check side effect imports. */
    // "resolvejsonmodule": true,                        /* enable importing .json files. */
    // "allowarbitraryextensions": true,                 /* enable importing files with any extension, provided a declaration file is present. */
    // "noresolve": true,                                /* disallow 'import's, 'require's or '<reference>'s from expanding the number of files typescript should add to a project. */

    /* javascript support */
    // "allowjs": true,                                  /* allow javascript files to be a part of your program. use the 'checkjs' option to get errors from these files. */
    // "checkjs": true,                                  /* enable error reporting in type-checked javascript files. */
    // "maxnodemodulejsdepth": 1,                        /* specify the maximum folder depth used for checking javascript files from 'node_modules'. only applicable with 'allowjs'. */

    /* emit */
    // "declaration": true,                              /* generate .d.ts files from typescript and javascript files in your project. */
    // "declarationmap": true,                           /* create sourcemaps for d.ts files. */
    // "emitdeclarationonly": true,                      /* only output d.ts files and not javascript files. */
    // "sourcemap": true,                                /* create source map files for emitted javascript files. */
    // "inlinesourcemap": true,                          /* include sourcemap files inside the emitted javascript. */
    // "noemit": true,                                   /* disable emitting files from a compilation. */
    // "outfile": "./",                                  /* specify a file that bundles all outputs into one javascript file. if 'declaration' is true, also designates a file that bundles all .d.ts output. */
    // "outdir": "./",                                   /* specify an output folder for all emitted files. */
    // "removecomments": true,                           /* disable emitting comments. */
    // "importhelpers": true,                            /* allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "downleveliteration": true,                       /* emit more compliant, but verbose and less performant javascript for iteration. */
    // "sourceroot": "",                                 /* specify the root path for debuggers to find the reference source code. */
    // "maproot": "",                                    /* specify the location where debugger should locate map files instead of generated locations. */
    // "inlinesources": true,                            /* include source code in the sourcemaps inside the emitted javascript. */
    // "emitbom": true,                                  /* emit a utf-8 byte order mark (bom) in the beginning of output files. */
    // "newline": "crlf",                                /* set the newline character for emitting files. */
    // "stripinternal": true,                            /* disable emitting declarations that have '@internal' in their jsdoc comments. */
    // "noemithelpers": true,                            /* disable generating custom helper functions like '__extends' in compiled output. */
    // "noemitonerror": true,                            /* disable emitting files if any type checking errors are reported. */
    // "preserveconstenums": true,                       /* disable erasing 'const enum' declarations in generated code. */
    // "declarationdir": "./",                           /* specify the output directory for generated declaration files. */

    /* interop constraints */
    // "isolatedmodules": true,                          /* ensure that each file can be safely transpiled without relying on other imports. */
    // "verbatimmodulesyntax": true,                     /* do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
    // "isolateddeclarations": true,                     /* require sufficient annotation on exports so other tools can trivially generate declaration files. */
    // "allowsyntheticdefaultimports": true,             /* allow 'import x from y' when a module doesn't have a default export. */
    "esmoduleinterop": true,                             /* emit additional javascript to ease support for importing commonjs modules. this enables 'allowsyntheticdefaultimports' for type compatibility. */
    // "preservesymlinks": true,                         /* disable resolving symlinks to their realpath. this correlates to the same flag in node. */
    "forceconsistentcasinginfilenames": true,            /* ensure that casing is correct in imports. */

    /* type checking */
    "strict": true,                                      /* enable all strict type-checking options. */
    // "noimplicitany": true,                            /* enable error reporting for expressions and declarations with an implied 'any' type. */
    // "strictnullchecks": true,                         /* when type checking, take into account 'null' and 'undefined'. */
    // "strictfunctiontypes": true,                      /* when assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictbindcallapply": true,                      /* check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
    // "strictpropertyinitialization": true,             /* check for class properties that are declared but not set in the constructor. */
    // "strictbuiltiniteratorreturn": true,              /* built-in iterators are instantiated with a 'treturn' type of 'undefined' instead of 'any'. */
    // "noimplicitthis": true,                           /* enable error reporting when 'this' is given the type 'any'. */
    // "useunknownincatchvariables": true,               /* default catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysstrict": true,                             /* ensure 'use strict' is always emitted. */
    // "nounusedlocals": true,                           /* enable error reporting when local variables aren't read. */
    // "nounusedparameters": true,                       /* raise an error when a function parameter isn't read. */
    // "exactoptionalpropertytypes": true,               /* interpret optional property types as written, rather than adding 'undefined'. */
    // "noimplicitreturns": true,                        /* enable error reporting for codepaths that do not explicitly return in a function. */
    // "nofallthroughcasesinswitch": true,               /* enable error reporting for fallthrough cases in switch statements. */
    // "nouncheckedindexedaccess": true,                 /* add 'undefined' to a type when accessed using an index. */
    // "noimplicitoverride": true,                       /* ensure overriding members in derived classes are marked with an override modifier. */
    // "nopropertyaccessfromindexsignature": true,       /* enforces using indexed accessors for keys declared using an indexed type. */
    // "allowunusedlabels": true,                        /* disable error reporting for unused labels. */
    // "allowunreachablecode": true,                     /* disable error reporting for unreachable code. */

    /* completeness */
    // "skipdefaultlibcheck": true,                      /* skip type checking .d.ts files that are included with typescript. */
    "skiplibcheck": true                                 /* skip type checking all .d.ts files. */
  }
}

文件中有一些注释,读者可自行观看,我们这里只实现我们的目的。

4. 创建项目结构

接下来创建项目的目录结构,其实最主要的就是创建src目录,然后在src目录下新建个index.ts,至于其他的目录我们还是要用代码去创建。目录结构创建好后,如下图所示

5. 配置ts

ts的配置的话主要是以下内容

  • 保存时编译
  • 语法用最新的
  • 开启sourcemap,方便调试
  • 设置输出目录
  • 设置源码目录
  • 设置包含的ts文件
  • 设置排除的ts文件

如果你有兴趣可以到上面的文档或者ts官方学习一下如何配置,我这里给出完整配置

{
  "compileonsave": true,
  "compileroptions": {
    "module": "es2022",
    "noimplicitany": true,
    "removecomments": true,
    "preserveconstenums": true,
    "sourcemap": true,
    "declaration": false,
    "emitdecoratormetadata": true,
    "experimentaldecorators": true,
    "target": "es2023",
    "moduleresolution": "node",
    "outdir": "./dist",
    "lib": ["esnext"],
    "esmoduleinterop": true,
    "rootdir": "./src"
  },
  "files": ["./src/index.ts"],
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules", "tmp"]
}

6. 配置项目启动命令

按照之前的需求,来编写项目启动命令。

{
  "name": "schemas",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"error: no test specified\" && exit 1",
    "dev": "tsc && node dist/index.js"
  },
  "keywords": [],
  "type": "module",
  "author": "",
  "license": "isc",
  "dependencies": {
    "typescript": "^5.6.3"
  },
  "devdependencies": {
    "@types/node": "^22.7.5"
  }
}

在工程的package.json中,scripts字段是定义执行的命令的,后面的命令代表两个意思

  • tsc 编译当前项目
  • node dist/index.js执行dist/index.js文件(这是因为编译了以后,输出的就是那个地方的index.js文件,这个在package.jsontsconfig.json中写了的,如果你不理解可以返回去看看)

7. 运行项目

在经过以上操作后,运行以下命令即可看到ts被编译执行了。

pnpm run dev

8. 测试多模块

对于一个ts项目来说,能创建多个ts文件是至关重要的,本来就是想着这么点便利的地方。

此时创建个test.ts文件,里面导出个test方法

const test_hello = (data: string) => {
    return `hello ${data}`;
}

export default test_hello;

然后在index.ts中测试

当前只能以js后缀导入,还是感觉不太舒服的,但是这就需要集成打包工具了,这就很麻烦。

总结 

到此这篇关于nodejs构建一个typescript项目的文章就介绍到这了,更多相关nodejs构建ts项目内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com