zixulu 0.0.3 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,11 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command } from 'commander';
3
- import { createPromptModule } from 'inquirer';
4
- import { readdirSync, mkdirSync, writeFileSync, statSync, readFileSync } from 'fs';
5
- import { execSync } from 'child_process';
3
+ import { writeFileSync } from 'fs';
6
4
 
7
5
  var name = "zixulu";
8
- var version = "0.0.2";
6
+ var version = "0.0.4";
9
7
  var main = "index.js";
10
8
  var license = "MIT";
11
9
  var type = "module";
@@ -39,360 +37,20 @@ var pkg = {
39
37
  dependencies: dependencies
40
38
  };
41
39
 
42
- const prompt = createPromptModule();
43
- const packageNameReg = /^[a-z0-9]{1}[-_a-z0-9]{0,213}$/i;
44
- const JavaScriptTargets = ["ES2015", "ES2016", "ES2017", "ES2018", "ES2019", "ES2020", "ES2021", "ES2022", "ES2023", "ESNext"];
45
- async function getPackageLatestVersion(name) {
46
- const response = await fetch(`https://registry.npmjs.org/${name}`);
47
- const data = await response.json();
48
- return data["dist-tags"].latest;
49
- }
50
- function getBuildJS(answer) {
51
- const { target, css } = answer;
52
- if (css) {
53
- return `import { execSync } from "child_process"
54
- import { copyFileSync, mkdirSync, readdirSync, rmSync, statSync } from "fs"
55
- import { join } from "path"
56
-
57
- try {
58
- rmSync("./dist", { recursive: true })
59
- } catch (error) {}
60
-
61
- execSync("npx tsc --sourceMap -module ${target} -outDir dist/esm && npx tsc --sourceMap -module CommonJS -outDir dist/cjs && npx tsc --declaration --emitDeclarationOnly -outDir dist")
62
-
63
- const src = "./src"
64
- const distEsm = "./dist/esm"
65
- const distCjs = "./dist/cjs"
66
-
67
- function bundleCSS(...paths) {
68
- const dir = readdirSync(join(src, ...paths))
69
- dir.forEach(name => {
70
- const status = statSync(join(src, ...paths, name))
71
- if (status.isFile() && name.endsWith(".css")) {
72
- for (let i = 0; i < paths.length; i++) {
73
- const d0 = readdirSync(join(distEsm, ...paths.slice(0, i)))
74
- if (!d0.includes(paths[i]) || !statSync(join(distEsm, ...paths.slice(0, i + 1))).isDirectory()) {
75
- mkdirSync(join(distEsm, ...paths.slice(0, i + 1)))
76
- }
77
- const d1 = readdirSync(join(distCjs, ...paths.slice(0, i)))
78
- if (!d1.includes(paths[i]) || !statSync(join(distCjs, ...paths.slice(0, i + 1))).isDirectory()) {
79
- mkdirSync(join(distCjs, ...paths.slice(0, i + 1)))
80
- }
81
- }
82
- copyFileSync(join(src, ...paths, name), join(distEsm, ...paths, name))
83
- copyFileSync(join(src, ...paths, name), join(distCjs, ...paths, name))
84
- return
85
- }
86
- if (status.isDirectory()) {
87
- bundleCSS(...paths, name)
88
- }
89
- })
90
- }
91
-
92
- bundleCSS()
93
- `;
94
- }
95
- return `import { execSync } from "child_process"
96
- import { rmSync } from "fs"
97
-
98
- try {
99
- rmSync("./dist", { recursive: true })
100
- } catch (error) {}
101
-
102
- execSync("npx tsc --sourceMap -module ${target} -outDir dist/esm && npx tsc --sourceMap -module CommonJS -outDir dist/cjs && npx tsc --declaration --emitDeclarationOnly -outDir dist")
103
- `;
104
- }
105
- async function getPackageJson(answer) {
106
- const { name, react, esm, cjs } = answer;
107
- const info = {
108
- name,
109
- version: "0.0.1",
110
- main: "dist/cjs/index.js",
111
- module: "dist/esm/index.js",
112
- types: "dist/index.d.ts",
113
- license: "MIT",
114
- type: "module",
115
- exports: {
116
- ".": {}
117
- },
118
- scripts: {
119
- build: "node ./build.js"
120
- },
121
- devDependencies: {}
122
- };
123
- if (esm) {
124
- info.exports["."]["import"] = {
125
- types: "./dist/index.d.ts",
126
- default: "./dist/esm/index.js"
127
- };
128
- }
129
- if (cjs) {
130
- info.exports["."]["require"] = {
131
- types: "./dist/index.d.ts",
132
- default: "./dist/cjs/index.js"
133
- };
134
- }
135
- if (react) {
136
- info.devDependencies["@types/react"] = `^${await getPackageLatestVersion("@types/react")}`;
137
- info.devDependencies["@types/react-dom"] = `^${await getPackageLatestVersion("@types/react-dom")}`;
138
- }
139
- info.devDependencies.typescript = `^${await getPackageLatestVersion("typescript")}`;
140
- return JSON.stringify(info, null, 4);
141
- }
142
- function getTSConfig(answer) {
143
- const { react, target } = answer;
144
- return `{
145
- "compilerOptions": {
146
- /* Visit https://aka.ms/tsconfig to read more about this file */
147
- /* Projects */
148
- // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
149
- // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
150
- // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
151
- // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
152
- // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
153
- // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
154
- /* Language and Environment */
155
- "target": "${target}", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
156
- // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
157
- ${react ? "" : "// "}"jsx": "react",${react ? " " : ""} /* Specify what JSX code is generated. */
158
- // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
159
- // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
160
- // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
161
- // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
162
- // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
163
- // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
164
- // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
165
- // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
166
- // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
167
- /* Modules */
168
- // "module": "commonjs", /* Specify what module code is generated. */
169
- "rootDir": "./src", /* Specify the root folder within your source files. */
170
- "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
171
- // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
172
- // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
173
- // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
174
- // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
175
- // "types": [], /* Specify type package names to be included without being referenced in a source file. */
176
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
177
- // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
178
- // "resolveJsonModule": true, /* Enable importing .json files. */
179
- // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
180
- /* JavaScript Support */
181
- // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
182
- // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
183
- // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
184
- /* Emit */
185
- // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
186
- // "declarationMap": true, /* Create sourcemaps for d.ts files. */
187
- // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
188
- "sourceMap": true, /* Create source map files for emitted JavaScript files. */
189
- // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
190
- // "outDir": "./dist", /* Specify an output folder for all emitted files. */
191
- // "removeComments": true, /* Disable emitting comments. */
192
- // "noEmit": true, /* Disable emitting files from a compilation. */
193
- // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
194
- // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
195
- // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
196
- // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
197
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
198
- // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
199
- // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
200
- // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
201
- // "newLine": "crlf", /* Set the newline character for emitting files. */
202
- // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
203
- // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
204
- // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
205
- // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
206
- // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
207
- // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
208
- /* Interop Constraints */
209
- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
210
- // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
211
- "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
212
- // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
213
- "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
214
- /* Type Checking */
215
- "strict": true, /* Enable all strict type-checking options. */
216
- // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
217
- // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
218
- // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
219
- // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
220
- // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
221
- // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
222
- // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
223
- // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
224
- // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
225
- // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
226
- // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
227
- // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
228
- // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
229
- // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
230
- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
231
- // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
232
- // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
233
- // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
234
- /* Completeness */
235
- // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
236
- "skipLibCheck": true /* Skip type checking all .d.ts files. */
237
- }
238
- }`;
239
- }
240
- function validateName(name) {
241
- name = name.trim();
242
- if (!packageNameReg.test(name)) {
243
- throw new Error("项目名称必须由数字、字母、下划线和中划线构成,且不能以下划线和中划线开头");
244
- }
245
- const dir = readdirSync("./");
246
- if (dir.includes(name) && statSync(`./${name}`).isDirectory() && readdirSync(`./${name}`).length > 0) {
247
- throw new Error("当前目录下存在同名文件夹,且文件夹非空");
248
- }
249
- }
250
- function validateTarget(target) {
251
- target = target.trim().toUpperCase();
252
- if (!JavaScriptTargets.includes(target)) {
253
- throw new Error("请输入有效的 JavaScript 版本");
254
- }
255
- }
256
- function getProjectAnswer(...exclude) {
257
- return prompt([
258
- {
259
- type: "input",
260
- name: "name",
261
- message: "请输入项目名称:",
262
- default: "my-project",
263
- validate: (input) => {
264
- try {
265
- validateName(input);
266
- return true;
267
- }
268
- catch (error) {
269
- return String(error);
270
- }
271
- }
272
- },
273
- {
274
- type: "list",
275
- name: "target",
276
- message: "JavaScript 版本:",
277
- choices: JavaScriptTargets,
278
- default: "ES2020"
279
- },
280
- {
281
- type: "confirm",
282
- name: "react",
283
- message: "是否为 react 项目:",
284
- default: false
285
- },
286
- {
287
- type: "confirm",
288
- name: "css",
289
- message: "是否打包 CSS:",
290
- default: false
291
- },
292
- {
293
- type: "confirm",
294
- name: "esm",
295
- message: "是否打包 ES Module:",
296
- default: true
297
- },
298
- {
299
- type: "confirm",
300
- name: "cjs",
301
- message: "是否打包 Common JS:",
302
- default: true
303
- },
304
- {
305
- type: "list",
306
- name: "install",
307
- message: "现在就安装依赖:",
308
- choices: ["Yarn", "Pnpm", "Npm", "No"],
309
- default: "Yarn"
310
- }
311
- ].filter(it => exclude.every(i => i !== it.name)));
312
- }
313
40
  const program = new Command();
314
41
  program.name("格数科技").version(pkg.version);
315
42
  program.option("-v, --version").action(() => {
316
43
  console.log(pkg.version);
317
44
  });
318
- program
319
- .command("create")
320
- .description("初始化 npm 项目")
321
- .option("-n --name <name>", "指定项目名称")
322
- .option("-r --react", "指定为 react 项目")
323
- .option("-c --css", "打包 CSS")
324
- .option("-t --target <target>", "指定 JavaScript 版本")
325
- .option("--no-esm", "不打包 ES Module")
326
- .option("--no-cjs", "不打包 Common JS")
327
- .action(async (options) => {
328
- const initAnswer = {};
329
- const exclude = [];
330
- if ("name" in options) {
331
- validateName(options.name);
332
- exclude.push("name");
333
- initAnswer.name = options.name.trim();
334
- }
335
- if ("react" in options) {
336
- initAnswer.react = true;
337
- exclude.push("react");
338
- }
339
- if ("css" in options) {
340
- initAnswer.css = true;
341
- exclude.push("css");
342
- }
343
- if ("target" in options) {
344
- validateTarget(options.target);
345
- exclude.push("target");
346
- initAnswer.target = options.target.trim().toUpperCase();
347
- }
348
- if (options.esm === false) {
349
- exclude.push("esm");
350
- initAnswer.esm = false;
351
- }
352
- if (options.cjs === false) {
353
- exclude.push("cjs");
354
- initAnswer.cjs = false;
355
- }
356
- if (options.esm === false && options.cjs === false) {
357
- throw new Error("必须选择 ES Module 和 Common JS 至少一种");
358
- }
359
- const answer = { ...initAnswer, ...(await getProjectAnswer(...exclude)) };
360
- const { name, react, install, esm, cjs } = answer;
361
- if (esm === false && cjs === false) {
362
- throw new Error("必须选择 ES Module 和 Common JS 至少一种");
363
- }
364
- const dir = readdirSync("./");
365
- if (!dir.includes(name)) {
366
- mkdirSync(`./${name}`);
367
- }
368
- mkdirSync(`./${name}/src`);
369
- writeFileSync(`./${name}/src/index.${react ? "tsx" : "ts"}`, 'export default "Hello, world!"');
370
- writeFileSync(`./${name}/build.js`, getBuildJS(answer));
371
- writeFileSync(`./${name}/package.json`, await getPackageJson(answer));
372
- writeFileSync(`./${name}/tsconfig.json`, getTSConfig(answer));
373
- writeFileSync(`./${name}/.gitignore`, "node_modules");
374
- if (install !== "No") {
375
- execSync(`${install.toLowerCase()} install`, { cwd: `./${name}` });
376
- }
377
- console.log("创建项目成功");
378
- });
379
- program
380
- .command("build")
381
- .description("更新打包命令")
382
- .option("--no-css", "不打包 CSS")
383
- .action(options => {
384
- const { css } = options;
385
- const dir = readdirSync("./");
386
- if (!dir.includes("package.json") || !statSync("./package.json").isFile()) {
387
- throw new Error("当前目录下不存在 package.json 文件");
388
- }
389
- const info = JSON.parse(readFileSync("./package.json", "utf-8"));
390
- info.scripts ?? (info.scripts = {});
391
- info.scripts.build = "node build.js";
392
- writeFileSync("./package.json", JSON.stringify(info, null, 4), "utf-8");
393
- const config = readFileSync("./tsconfig.json", "utf-8");
394
- const target = config.match(/"target":[ ]*?"(.+?)"/i)[1].toUpperCase();
395
- writeFileSync("./build.js", getBuildJS({ target, css }));
396
- console.log("更新打包命令成功");
397
- });
398
45
  program.parse();
46
+ const prettier = `module.exports = {
47
+ plugins: ["prettier-plugin-tailwindcss"],
48
+ semi: false,
49
+ tabWidth: 4,
50
+ arrowParens: "avoid",
51
+ printWidth: 800,
52
+ trailingComma: "none"
53
+ }`;
54
+ program.command("prettier").action(() => {
55
+ writeFileSync("./prettier.config.js", prettier);
56
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zixulu",
3
- "version": "0.0.3",
3
+ "version": "1.0.0",
4
4
  "main": "index.js",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/index.ts CHANGED
@@ -2,303 +2,7 @@
2
2
 
3
3
  import { Command } from "commander"
4
4
  import pkg from "../package.json"
5
- import { createPromptModule } from "inquirer"
6
- import { mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "fs"
7
- import { execSync } from "child_process"
8
-
9
- const prompt = createPromptModule()
10
-
11
- const packageNameReg = /^[a-z0-9]{1}[-_a-z0-9]{0,213}$/i
12
-
13
- type JavaScriptTarget = "ES2015" | "ES2016" | "ES2017" | "ES2018" | "ES2019" | "ES2020" | "ES2021" | "ES2022" | "ES2023" | "ESNext"
14
-
15
- interface ProjectAnswer {
16
- name: string
17
- target: JavaScriptTarget
18
- react: boolean
19
- css: boolean
20
- esm: boolean
21
- cjs: boolean
22
- install: "No" | "Yarn" | "Pnpm" | "Npm"
23
- }
24
-
25
- const JavaScriptTargets: JavaScriptTarget[] = ["ES2015", "ES2016", "ES2017", "ES2018", "ES2019", "ES2020", "ES2021", "ES2022", "ES2023", "ESNext"]
26
-
27
- async function getPackageLatestVersion(name: string) {
28
- const response = await fetch(`https://registry.npmjs.org/${name}`)
29
- const data = await response.json()
30
- return data["dist-tags"].latest
31
- }
32
-
33
- function getBuildJS(answer: Pick<ProjectAnswer, "target" | "css">) {
34
- const { target, css } = answer
35
- if (css) {
36
- return `import { execSync } from "child_process"
37
- import { copyFileSync, mkdirSync, readdirSync, rmSync, statSync } from "fs"
38
- import { join } from "path"
39
-
40
- try {
41
- rmSync("./dist", { recursive: true })
42
- } catch (error) {}
43
-
44
- execSync("npx tsc --sourceMap -module ${target} -outDir dist/esm && npx tsc --sourceMap -module CommonJS -outDir dist/cjs && npx tsc --declaration --emitDeclarationOnly -outDir dist")
45
-
46
- const src = "./src"
47
- const distEsm = "./dist/esm"
48
- const distCjs = "./dist/cjs"
49
-
50
- function bundleCSS(...paths) {
51
- const dir = readdirSync(join(src, ...paths))
52
- dir.forEach(name => {
53
- const status = statSync(join(src, ...paths, name))
54
- if (status.isFile() && name.endsWith(".css")) {
55
- for (let i = 0; i < paths.length; i++) {
56
- const d0 = readdirSync(join(distEsm, ...paths.slice(0, i)))
57
- if (!d0.includes(paths[i]) || !statSync(join(distEsm, ...paths.slice(0, i + 1))).isDirectory()) {
58
- mkdirSync(join(distEsm, ...paths.slice(0, i + 1)))
59
- }
60
- const d1 = readdirSync(join(distCjs, ...paths.slice(0, i)))
61
- if (!d1.includes(paths[i]) || !statSync(join(distCjs, ...paths.slice(0, i + 1))).isDirectory()) {
62
- mkdirSync(join(distCjs, ...paths.slice(0, i + 1)))
63
- }
64
- }
65
- copyFileSync(join(src, ...paths, name), join(distEsm, ...paths, name))
66
- copyFileSync(join(src, ...paths, name), join(distCjs, ...paths, name))
67
- return
68
- }
69
- if (status.isDirectory()) {
70
- bundleCSS(...paths, name)
71
- }
72
- })
73
- }
74
-
75
- bundleCSS()
76
- `
77
- }
78
- return `import { execSync } from "child_process"
79
- import { rmSync } from "fs"
80
-
81
- try {
82
- rmSync("./dist", { recursive: true })
83
- } catch (error) {}
84
-
85
- execSync("npx tsc --sourceMap -module ${target} -outDir dist/esm && npx tsc --sourceMap -module CommonJS -outDir dist/cjs && npx tsc --declaration --emitDeclarationOnly -outDir dist")
86
- `
87
- }
88
-
89
- async function getPackageJson(answer: ProjectAnswer) {
90
- const { name, react, esm, cjs } = answer
91
- const info: any = {
92
- name,
93
- version: "0.0.1",
94
- main: "dist/cjs/index.js",
95
- module: "dist/esm/index.js",
96
- types: "dist/index.d.ts",
97
- license: "MIT",
98
- type: "module",
99
- exports: {
100
- ".": {}
101
- },
102
- scripts: {
103
- build: "node ./build.js"
104
- },
105
- devDependencies: {}
106
- }
107
- if (esm) {
108
- info.exports["."]["import"] = {
109
- types: "./dist/index.d.ts",
110
- default: "./dist/esm/index.js"
111
- }
112
- }
113
- if (cjs) {
114
- info.exports["."]["require"] = {
115
- types: "./dist/index.d.ts",
116
- default: "./dist/cjs/index.js"
117
- }
118
- }
119
- if (react) {
120
- info.devDependencies["@types/react"] = `^${await getPackageLatestVersion("@types/react")}`
121
- info.devDependencies["@types/react-dom"] = `^${await getPackageLatestVersion("@types/react-dom")}`
122
- }
123
- info.devDependencies.typescript = `^${await getPackageLatestVersion("typescript")}`
124
- return JSON.stringify(info, null, 4)
125
- }
126
-
127
- function getTSConfig(answer: ProjectAnswer) {
128
- const { react, target } = answer
129
- return `{
130
- "compilerOptions": {
131
- /* Visit https://aka.ms/tsconfig to read more about this file */
132
- /* Projects */
133
- // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
134
- // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
135
- // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
136
- // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
137
- // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
138
- // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
139
- /* Language and Environment */
140
- "target": "${target}", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
141
- // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
142
- ${react ? "" : "// "}"jsx": "react",${react ? " " : ""} /* Specify what JSX code is generated. */
143
- // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
144
- // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
145
- // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
146
- // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
147
- // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
148
- // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
149
- // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
150
- // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
151
- // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
152
- /* Modules */
153
- // "module": "commonjs", /* Specify what module code is generated. */
154
- "rootDir": "./src", /* Specify the root folder within your source files. */
155
- "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
156
- // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
157
- // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
158
- // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
159
- // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
160
- // "types": [], /* Specify type package names to be included without being referenced in a source file. */
161
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
162
- // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
163
- // "resolveJsonModule": true, /* Enable importing .json files. */
164
- // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
165
- /* JavaScript Support */
166
- // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
167
- // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
168
- // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
169
- /* Emit */
170
- // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
171
- // "declarationMap": true, /* Create sourcemaps for d.ts files. */
172
- // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
173
- "sourceMap": true, /* Create source map files for emitted JavaScript files. */
174
- // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
175
- // "outDir": "./dist", /* Specify an output folder for all emitted files. */
176
- // "removeComments": true, /* Disable emitting comments. */
177
- // "noEmit": true, /* Disable emitting files from a compilation. */
178
- // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
179
- // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
180
- // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
181
- // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
182
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
183
- // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
184
- // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
185
- // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
186
- // "newLine": "crlf", /* Set the newline character for emitting files. */
187
- // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
188
- // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
189
- // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
190
- // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
191
- // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
192
- // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
193
- /* Interop Constraints */
194
- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
195
- // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
196
- "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
197
- // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
198
- "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
199
- /* Type Checking */
200
- "strict": true, /* Enable all strict type-checking options. */
201
- // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
202
- // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
203
- // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
204
- // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
205
- // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
206
- // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
207
- // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
208
- // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
209
- // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
210
- // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
211
- // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
212
- // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
213
- // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
214
- // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
215
- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
216
- // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
217
- // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
218
- // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
219
- /* Completeness */
220
- // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
221
- "skipLibCheck": true /* Skip type checking all .d.ts files. */
222
- }
223
- }`
224
- }
225
-
226
- function validateName(name: string) {
227
- name = name.trim()
228
- if (!packageNameReg.test(name)) {
229
- throw new Error("项目名称必须由数字、字母、下划线和中划线构成,且不能以下划线和中划线开头")
230
- }
231
- const dir = readdirSync("./")
232
- if (dir.includes(name) && statSync(`./${name}`).isDirectory() && readdirSync(`./${name}`).length > 0) {
233
- throw new Error("当前目录下存在同名文件夹,且文件夹非空")
234
- }
235
- }
236
-
237
- function validateTarget(target: string) {
238
- target = target.trim().toUpperCase()
239
- if (!JavaScriptTargets.includes(target as JavaScriptTarget)) {
240
- throw new Error("请输入有效的 JavaScript 版本")
241
- }
242
- }
243
-
244
- function getProjectAnswer<T extends keyof ProjectAnswer>(...exclude: T[]): Promise<Omit<ProjectAnswer, T>> {
245
- return prompt<Omit<ProjectAnswer, T>>(
246
- [
247
- {
248
- type: "input",
249
- name: "name",
250
- message: "请输入项目名称:",
251
- default: "my-project",
252
- validate: (input: string) => {
253
- try {
254
- validateName(input)
255
- return true
256
- } catch (error) {
257
- return String(error)
258
- }
259
- }
260
- },
261
- {
262
- type: "list",
263
- name: "target",
264
- message: "JavaScript 版本:",
265
- choices: JavaScriptTargets,
266
- default: "ES2020"
267
- },
268
- {
269
- type: "confirm",
270
- name: "react",
271
- message: "是否为 react 项目:",
272
- default: false
273
- },
274
- {
275
- type: "confirm",
276
- name: "css",
277
- message: "是否打包 CSS:",
278
- default: false
279
- },
280
- {
281
- type: "confirm",
282
- name: "esm",
283
- message: "是否打包 ES Module:",
284
- default: true
285
- },
286
- {
287
- type: "confirm",
288
- name: "cjs",
289
- message: "是否打包 Common JS:",
290
- default: true
291
- },
292
- {
293
- type: "list",
294
- name: "install",
295
- message: "现在就安装依赖:",
296
- choices: ["Yarn", "Pnpm", "Npm", "No"],
297
- default: "Yarn"
298
- }
299
- ].filter(it => exclude.every(i => i !== it.name))
300
- )
301
- }
5
+ import { writeFileSync } from "fs"
302
6
 
303
7
  const program = new Command()
304
8
 
@@ -308,86 +12,17 @@ program.option("-v, --version").action(() => {
308
12
  console.log(pkg.version)
309
13
  })
310
14
 
311
- program
312
- .command("create")
313
- .description("初始化 npm 项目")
314
- .option("-n --name <name>", "指定项目名称")
315
- .option("-r --react", "指定为 react 项目")
316
- .option("-c --css", "打包 CSS")
317
- .option("-t --target <target>", "指定 JavaScript 版本")
318
- .option("--no-esm", "不打包 ES Module")
319
- .option("--no-cjs", "不打包 Common JS")
320
- .action(async (options: Partial<ProjectAnswer>) => {
321
- const initAnswer: Partial<ProjectAnswer> = {}
322
- const exclude: (keyof ProjectAnswer)[] = []
323
- if ("name" in options) {
324
- validateName(options.name!)
325
- exclude.push("name")
326
- initAnswer.name = options.name!.trim()
327
- }
328
- if ("react" in options) {
329
- initAnswer.react = true
330
- exclude.push("react")
331
- }
332
- if ("css" in options) {
333
- initAnswer.css = true
334
- exclude.push("css")
335
- }
336
- if ("target" in options) {
337
- validateTarget(options.target!)
338
- exclude.push("target")
339
- initAnswer.target = options.target!.trim().toUpperCase() as JavaScriptTarget
340
- }
341
- if (options.esm === false) {
342
- exclude.push("esm")
343
- initAnswer.esm = false
344
- }
345
- if (options.cjs === false) {
346
- exclude.push("cjs")
347
- initAnswer.cjs = false
348
- }
349
- if (options.esm === false && options.cjs === false) {
350
- throw new Error("必须选择 ES Module 和 Common JS 至少一种")
351
- }
352
- const answer = { ...initAnswer, ...(await getProjectAnswer(...exclude)) } as ProjectAnswer
353
- const { name, react, install, esm, cjs } = answer
354
- if (esm === false && cjs === false) {
355
- throw new Error("必须选择 ES Module 和 Common JS 至少一种")
356
- }
357
- const dir = readdirSync("./")
358
- if (!dir.includes(name)) {
359
- mkdirSync(`./${name}`)
360
- }
361
- mkdirSync(`./${name}/src`)
362
- writeFileSync(`./${name}/src/index.${react ? "tsx" : "ts"}`, 'export default "Hello, world!"')
363
- writeFileSync(`./${name}/build.js`, getBuildJS(answer))
364
- writeFileSync(`./${name}/package.json`, await getPackageJson(answer))
365
- writeFileSync(`./${name}/tsconfig.json`, getTSConfig(answer))
366
- writeFileSync(`./${name}/.gitignore`, "node_modules")
367
- if (install !== "No") {
368
- execSync(`${install.toLowerCase()} install`, { cwd: `./${name}` })
369
- }
370
- console.log("创建项目成功")
371
- })
15
+ program.parse()
372
16
 
373
- program
374
- .command("build")
375
- .description("更新打包命令")
376
- .option("--no-css", "不打包 CSS")
377
- .action(options => {
378
- const { css } = options
379
- const dir = readdirSync("./")
380
- if (!dir.includes("package.json") || !statSync("./package.json").isFile()) {
381
- throw new Error("当前目录下不存在 package.json 文件")
382
- }
383
- const info = JSON.parse(readFileSync("./package.json", "utf-8"))
384
- info.scripts ??= {}
385
- info.scripts.build = "node build.js"
386
- writeFileSync("./package.json", JSON.stringify(info, null, 4), "utf-8")
387
- const config = readFileSync("./tsconfig.json", "utf-8")
388
- const target = config.match(/"target":[ ]*?"(.+?)"/i)![1].toUpperCase() as JavaScriptTarget
389
- writeFileSync("./build.js", getBuildJS({ target, css }))
390
- console.log("更新打包命令成功")
391
- })
17
+ const prettier = `module.exports = {
18
+ plugins: ["prettier-plugin-tailwindcss"],
19
+ semi: false,
20
+ tabWidth: 4,
21
+ arrowParens: "avoid",
22
+ printWidth: 800,
23
+ trailingComma: "none"
24
+ }`
392
25
 
393
- program.parse()
26
+ program.command("prettier").action(() => {
27
+ writeFileSync("./prettier.config.js", prettier)
28
+ })
package/typing.d.ts DELETED
@@ -1,4 +0,0 @@
1
- // declare module "*.json" {
2
- // var pkg: any
3
- // export default pkg
4
- // }