标签: ts-node

如何在 ts-node 中使用三斜线指令

我正在研究 typescript 及其模块系统。

与此同时,我发现了三斜杠指令。

我只是认为这是导入/导出的另一种表达方式。但它不起作用。在下面的代码中,我想在 test.ts 文件中使用名称空间 Myconsole。


// Myconsole.ts

namespace MyConsole {
  export function log(msg: string) {
    console.log(msg);
  }
}



// test.ts
/// <reference path="Myconsole.ts" />



MyConsole.log("log"); // ReferenceError occurs here. but no redline

namespace MyConsole2 { 
  export function foo(msg: string) {
    console.log(msg);
  }
}

MyConsole2.foo("ging"); // but this one works.  

Run Code Online (Sandbox Code Playgroud)

但当我跑的时候ts-node test.ts 它吐了出来Reference Error: Myconsole is not defined

让我更困惑的是遵守tsc -d命令正在工作。

// test.js

/// <reference path="Myconsole.ts" /> // Do .ts file available in .js ...? …
Run Code Online (Sandbox Code Playgroud)

typescript ts-node

6
推荐指数
1
解决办法
1881
查看次数

Jest - Angular 9 - 类构造函数 SomeComponentClass 无法在没有“new”的情况下调用

我正在将我们的业力测试迁移到旧的 Angular 9 应用程序中的 Jest,并且面临一些测试失败的问题,并出现以下类型的异常:

类型错误:类构造函数 SomeComponentClass 无法在没有“new”的情况下调用

我遵循 Jest 设置指南并参考了其他一些独立指南,我的设置如下:

笑话配置.js

module.exports = {
    preset: "jest-preset-angular",
    setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
    globals: {
      'ts-jest': {
        tsconfig: '<rootDir>/src/tsconfig.spec.json',
        stringifyContentPathRegex: '\\.(html|svg)$',
      },
    },
    coverageDirectory: 'coverage',
    coverageReporters: ["html", "text-summary", "json-summary", "cobertura"],
    transform: {
        '^.+\\.(ts|js|html)$': 'jest-preset-angular',
    },
    snapshotSerializers: [
      'jest-preset-angular/build/serializers/no-ng-attributes',
      'jest-preset-angular/build/serializers/ng-snapshot',
      'jest-preset-angular/build/serializers/html-comment',
    ],
    testEnvironment: "jsdom",
    transformIgnorePatterns: [
        "node_modules/(?!@o3|@al|ui-metadata)"
    ],
    testPathIgnorePatterns: [
        "<rootDir>/node_modules/",
        "<rootDir>/dist/",
        "<rootDir>/cypress/",
        "<rootDir>/src/test.ts/"
    ],
    reporters: [ "default" ],
    testMatch: [
        "<rootDir>/src/exposures/**/*.spec.ts"
    ]
  };
Run Code Online (Sandbox Code Playgroud)

测试设置.ts

import 'jest-preset-angular/setup-jest';
import '@angular/localize/init';
Object.defineProperty(window, 'CSS', { value: null }); …
Run Code Online (Sandbox Code Playgroud)

jestjs babel-jest ts-node angular ts-jest

5
推荐指数
1
解决办法
1227
查看次数

ts-node应该检查baseUrl tsconfig.json属性吗?

我正在使用ts-node而且tsconfig.json我已经使用过了"baseUrl": "./src".这样我可以在src不使用的情况下导入兄弟./.但是ts-node似乎没有使用该baseUrl属性来解析兄弟导入,所以我得到这样的错误:

    > tsmochanyc@1.0.0 test /home/ole/Junk/tsmochanyc
    > mocha -r ts-node/register src/**/*.spec.ts

    Error: Cannot find module 'hello'
        at Function.Module._resolveFilename (internal/modules/cjs/loader.js:548:15)
Run Code Online (Sandbox Code Playgroud)

好奇这是否是一个ts节点错误或我是否应该做一些不同的事情?

javascript typescript ts-node

5
推荐指数
1
解决办法
964
查看次数

使用 ts-node 时通过 fork() 调用子进程

我有一个打字稿项目,而不是tsc首先使用,我只是ts-node直接运行通过。

在我的代码中,我需要使用fork().

如果我喜欢运行的代码child_process.fork('ChildProcess.ts'),并ChildProcess.ts包含一些打字稿只有结构(如:import {}export,...),然后解释之中node,而不是ts-node将失败。

可能建议使用类似的东西child_process.exec('node ./node_modules/.bin/ts-node ChildProcess.ts),但我真的想要/需要在父进程和子进程之间设置的 IPC 通信通道,当fork()专门使用时。

关于如何实现这一目标的任何想法?

谢谢!

child-process node.js typescript ts-node

5
推荐指数
1
解决办法
4050
查看次数

TypeError:对象原型只能是Object或为null:未定义

在下面的示例中,如果我导入,则会Entity得到帖子的主题错误(TypeError:对象原型可能只是一个Object或null:未定义),但是如果我将导入替换为实际的Entity声明,则代码可以正常运行。

Stackblitz演示在这里

这是Customer.ts在当我运行的代码产生错误的形式ts-node

索引

export { Customer } from "./Customer";
export { Entity } from "./Entity";
Run Code Online (Sandbox Code Playgroud)

客户

import { Entity } from "./index";

export class Customer extends Entity {
  sku: string;
  constructor(po: any) {
    super();
    this.sku = po.sku;
  }
}
Run Code Online (Sandbox Code Playgroud)

实体

export abstract class Entity {
  id?: string;
}    
Run Code Online (Sandbox Code Playgroud)

Run.ts(测试代码)

import {Customer} from "./";

let c = new Customer({
  name: "Bob"
});
console.log(c);
Run Code Online (Sandbox Code Playgroud)

如果我用这样Entity的声明替换导入:

export abstract class Entity { …
Run Code Online (Sandbox Code Playgroud)

javascript node.js typescript ts-node

5
推荐指数
1
解决办法
7960
查看次数

NestJS启动令人难以置信的开发速度

我在开发环境中的应用程序在启动阶段非常缓慢。我在各个地方设置了一些调试日志,以查看花费了很多时间,并且发现我main.ts实际上花了将近9分钟的时间app.module导入我的!

资源

import { performance } from 'perf_hooks';
const startTime = performance.now();

import { Log } from 'api/common/util/logger/log';
Log.log.info(`??????????????????????????????????????????????????????????????`);
Log.log.info(`?    Starting: ${new Date().toISOString()}                      ?`);
Log.log.info(`??????????????????????????????????????????????????????????????`);

// From here -------------------->
import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import 'reflect-metadata';
import { existsSync, mkdirSync, writeFile } from 'fs';
import * as express from 'express';
import * as bodyParser from 'body-parser';
import * as helmet from 'helmet';
import * as morgan from …
Run Code Online (Sandbox Code Playgroud)

node.js typescript ts-node nestjs

5
推荐指数
2
解决办法
1722
查看次数

打字稿路径在Express项目中不起作用

我正在尝试使用打字稿路径功能,以便不再需要使用相对导入。

这是我的tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "outDir": "./dist",
    "rootDir": ".",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "baseUrl": ".",
    "allowJs": true,
    "paths": {
      "*": ["node_modules/*", "src/*"],
      "@config/*": ["src/config/*"],
      "@controllers/*": ["src/controllers/*"],
      "@middlewares/*": ["src/middlewares/*"],
      "@models/*": ["src/models/*"],
      "@routes/*": ["src/routes/*"],
      "@types/*": ["src/types/*"],
      "@utils/*": ["src/utils/*"]
    }
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "firebase-config.json", "webpack.config.js"]
}
Run Code Online (Sandbox Code Playgroud)

这是我的package.json

{
  "name": "express-ts-boilerplate",
  "version": "0.1.0",
  "description": "Express Typescript Boilerplate",
  "main": "src/server.js",
  "author": "Sriram R",
  "scripts": {
    "start": "NODE_ENV=production node dist/src/app.js",
    "dev": "nodemon src/app.ts",
    "build": …
Run Code Online (Sandbox Code Playgroud)

typescript nodemon ts-node

5
推荐指数
2
解决办法
334
查看次数

为什么 TypeScript 有时只能通过字符串索引对象

当字符串是常量或简单的字符串变量时,为什么 TypeScript 可以按字符串索引类型化对象,但如果该字符串从数组中拉出,则无法按字符串索引类型化对象

也就是说,考虑下面的代码

class Foo {
    public bar: string = 'hello';

    public test() {
        // this works
        console.log(this['bar'])

        // this also works
        const index = 'bar';
        console.log(this[index])

        // in both cases above I have successfully used
        // a string as an index for my type Foo

        // However, this doesn't work
        const props:string[] = ['bar']
        for(const [key,value] of props.entries()) {
            console.log(value); // prints 'bar' to terminal/console
            console.log(this[value])
        }

        // Nor does this
        for(let i=0;i<props.length;i++) {
            console.log(this[props[i]])
        }

        // when …
Run Code Online (Sandbox Code Playgroud)

javascript types typescript ts-node

5
推荐指数
1
解决办法
3768
查看次数

mocha 和 ts-node UnhandledPromiseRejectionWarning:TypeError: 无法将 undefined 或 null 转换为对象

我正在尝试使用 mocha 设置 ts-node 但是测试脚本总是失败。

我试过了

mocha --require ts-node/register --extensions ts,tsx --watch --watch-files src 'src/**/*.spec.{ts,tsx}'
Run Code Online (Sandbox Code Playgroud)

mocha --require ts-node/register src/**/*.spec.ts
Run Code Online (Sandbox Code Playgroud)

我也尝试在本地和全局安装 ts-node 但总是这是输出

> project@1.0.0 test /home/moamen/foo/baz
> mocha --require ts-node/register src/**/*.spec.ts

(node:48106) UnhandledPromiseRejectionWarning: TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at Object.help (/home/moamen/foo/baz/node_modules/yargs/lib/usage.js:240:22)
    at Object.self.showHelp (/home/moamen/foo/baz/node_modules/yargs/lib/usage.js:432:15)
    at Array.<anonymous> (/home/moamen/foo/baz/node_modules/mocha/lib/cli/cli.js:53:13)
    at Object.fail (/home/moamen/foo/baz/node_modules/yargs/lib/usage.js:41:17)
    at /home/moamen/foo/baz/node_modules/yargs/lib/command.js:246:36
(Use `node --trace-warnings ...` to show where the warning was created)
(node:48106) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by …
Run Code Online (Sandbox Code Playgroud)

mocha.js typescript ts-node

5
推荐指数
1
解决办法
1324
查看次数

更改后 ts-node-dev 不会重新启动

这是我的文件:

包.json :

"scripts": {
  "generate-interfaces": "ts-node src/cli/generate-interfaces.ts",
  "dist": "npm run generate-interfaces && rm -rf dist && tsc && cp -r static/ dist/ && cp -r resource/ dist/",
  "prestart": "npm run generate-interfaces",
  "start": "ts-node-dev --respawn --transpileOnly --no-notify ./src/index.ts",
  "start:inspect": "ts-node-dev --no-deps --inspect -- ./src/index.ts",
  "pretest": "npm run generate-interfaces",
  "test": "jest"
 }
Run Code Online (Sandbox Code Playgroud)

配置文件

{
"compilerOptions": {
"declaration": true,
"target": "es2017",
"module": "commonjs",
"esModuleInterop": true,
"outDir": "dist",
"sourceMap": true,
"skipLibCheck": true,
"typeRoots": ["node_modules/@types", "./typings", "node_modules/**/*.d.ts"],
"lib": ["esnext"]
},
"include": ["src/**/*.ts", "./typings/**/*.d.ts"],
"exclude": …
Run Code Online (Sandbox Code Playgroud)

node.js typescript tsc nodemon ts-node

5
推荐指数
2
解决办法
4900
查看次数