node: 将json转换ts

安装插件(前提存在pageage.json文件):

当前目录下安装插件: npm install  json2ts -D

当前目录,打开cmd:

新建文件夹 mkdir mock

当前目录新建入口文件: type nul > index.js

index.js

/* eslint-disable */
const fs = require('fs');
const json2ts = require('json2ts');

const mock_path = './mock';
const interface_path = './interface-type';

// fs.writeFileSync(mockPath, formatData, 'utf-8');
function mockToTs() {
  fs.readdir(mock_path, function (err, files) {
    files.forEach((name) => {
      const mockPath = `${mock_path}/${name}`;
      fs.readFile(mockPath, { encoding: 'utf-8' }, (err, data) => {
        const formatData = JSON.stringify(JSON.parse(data), null, 2);
        fs.writeFile(mockPath, formatData, () => {});
        const interfaceString = json2ts.convert(formatData);
        const tsPath = `${interface_path}/${name.replace('json', 'ts')}`;
        fs.writeFile(tsPath, interfaceString, () =>
          console.log('写入ts成功:', tsPath),
        );
      });
    });
  });
}

mockToTs();

运行: node index.js

 

 

 

posted @ 2022-02-21 11:51  vs1435  阅读(597)  评论(0编辑  收藏  举报