Javascript

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: 将json转换ts的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!