编程语言
首页 > 编程语言> > node: 将json转换ts

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';

function formatMockData() {
  return new Promise((resolve, reject) => {
    fs.readdir(mock_path, function (err, files) {
      files.forEach((name) => {
        const fullPath = `${mock_path}/${name}`;
        const data = JSON.parse(fs.readFileSync(fullPath));
        const formatData = JSON.stringify(data, null, 2);
        fs.writeFileSync(fullPath, formatData, 'utf-8');
        resolve();
      });
    });
  });
}

async function mockToTs() {
  await formatMockData();
  const isExist = fs.existsSync(interface_path);
  if (!isExist) fs.mkdirSync(interface_path);
  fs.readdir(mock_path, function (err, files) {
    files.forEach((name) => {
      const fullPath = `${mock_path}/${name}`;
      const data = fs.readFileSync(fullPath, 'utf-8');
      const interfaceString = json2ts.convert(data);
      fs.writeFileSync(
        `${interface_path}/${name.replace('json', 'ts')}`,
        interfaceString,
        'utf-8',
      );
    });
  });
}

mockToTs();

运行: node index.js

 

 

 

标签:node,fs,const,ts,json,interface,path,fullPath,mock
来源: https://www.cnblogs.com/vs1435/p/15918238.html