简体   繁体   English

在具有.js文件的现有项目中使用打字稿

[英]Using typescript in the existing project that has .js files

I have an existing NodeJS project, which has .js files, written in ES6 . 我有一个现有的NodeJS项目,该项目具有用ES6编写的.js文件。 Now I want to start using typescript in the existing project. 现在,我想开始在现有项目中使用typescript How should I go about? 我该怎么办? Should I just start with .ts files in the same directory structure? 我是否应该以相同目录结构中的.ts文件开头?

One of the problems I noticed, is that tsc only considers the .ts files. 我注意到的问题之一是tsc仅考虑.ts文件。 So for tsconfig.json which looks something like: 因此,对于tsconfig.json ,它类似于:

    {
    "compilerOptions": {
        "target": "es2015",
        "outDir": "./dist",
        "allowJs": true,
        "module": "commonjs",
        "noEmitOnError": false,
        "noImplicitAny": false,
        "strictNullChecks": true
    },
    "include": [
        "app/"
    ] 
}

will only convert the .ts files and leave the other .js files that form the majority of the project. 只会转换.ts文件,而保留构成项目大部分的其他.js文件。 How should I approach this? 我应该如何处理?

First you need to add typescript as developer dependency by using this command to your project directory 首先,您需要使用此命令将Typescript作为开发人员依赖项添加到项目目录中

npm i --save-dev typescript

Then you convert all .js files to .ts files and then run this command. 然后,您将所有.js文件转换为.ts文件,然后运行此命令。 <your_project_path>/node_modules/.bin/tsc -p '<your_project_path>/tsconfig.json'

Remember to give absolute paths so that there won't be any ambiguity 记住要给出绝对的路径,以免产生歧义

After you run this command it will create .js files in your ./dist folder. 运行此命令后,它将在./dist文件夹中创建.js文件。 This is your output path given in "outDir": "./dist in your tsconfig.json file. It will keep the same directory structure which was in your app but with .js and .map files. 这是tsconfig.json文件中"outDir": "./dist中给出的输出路径。它将保留与app相同的目录结构,但带有.js.map文件。

I would recommend to use app/ folder to write all your code in typescript and while deploying run javascript files from ./dist folder ignoring the .map files. 我建议使用app/文件夹在./dist编写所有代码,并在从./dist文件夹部署运行javascript文件时忽略.map文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM