Logo of knitwork

knitwork

生成 JavaScript 代码的实用工具。

生成 JavaScript 代码的实用工具。

安装

# npm
npm install knitwork

# yarn
yarn add knitwork

# pnpm
pnpm install knitwork

用法

生成 ESM 语法

import { genImport, genExport } from 'knitwork'

// import foo from "pkg"
console.log(genImport('pkg', 'foo'))

// import { foo } from "pkg"
console.log(genImport('pkg', ['foo']))

// import { a, b } from "pkg"
console.log(genImport('pkg', ['a', 'b']))

// import foo as bar from "pkg";
console.log(genImport('pkg', { name: 'foo', as: 'bar' }))

// import { foo as bar } from "pkg";
console.log(genImport('pkg', [{ name: 'foo', as: 'bar' }]))

// import foo from "pkg" assert { type: "json" };
console.log(genImport('pkg', 'foo', { assert: { type: 'json' } }))

// export foo from "pkg"
console.log(genExport('pkg', 'foo'))

// export { a, b } from "pkg"
console.log(genExport('pkg', ['a', 'b']))

// export * as bar from "pkg"
console.log(genExport('pkg', { name: '*', as: 'bar' }))

// export foo from "pkg" assert { type: "json" };
console.log(genExport('pkg', 'foo', { assert: { type: 'json' } }))

生成 TS

import { genInterface, genAugmentation, genInlineTypeImport, genTypeImport, genTypeExport } from 'knitwork'

// interface FooInterface extends A, B {
//   name: boolean
//   optional?: string
// }
console.log(genInterface('FooInterface', { name: 'boolean', 'optional?': 'string' }, { extends: ['A', 'B'] }))
// declare module "my-module" {
//   interface MyInterface {}
// }
console.log(genAugmentation('my-module', { MyInterface: {} }))
// typeof import("my-module").genString'
console.log(genInlineTypeImport('my-module', 'genString'))
// typeof import("my-module").default'
console.log(genInlineTypeImport('my-module'))
// import type { test as value } from "my-module";
console.log(genTypeImport('my-module', [{ name: 'test', as: 'value' }]))
// export type { test } from "my-module";
console.log(genTypeExport('my-module', ['test']))

序列化 JS 对象

import { genObjectFromRaw, genObjectFromRawEntries, genArrayFromRaw } from 'knitwork'

// { test: () => import("pkg") }
console.log(genObjectFromRaw({ test: '() => import("pkg")' }))

// { 0: [ test, () => import("pkg") ] }
console.log(genObjectFromRaw([ ['test', '() => import("pkg")'] ]))

const entries = Object.entries({
  a: 1, b: null, c: '"c"', nest: { hello: '"world"', fn: () => 1 }
})
// { a: 1, b: null, c: "c", nest: { hello: "world", fn: () => 1 } }
console.log(genObjectFromRawEntries(entries))

// [ 1, 2, () => import("pkg") ]
console.log(genArrayFromRaw(['1', '2', '() => import("pkg")']))

生成安全的变量名

import { genSafeVariableName } from 'knitwork'

// _123_32foo
genSafeVariableName('123 foo')
// _for
genSafeVariableName('for')

开发

  • 克隆此仓库
  • 安装最新 LTS 版本的 Node.js
  • 使用 corepack enable 启用 Corepack
  • 使用 pnpm install 安装依赖
  • 使用 pnpm dev 运行交互式测试

许可

用心制作 💛

根据 MIT 许可证 发布。