node 搭建 ts 开发环境

新建空项目

使用 yarn init 初始化 一个node 项目

安装 依赖 yarn add typescript -D && yarn add ts-node -D && yarn add tslib @types/node -D

安装 全局 ts-node sudo npm install global ts-node

添加 tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "CommonJS",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "outDir": "./output",
    "types": [
      "node"
    ],
    "declaration": true,// 是否生成声明文件
    "declarationDir": "dist/type",// 声明文件打包的位置
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "exclude": [
    "node_modules"
  ]
}

新间 main.ts

import HandleThemes from "./lib/handleTheme";

const handles = new HandleThemes();
handles.getFolderFiles("/");

新建 lib/handleTheme.ts

import {readdir} from "fs";

export default class HandleThemes {
  public getFolderFiles(path: string): void {
    readdir(path, (errStatus, fileList) => {
      if (errStatus !== null) {
        console.log("文件读取失败, 错误原因: ", errStatus);
        return;
      }
      console.log("文件读取成功", fileList);
    });
  }
}

命令行使用 ts-node main.ts

$ ts-node main.ts
文件读取成功 [
  '.cpolar', '.local',   'bin',
  'boot',    'captures', 'dev',
  'efi',     'etc',      'home',
  'lib',     'lib64',    'lost+found',
  'mnt',     'opt',      'proc',
  'root',    'run',      'sbin',
  'srv',     'sys',      'tmp',
  'usr',     'var'
]


可以 在 packages 里面 加

  "scripts": {
    "start":"ts-node main.ts"
  },

来使用 webstorm 调试 和启动

简单demo 搭建成功 !

posted @ 2022-07-26 14:00  ifnk  阅读(751)  评论(0编辑  收藏  举报