代码之家  ›  专栏  ›  技术社区  ›  Alexander Zeitler

将Node.js项目从普通ES6迁移到TypeScript

  •  6
  • Alexander Zeitler  · 技术社区  · 7 年前

    我所做的:

    npm install -g typescript
    npm install @types/node --save-dev
    

    安装程序 tsconfig.json

    {
         "compilerOptions": {
             "emitDecoratorMetadata": true,
             "experimentalDecorators": true,
             "moduleResolution": "node",
             "module": "commonjs",
             "target": "es6",
             "sourceMap": true,
             "outDir": "dist",
             "allowJs": true,
             "forceConsistentCasingInFileNames": true
         },
         "exclude": [
             "node_modules",
             "dist",
             "docs"
         ]
    }
    

    从更改所有文件扩展名 .js 到 .ts (除 node_modules

    find . -not \( -path node_modules -prune \) -iname "*.js" -exec bash -c 'mv "$1" "${1%.js}".ts' - '{}' \;
    

    跑步 tsc 现在会导致大量类似以下的错误:

    server.ts:13:7 - error TS2451: Cannot redeclare block-scoped variable 'async'.
    
    13 const async = require('async');
         ~~~~~
    

    bootstrap/index.ts:8:7
    8 const async = require('async');
            ~~~~~
    'async' was also declared here.
    

    同样的情况也发生在 retry 及其他 npm 包装:

    const retry = require('retry');
    

    require import 语句基本上修复了这些问题,但是一次迁移几千个文件是不可行的,所以我需要一种方法来坚持 有一段时间。这可能吗?

    4 回复  |  直到 7 年前
        1
  •  7
  •   Styx    7 年前

    这是可能的,但您仍必须编辑这些文件。

    1. 代替 const ... = require() 具有 import ... = require()

      import async = require('async');
      ...
      
    2. 添加 export {} 到文件的顶部:

      export {};
      const async = require('async');
      ...
      

    初始问题的原因是在TS中使用了不同的文件 不 模块,除非它们显式声明为模块,否则它们将在相同的全局范围内编译/执行,这就是为什么 tsc async 变量不能是

    从…起 documentation

    import 或 export 被认为是一个模块。相反地 进口 或 声明被视为一个脚本,其内容在全局范围内可用(因此也适用于模块)。

        2
  •  4
  •   Estus Flask    7 年前

    this one .

    为了被视为ES模块,文件应包含 import export 语句,否则,TypeScript编译器会将变量视为在全局范围内声明(即使在运行时并非如此)。

    解决方案与链接问题中的相同,即添加虚拟对象 export {} module.exports = ... 导出已在使用中,它们之间可能存在冲突。

    CommonJS的使用 require() @types/... 或内置打字。现有的NPM包可以与代码库中的正则表达式相匹配,以便安装相关的 @类型/。。。 const async = require('async') 可批量更换为 import async from 'async' . 这需要 esModuleInterop 和 allowSyntheticDefaultImports

        3
  •  1
  •   Gillsoft AB    7 年前

    异步的 是受保护的关键字。使用async/await时,可能会跳过“async”包。如果您正确使用ES6+ 您还重命名了所有文件*.mjs,例如index.mjs。如果您有index.js文件名,通常认为它不是ESM。您必须将类型/接口添加到所有ES6代码中,因此根据您的情况,一次生成所有类型/接口可能是不可行的,这就是我以ES2015+ESM符号给出示例的原因。

    对于TypeScript,您应该能够使用ESM,因为我想您需要更多最新的符号。为了在顶层使用async 异步函数 因为这样做而存在。

    import { createRequireFromPath } from 'module'; // ESM import
    import { fileURLToPath } from 'url';
    const require = createRequireFromPath(fileURLToPath(import.meta.url));
    // const untypedAsync = require('async');
    
    class Index {
    
      constructor() {
        this._server = null;
        this.host = `localhost`;
        this.port = 8080;
      }
    
      set server(value) { this._server = value; }
      get server() { return this._server; }
    
      async start() {
        const http = await import(`http`); // dynamic import
        this.server = http.createServer(this.handleRequest);
        this.server.on(`error`, (err) => {
            console.error(`start error:`, err);
        });
        this.server.on(`clientError`, (err, socket) => {
            console.error(`start clientError:`, err);
            if (socket.writable) {
                return socket.end(`HTTP/1.1 400 Bad Request\r\n\r\n`);
            }
            socket.destroy();
        });
        this.server.on(`connection`, (socket) => {
          const arrival = new Date().toJSON();
          const ip = socket.remoteAddress;
          const port = socket.localPort;
          console.log(`Request from IP-Address ${ip} and source port ${port} at ${arrival}`);
        });
        this.server.listen(this.port, this.host, () => {
          console.log(`http server listening at ${this.host}:${this.port}`);
        });
      }
    
      handleRequest(req, res) {
        console.log(`url:`, req.url);
        res.setHeader(`Content-Type`, `application/json`);
        res.writeHead(200);
        res.end(JSON.stringify({ url: req.url }));
      }
    }
    
    export default Index; // ESM export
    export const randomName = new Index(); // Usage: import { randomName } from './index.mjs';
    
    async function main() {
      const index = new Index();
      const cjs = require(`./otherfile.js`); // ES5/CommonJS import
      console.log(`otherfile:`, cjs);
      // 'async' can be used by using: cjs.untypedAsync
      await index.start();
    }
    
    main();
    
    // in otherfile.js
    const untypedAsync = require('async');
    const test = {
      url: "url test",
      title: "title test",
    };
    module.exports = { test, untypedAsync }; // ES5/CommonJS export.
    

    但是,在typescript中使用.mjs目前存在一些问题。请查看尚未解决的相关typescript问题: .mjs input files .mjs output files es6 to ts source

    // in package.json
    "files": [ "dist" ],
    "main": "dist/index",
    "types": "dist/index.d.ts",
    "scripts": {
        "mjs": "tsc -d && mv dist/index.js dist/index.mjs",
        "cjs": "tsc -m commonjs",
        "start": "node --no-warnings --experimental-modules ./dist/index.mjs"
        "build": "npm run mjs && npm run cjs"
    },
    "devDependencies": {
        "typescript": "^3.2.2"
    }
    
    // in tsconfig.json
    "compilerOptions": {
        "module": "es2015",
        "target": "ES2017",
        "rootDir": "src",
        "outDir": "dist",
        "sourceMap": false,
        "strict": true
    }
    
        4
  •  0
  •   Ashutosh    7 年前

    https://www.npmjs.com/package/javascript-to-typescript )这可以自动化一些工作。

    您可以编写脚本来打开项目中的每个文件并添加 export {}

    推荐文章