repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
create-neat
github_2023
typescript
294
xun082
uaenaTzx
@@ -1,27 +1,22 @@ -const globalProtocol = { +export const globalProtocol = { ENTRY_FILE: "ENTRY_FILE", // 入口文件配置,如:入口文件引入全局 less、scss + UPDATE_EXPORT_CONTENT_PROTOCOL: "UPDATE_EXPORT_CONTENT_PROTOCOL",
没有 get 到 UPDATE 的语义,INSERT_EXPORT 感觉合适一些
create-neat
github_2023
typescript
294
xun082
uaenaTzx
@@ -1,27 +1,22 @@ -const globalProtocol = { +export const globalProtocol = { ENTRY_FILE: "ENTRY_FILE", // 入口文件配置,如:入口文件引入全局 less、scss + UPDATE_EXPORT_CONTENT_PROTOCOL: "UPDATE_EXPORT_CONTENT_PROTOCOL", }; // 插件对框架的协议 -const pluginToTemplateProtocol = { +export const pluginToTemplateProtocol = { ...globalProtocol, PROCESS_STYLE_PLUGIN: "PROCESS_STYLE_PLUGIN", INSERT_IMPORT: "INSERT_IMPORT", }; // 插件对构建工具的协议 -const pluginToBuildToolProtocol = { +export const pluginToBuildToolProtocol = { ...globalProtocol, }; // 框架对构建工具的协议 -const templateToBuildToolProtocol = { +export const templateToBuildToolProtocol = {
统一导出在性能上会更好
create-neat
github_2023
typescript
294
xun082
uaenaTzx
@@ -11,7 +13,7 @@ import { Protocol } from "../../types/protocol"; class ProtocolGeneratorAPI { protected protocols: Record<string, object>; // todo 类型考虑优化 protected props: ProtocolProps; - protected protocol: Protocol; + protected protocol: string;
为啥不用 Protocol 了
create-neat
github_2023
typescript
294
xun082
uaenaTzx
@@ -52,3 +52,13 @@ export const createCallExpression = ( */ export const createObjectProperty = (name: string, value: Parameters<typeof objectProperty>[1]) => objectProperty(identifier(name), value); + +/** + * 封装遍历ast中ExportDefaultDeclaration的通用函数
ExportDefaultDeclaration的通用函数,需要结合上下文才能看懂是什么意思 可以尝试给一个更清晰的说明
create-neat
github_2023
others
292
xun082
uaenaTzx
@@ -1,8 +1,61 @@ +const path = require('path'); +const protocol = require("../../../core/src/configs/protocol.ts"); +const pluginToTemplateProtocol = protocol.pluginToTemplateProtocol;
require 放最前面,这个穿插些有点乱
create-neat
github_2023
typescript
292
xun082
uaenaTzx
@@ -0,0 +1,106 @@ +// todo 因为文件中的函数或方法被index.cjs调用,导致无法用ts和esm导出写法 + +// 定义 LocationCode 枚举,用于指定插件内容插入的位置 +/** + * 插入位置 + * @enum + * @property {number} BeforeMatchStructure - 在匹配结构之前 + * @property {number} InMatchStructure - 在匹配结构中 + * @property {number} AfterMatchStructureImport - 在匹配结构导入之后 + * @property {number} AfterMatchStructureUse - 在匹配结构使用之后 + * @property {number} WrapMatchStructure - 包裹匹配结构 + */ +const LocationCode = {
那应该定义成 enum 更好吧
create-neat
github_2023
typescript
292
xun082
uaenaTzx
@@ -0,0 +1,106 @@ +// todo 因为文件中的函数或方法被index.cjs调用,导致无法用ts和esm导出写法 + +// 定义 LocationCode 枚举,用于指定插件内容插入的位置 +/** + * 插入位置 + * @enum + * @property {number} BeforeMatchStructure - 在匹配结构之前 + * @property {number} InMatchStructure - 在匹配结构中 + * @property {number} AfterMatchStructureImport - 在匹配结构导入之后 + * @property {number} AfterMatchStructureUse - 在匹配结构使用之后 + * @property {number} WrapMatchStructure - 包裹匹配结构 + */ +const LocationCode = { + BeforeMatchStructure: 0, + InMatchStructure: 1, + AfterMatchStructureImport: 2, + AfterMatchStructureUse: 3, + WrapMatchStructure: 4, +}; + +const RegExpEnum = { + reactRouterRegexpJSX: "reactRouterRegexpJSX", + fileImport: "fileImport", + createAppRegex: "createAppRegex", + exportDefaultRexg: "exportDefaultRexg", +}; + +const RegExpMap = { + [RegExpEnum.reactRouterRegexpJSX]: /return\s*\(([\s\S]*?)\);/s,
注释尽可能加上去
create-neat
github_2023
typescript
292
xun082
uaenaTzx
@@ -0,0 +1,106 @@ +// todo 因为文件中的函数或方法被index.cjs调用,导致无法用ts和esm导出写法 + +// 定义 LocationCode 枚举,用于指定插件内容插入的位置 +/** + * 插入位置 + * @enum + * @property {number} BeforeMatchStructure - 在匹配结构之前 + * @property {number} InMatchStructure - 在匹配结构中 + * @property {number} AfterMatchStructureImport - 在匹配结构导入之后 + * @property {number} AfterMatchStructureUse - 在匹配结构使用之后 + * @property {number} WrapMatchStructure - 包裹匹配结构 + */ +const LocationCode = { + BeforeMatchStructure: 0, + InMatchStructure: 1, + AfterMatchStructureImport: 2, + AfterMatchStructureUse: 3, + WrapMatchStructure: 4, +}; + +const RegExpEnum = { + reactRouterRegexpJSX: "reactRouterRegexpJSX", + fileImport: "fileImport", + createAppRegex: "createAppRegex", + exportDefaultRexg: "exportDefaultRexg", +}; + +const RegExpMap = { + [RegExpEnum.reactRouterRegexpJSX]: /return\s*\(([\s\S]*?)\);/s, + [RegExpEnum.fileImport]: /^import.*$/gm, + [RegExpEnum.createAppRegex]: /const\s+app\s*=\s*createApp\s*\(\s*App\s*\)/, + [RegExpEnum.exportDefaultRexg]: /export\s+default\s+(\w+);/, +}; + +function insertBefore(content, index, insertion) { + return content.slice(0, index) + insertion + content.slice(index); +} + +function insertAfter(content, index, insertion) { + return content.slice(0, index) + insertion + content.slice(index); +} + +function insertAfterLastImport(content, insertion) { + const importRegex = /^import\s+.*$/gm; + const imports = content.match(importRegex); + if (imports && imports.length > 0) { + const lastImport = imports[imports.length - 1]; + const lastImportIndex = content.lastIndexOf(lastImport); + const endOfLastImportIndex = lastImportIndex + lastImport.length; + return ( + content.substring(0, endOfLastImportIndex) + + insertion + + content.substring(endOfLastImportIndex) + ); + } + return insertion + "\n" + content; +} + +function wrapContent(content, match, wrapper, structure) { + const matchedContent = match[1] || match[0]; + const wrappedContent = wrapper.replace("%*#$", matchedContent); + return ( + content.slice(0, match.index) + + structure.replace("%*#$", wrappedContent) + + content.slice(match.index + match[0].length) + ); +} + +function applyPluginTransformation(content, plugin, index) { + const match = content.match(plugin.regexps[index]); + if (!match) return content; + + let result = content; + + switch (plugin.locations[index]) { + case LocationCode.BeforeMatchStructure: + result = insertBefore(content, match.index, plugin.contents[index]); + break; + case LocationCode.AfterMatchStructureImport: + result = insertAfterLastImport(content, plugin.contents[index]); + break; + case LocationCode.AfterMatchStructureUse: + result = insertAfter(content, match.index + match[0].length, plugin.contents[index]); + break; + case LocationCode.WrapMatchStructure: + if (plugin.wrapStructures && plugin.wrapStructures[index]) { + result = wrapContent(content, match, plugin.contents[index], plugin.wrapStructures[index]); + } + break; + default: + break; + } + + return result; +} + +module.exports = {
这块其实是和 AST 息息相关的,我觉得得和 AST 同学沟通一下,整理在一块
create-neat
github_2023
others
292
xun082
uaenaTzx
@@ -1,8 +1,61 @@ +const path = require('path'); +const protocol = require("../../../core/src/configs/protocol.ts"); +const pluginToTemplateProtocol = protocol.pluginToTemplateProtocol; +const { applyPluginTransformation, LocationCode, RegExpMap } = require('../../../core/src/utils/transformFileData.ts') + +const reactMobx = { + plugin: "reactMobx", + paths: ["App.jsx", "App.jsx", "App.jsx"], + contents: [ + "\nimport { observer } from 'mobx-react-lite';", + "\nimport store from './store';", + "observer(%*#$)", + ], + regexps: [RegExpMap.fileImport, RegExpMap.fileImport, RegExpMap.exportDefaultRexg], + locations: [ + LocationCode.AfterMatchStructureImport, + LocationCode.AfterMatchStructureImport, + LocationCode.WrapMatchStructure, + ], + wrapStructures: ["", "", "export default %*#$;"], +}; + +function processReactFiles(fileData) {
mobx 如果评估下来只可能对 react 造成侵入的话,是不是 ejs 更优? 可以看看是否存在对构建工具的影响
create-neat
github_2023
typescript
292
xun082
uaenaTzx
@@ -215,6 +215,25 @@ class PluginToTemplateAPI extends ProtocolGeneratorAPI { console.log(error); } } + + /** + * 框架类插件协议 + * @param params + */ + PROCESS_TEMPLATE_PLUGIN(params) { + const content = params.params.content; + const plugins = this.props.preset.plugins; + const fileData: FileData = this.props.files.getFileData(); + try { + for (const plugin in plugins) {
这块还不能和 scss 的保持一致,因为随着插件的增多,这里的判断逻辑会越来越复杂,我想的是既然协议是在固定的插件里面触发的,那执行什么应该可以从入参去判断 比如:PROCESS_TEMPLATE_PLUGIN 被 aaa 中调用了,处理的时候,直接执行回调就行了。 processReactFiles 就统一命名为 callback 这类的
create-neat
github_2023
typescript
292
xun082
uaenaTzx
@@ -0,0 +1,157 @@ +// todo 因为文件中的函数或方法被index.cjs调用,导致无法用ts和esm导出写法 + +// 定义 LocationCode 枚举,用于指定插件内容插入的位置 +/** + * 插入位置 + * @enum {number} + * @property {number} BeforeMatchStructure - 在匹配结构之前 + * @property {number} InMatchStructure - 在匹配结构中 + * @property {number} AfterMatchStructureImport - 在匹配结构导入之后 + * @property {number} AfterMatchStructureUse - 在匹配结构使用之后 + * @property {number} WrapMatchStructure - 包裹匹配结构 + */ +const LocationCode = { + BeforeMatchStructure: 0, + InMatchStructure: 1, + AfterMatchStructureImport: 2, + AfterMatchStructureUse: 3, + WrapMatchStructure: 4, +}; + +// 定义正则表达式枚举,用于标识不同的正则表达式类型 +/** + * 正则表达式枚举 + * @enum {string} + */ +const RegExpEnum = { + reactRouterRegexpJSX: "reactRouterRegexpJSX", + fileImport: "fileImport", + createAppRegex: "createAppRegex", + exportDefaultRexg: "exportDefaultRexg", +}; + +// 定义正则表达式映射,将正则表达式枚举映射到实际的正则表达式 +/** + * 正则表达式映射 + * @type {Object.<string, RegExp>} + */ +const RegExpMap = { + [RegExpEnum.reactRouterRegexpJSX]: /return\s*\(([\s\S]*?)\);/s, + [RegExpEnum.fileImport]: /^import.*$/gm, + [RegExpEnum.createAppRegex]: /const\s+app\s*=\s*createApp\s*\(\s*App\s*\)/,
这种映射比较特化,如果每个插件都有很多特化会导致 regexpmap 难以维护,遇到这种情况还是尽量想着抽象一些
create-neat
github_2023
others
292
xun082
uaenaTzx
@@ -1,8 +1,62 @@ +const path = require('path'); +const protocol = require("../../../core/src/configs/protocol.ts"); +const { applyPluginTransformation, LocationCode, RegExpMap } = require('../../../core/src/utils/transformFileData.ts') + +const pluginToTemplateProtocol = protocol.pluginToTemplateProtocol; + +const reactMobx = { + plugin: "reactMobx", + paths: ["App.jsx", "App.jsx", "App.jsx"], + contents: [ + "\nimport { observer } from 'mobx-react-lite';", + "\nimport store from './store';", + "observer(%*#$)", + ], + regexps: [RegExpMap.fileImport, RegExpMap.fileImport, RegExpMap.exportDefaultRexg], + locations: [ + LocationCode.AfterMatchStructureImport, + LocationCode.AfterMatchStructureImport, + LocationCode.WrapMatchStructure, + ], + wrapStructures: ["", "", "export default %*#$;"], +}; + +function processReactFiles(fileData) {
这个方法大部分都围绕在从 filetree 中找到目标路径,那我觉得可以把找路径的过程抽象成一个方法,这样能很大程度被复用
create-neat
github_2023
others
292
xun082
uaenaTzx
@@ -1,8 +1,62 @@ +const path = require('path'); +const protocol = require("../../../core/src/configs/protocol.ts"); +const { applyPluginTransformation, LocationCode, RegExpMap } = require('../../../core/src/utils/transformFileData.ts') + +const pluginToTemplateProtocol = protocol.pluginToTemplateProtocol; + +const reactMobx = { + plugin: "reactMobx", + paths: ["App.jsx", "App.jsx", "App.jsx"], + contents: [ + "\nimport { observer } from 'mobx-react-lite';", + "\nimport store from './store';", + "observer(%*#$)", + ], + regexps: [RegExpMap.fileImport, RegExpMap.fileImport, RegExpMap.exportDefaultRexg], + locations: [ + LocationCode.AfterMatchStructureImport, + LocationCode.AfterMatchStructureImport, + LocationCode.WrapMatchStructure, + ], + wrapStructures: ["", "", "export default %*#$;"], +}; + +function processReactFiles(fileData) { + for (let i = 0; i < fileData.children.length; i++) { + // 先寻找 src 文件夹 + const dirName = path.basename(fileData.children[i].path); + if (dirName === "src") { + const srcFileData = fileData.children[i]; + for (let j = 0; j < srcFileData.children.length; j++) { + const fileName = path.basename(srcFileData.children[j].path); + for (let k = 0; k < reactMobx.paths.length; k++) { + if (fileName === reactMobx.paths[k]) { + const fileContent = srcFileData.children[j].describe + fileContent.fileContent = applyPluginTransformation(fileContent.fileContent, reactMobx, k) + } + } + } + } + } + return fileData +} + module.exports = (generatorAPI) => { generatorAPI.extendPackage({ devDependencies: { mobx: "^6.6.4", "mobx-react-lite": "^3.2.2", }, }); + + generatorAPI.protocolGenerate({ + [pluginToTemplateProtocol.PROCESS_MOBX_PLUGIN]: {
协议抽象,提取 mobx 对 react 的侵入特征
create-neat
github_2023
others
293
xun082
uaenaTzx
@@ -1,7 +1,81 @@ +const path = require("path"); + +const protocol = require("../../../core/src/configs/protocol.ts"); +const pluginToTemplateProtocol = protocol.pluginToTemplateProtocol; + +/** + * 处理 Pinia 文件函数 + */ +function processPiniaFiles(plugin, fileData) { + const importRegex = /^import.*$/gm; + const mountRegex = /app\.mount\(.*\)/; + + for (let i = 0; i < fileData.children.length; i++) { + const dirName = path.basename(fileData.children[i].path); + if (dirName === "src") { + const mainFile = fileData.children[i].children.find( + (child) => + path.basename(child.path) === "main.js" || path.basename(child.path) === "main.ts", + ); + + if (mainFile && mainFile.describe) { + let content = mainFile.describe.fileContent; + + // 找到最后一个 import 语句 + const imports = content.match(importRegex); + if (imports) { + const lastImport = imports[imports.length - 1]; + const lastImportIndex = content.lastIndexOf(lastImport); + const endOfLastImportIndex = lastImportIndex + lastImport.length; + + // 在最后一个 import 后添加 pinia 相关导入 + const importContent = + "\n\nimport { createPinia } from 'pinia'\nconst pinia = createPinia()\n"; + content = + content.substring(0, endOfLastImportIndex) + + importContent + + content.substring(endOfLastImportIndex); + } + + // 在 mount 之前添加 app.use(pinia) + const mountMatch = content.match(mountRegex); + if (mountMatch) { + const useContent = "app.use(pinia)\n\n"; + const mountIndex = mountMatch.index; + content = content.substring(0, mountIndex) + useContent + content.substring(mountIndex); + } + + // 处理多余的空行 + content = content.replace( + /\n\n\nconst app = createApp\(App\)/, + "\nconst app = createApp(App)", + ); + content = content.replace( + /const app = createApp\(App\)\n\n\n/, + "const app = createApp(App)\n\n", + ); + + mainFile.describe.fileContent = content; + } + } + } + return fileData; +} + module.exports = (generatorAPI) => { generatorAPI.extendPackage({ dependencies: { pinia: "^2.2.2", }, }); + + generatorAPI.protocolGenerate({ + [pluginToTemplateProtocol.PROCESS_PINIA_PLUGIN]: {
协议这样子太特化了,我们预期的是协议复用
create-neat
github_2023
others
293
xun082
uaenaTzx
@@ -1,7 +1,28 @@ +const protocol = require("../../../core/src/configs/protocol.ts");
可以配一下 alias
create-neat
github_2023
typescript
293
xun082
uaenaTzx
@@ -66,7 +66,7 @@ class FileTree { describe: { fileName: path.basename(rootDirectory) }, }; // 初始化 PluginToTemplateAPI,传入所需协议 - this.pluginToTemplateAPI = new PluginToTemplateAPI({}, {}); + this.pluginToTemplateAPI = new PluginToTemplateAPI({}, {}, {});
这样传不如在 PluginToTemplateAPI 设置默认值吧
create-neat
github_2023
typescript
293
xun082
uaenaTzx
@@ -215,6 +44,93 @@ class PluginToTemplateAPI extends ProtocolGeneratorAPI { console.log(error); } } + + /** + * Import语句插入协议 + * @param params 包含导入信息的参数对象 + */ + INSERT_IMPORT(params) {
不需要做这个判断,协议被调用就说明这个插件被引入了(所以,目标插件的协议是一定能成功地) 所以判断可以去掉,同样的,传参可以少一层 额外的,可以评估一下是否还需要 content 这一层
create-neat
github_2023
typescript
293
xun082
uaenaTzx
@@ -215,6 +44,93 @@ class PluginToTemplateAPI extends ProtocolGeneratorAPI { console.log(error); } } + + /** + * Import语句插入协议 + * @param params 包含导入信息的参数对象 + */ + INSERT_IMPORT(params) { + const content = params.params.content; + const plugins = this.props.preset.plugins; + const fileData: FileData = this.props.files.getFileData(); + + try { + for (const plugin in plugins) { + if (content[plugin]?.imports?.length) { + const imports = content[plugin].imports; + for (const importConfig of imports) { + this.insertImportToFile(fileData, { + dir: importConfig.dir, + imports: [ + { + name: importConfig.name, + from: importConfig.from, + }, + ], + }); + } + } + } + } catch (error) { + console.log(error); + } + } + + private insertImportToFile(
这个应该是 IMPORT 协议独有的,直接写协议处理器里面就好了
create-neat
github_2023
typescript
293
xun082
uaenaTzx
@@ -215,6 +44,93 @@ class PluginToTemplateAPI extends ProtocolGeneratorAPI { console.log(error); } } + + /** + * Import语句插入协议 + * @param params 包含导入信息的参数对象 + */ + INSERT_IMPORT(params) { + const content = params.params.content; + const plugins = this.props.preset.plugins; + const fileData: FileData = this.props.files.getFileData(); + + try { + for (const plugin in plugins) { + if (content[plugin]?.imports?.length) { + const imports = content[plugin].imports; + for (const importConfig of imports) { + this.insertImportToFile(fileData, { + dir: importConfig.dir, + imports: [ + { + name: importConfig.name, + from: importConfig.from, + }, + ], + }); + } + } + } + } catch (error) { + console.log(error); + } + } + + private insertImportToFile( + fileData: FileData, + config: { + dir: string; + imports: Array<{ name: string; from: string }>; + }, + ) { + const dirParts = config.dir.split("/"); + const rootDir = dirParts[0]; + const targetFileName = dirParts[dirParts.length - 1]; + for (let i = 0; i < fileData.children.length; i++) {
遍历找文件的方法我记得 @四十 抽出来过,但你们代码没对齐 这个可以提取出来的,你们可以对一下
create-neat
github_2023
typescript
293
xun082
uaenaTzx
@@ -10,16 +10,19 @@ import { ProtocolProps } from "../BaseAPI"; class ProtocolGeneratorAPI { protected protocols: Record<string, object>; // todo 类型考虑优化 protected props: ProtocolProps; + protected protocol: any; - constructor(protocols) { + constructor(protocols, props, protocol) { this.protocols = protocols; + this.props = props; + this.protocol = protocol; } generator() { // todo: 加入优先级调度 - for (const protocol in this.protocols) { - this[protocol](this.protocols[protocol]); - } + const protocol = this.protocol; + const protocols = this.protocols; + this[protocol](protocols[protocol]);
这样无法保证一个插件的多个协议被调用吧
create-neat
github_2023
typescript
293
xun082
uaenaTzx
@@ -215,6 +44,45 @@ class PluginToTemplateAPI extends ProtocolGeneratorAPI { console.log(error); } } + + /** + * Import语句插入协议 + * @param params 包含导入信息的参数对象 + */ + INSERT_IMPORT(params) {
协议内部的操作适当加一些注释,以及一些地方可以加可选链吧 比如 path.node.loc.end.line 就比较不清晰,得结合上下文看懂
create-neat
github_2023
typescript
293
xun082
uaenaTzx
@@ -10,9 +10,12 @@ import { ProtocolProps } from "../BaseAPI"; class ProtocolGeneratorAPI { protected protocols: Record<string, object>; // todo 类型考虑优化 protected props: ProtocolProps; + protected protocol: any;
any 不好吧
create-neat
github_2023
typescript
293
xun082
uaenaTzx
@@ -6,12 +6,16 @@ const globalProtocol = { const pluginToTemplateProtocol = { ...globalProtocol, PROCESS_STYLE_PLUGIN: "PROCESS_STYLE_PLUGIN", + PROCESS_PINIA_PLUGIN: "PROCESS_PINIA_PLUGIN",
那这些协议可以删了
create-neat
github_2023
others
291
xun082
uaenaTzx
@@ -0,0 +1,116 @@ +.container {
这个为啥要加,本身应该在模板里面去定义的,如果写了一个 less 插件,会有重复工作
create-neat
github_2023
typescript
291
xun082
uaenaTzx
@@ -27,8 +36,24 @@ class BaseAPI { // todo: jsdoc + protocols 的类型 protocolGenerate(protocols) { - const pluginToTemplate = new PluginToTemplateAPI(protocols); - pluginToTemplate.generator(); + const preset = this.generator.getPreset(); + const buildToolConfigAst = this.generator.buildToolConfigAst; + const files = this.generator.getFiles(); + let api: ProtocolAPI = undefined; + for (const protocol in protocols) { + if (protocol in pluginToTemplateProtocol) { + protocols[protocol].perset = preset; + protocols[protocol].files = files; + api = api === undefined ? new PluginToTemplateAPI(protocols) : api; + } else if (protocol in pluginToBuildToolProtocol) { + // api = new PluginToBuildToolAPI(protocols); + } else if (protocol in templateToBuildToolProtocol) { + protocols[protocol].perset = preset; + protocols[protocol].buildToolConfigAst = buildToolConfigAst; + api = api === undefined ? new TemplateToBuildToolAPI(protocols) : api; + } + } + api.generator();
那我觉得要把注释讲清楚,BaseAPI 越来越复杂了
create-neat
github_2023
typescript
291
xun082
uaenaTzx
@@ -103,6 +116,34 @@ class PluginToTemplateAPI extends ProtocolGeneratorAPI { return processedContent; } + PROCESS_SASS(params) { + const { template, plugins } = params.perset; + const fileData = params.files.fileData; + if ("sass" in plugins) {
这里判断显得不太合适,建议从 params 里面取作用的插件是什么 如果这个协议给很多个插件使用,判断就麻烦了
create-neat
github_2023
typescript
291
xun082
uaenaTzx
@@ -103,6 +116,34 @@ class PluginToTemplateAPI extends ProtocolGeneratorAPI { return processedContent; } + PROCESS_SASS(params) { + const { template, plugins } = params.perset; + const fileData = params.files.fileData; + if ("sass" in plugins) { + for (let i = 0; i < fileData.children.length; i++) { + const dirName = path.basename(fileData.children[i].path); + if (dirName === "src") { + if (template === "vue") {
这块能不能抽象(如果抽象有难度可以考虑统一模板的格式
create-neat
github_2023
typescript
291
xun082
uaenaTzx
@@ -103,6 +116,34 @@ class PluginToTemplateAPI extends ProtocolGeneratorAPI { return processedContent; } + PROCESS_SASS(params) {
能不能把协议抽象,比如抽象给 sass、less 等 甚至抽象成 xx 文件的引入
create-neat
github_2023
javascript
291
xun082
uaenaTzx
@@ -124,6 +124,16 @@ module.exports = { }, }, }, + <% if (plugin ==='sass' ) { %> + { + test: /\.s[ac]ss$/i, + use: [ + 'style-loader', + 'css-loader', + 'sass-loader', + ], + }, + <% } %>
你觉得好做不,或者把这块的诉求抛群里 目前这种协作模式我建议不要关心 xx 对 xx 协议我来做,而是 xx 插件的所有协议我来做
create-neat
github_2023
others
291
xun082
uaenaTzx
@@ -1,6 +1,6 @@ { - "name": "@laconic/plugin-scss", - "description": "scss", + "name": "@laconic/plugin-sass",
sass 和 scss 统一一下吧,有的地方还是 scss
create-neat
github_2023
typescript
291
xun082
uaenaTzx
@@ -3,11 +3,20 @@ import path from "path"; import Generator from "./Generator"; import PluginToTemplateAPI from "./protocolGenerator/PluginToTemplateAPI"; +import TemplateToBuildToolAPI from "./protocolGenerator/TemplateToBuildToolAPI"; + +const {
cjs 和 esm 语法不要混用
create-neat
github_2023
typescript
291
xun082
uaenaTzx
@@ -38,6 +42,19 @@ interface WriteConfigIntoTemplate { wrapStructures?: string[]; } +/** + * 样式插件参数 + * @interface + * @param {Preset} preset - 用户预设 + * @param {FileTree} files - 文件树,包含了基础的 src 目录 + * @param {Record<'content', string>} params - 传入的 content,适用于一些需要添加字段的特殊情况。 + */ +interface StyleParams {
协议的传参能不能在独立的一个地方定义导出,在插件里面注册协议的时候也能保证引用 (考虑给插件的 cjs 换了吧)
create-neat
github_2023
typescript
291
xun082
uaenaTzx
@@ -51,9 +68,12 @@ class PluginToTemplateAPI extends ProtocolGeneratorAPI { private fileImport: RegExp = /^import.*$/gm; // 匹配 createApp 语句 private createAppRegex: RegExp = /const\s+app\s*=\s*createApp\s*\(\s*App\s*\)/; + // 匹配 index.css 语句 + private cssRegex: RegExp = /import\s+["']\.\/index\.css["'];/;
协议多起来了的话,会很乱,这些应该在协议处理器里面维护,而不是在整个 PluginToTemplateAPI 里面
create-neat
github_2023
typescript
291
xun082
uaenaTzx
@@ -102,6 +130,23 @@ class PluginToTemplateAPI extends ProtocolGeneratorAPI { return processedContent; } + /** + * 样式类插件协议 + * @param params + */ + PROCESS_STYLE_PLUGIN(params: StyleParams) {
PROCESS_STYLE_PLUGIN 相关的全都收敛到这里去
create-neat
github_2023
typescript
291
xun082
uaenaTzx
@@ -83,7 +103,15 @@ class PluginToTemplateAPI extends ProtocolGeneratorAPI { wrapStructures: ["return (%*#$)", ""], }; - this.plugins = [reactRouter, vuePinia]; + const sass: WriteConfigIntoTemplate = {
也是的,太特化了 内部的抽象还是没想到好方法,我觉得你可以考虑把这些内容不抽象了,作为传参提取出去,在插件的协议里作为参数传递进来(甚至可以给个回调函数) 如果你觉得不可用的协议有优化空间,甚至可以去直接改
create-neat
github_2023
typescript
291
xun082
uaenaTzx
@@ -183,6 +228,31 @@ class PluginToTemplateAPI extends ProtocolGeneratorAPI { content.slice(match.index! + match[0].length) ); } + + private processSass(fileData: FileData, template: string): FileData {
还是要尽可能的抽象一些,参考前面评论的,实在不行作为回调函数提取出来
create-neat
github_2023
typescript
291
xun082
uaenaTzx
@@ -268,6 +268,7 @@ class Generator { framework: this.templateName, bundler: this.buildTool, language: "typescript" in this.plugins ? "typescript" : "javascript", + plugin: "sass" in this.preset.plugins ? "sass" : "",
为啥需要给 ejs 加个参数,而且加的太特化了吧
create-neat
github_2023
typescript
291
xun082
uaenaTzx
@@ -102,6 +123,23 @@ class PluginToTemplateAPI extends ProtocolGeneratorAPI { return processedContent; } + /** + * 样式类插件协议 + * @param params + */ + PROCESS_STYLE_PLUGIN() { + const { template, plugins } = this.props.preset; + const fileData: FileData = this.props.files.getFileData(); + try { + for (const plugin in plugins) { + if (plugins.hasOwnProperty(plugin) && plugin === "sass") {
为啥要改成 sass,统一一下吧 现在有的地方 sass,有的地方 scss
create-neat
github_2023
typescript
291
xun082
uaenaTzx
@@ -102,6 +123,23 @@ class PluginToTemplateAPI extends ProtocolGeneratorAPI { return processedContent; } + /** + * 样式类插件协议 + * @param params + */ + PROCESS_STYLE_PLUGIN() { + const { template, plugins } = this.props.preset;
这个协议里面也不需要做额外的 plugins 判断,这是协议处理器,如果被调用了,肯定是有相关的插件去调用 那具体操作哪个插件?应该从 PROCESS_STYLE_PLUGIN() 的入参去获取
create-neat
github_2023
typescript
291
xun082
uaenaTzx
@@ -183,6 +221,64 @@ class PluginToTemplateAPI extends ProtocolGeneratorAPI { content.slice(match.index! + match[0].length) ); } + + // 处理 sass 的回调函数,这里传入props 的原因是因为回调函数无法找到 API 的 this。 + private processSass(fileData: FileData, props: ProtocolProps): FileData {
虽然他被作为回调函数被传入,但他的定义应该在插件里面,不然这个文件会随着插件越来越多而越来越复杂 会很难维护
create-neat
github_2023
others
278
xun082
uaenaTzx
@@ -1,223 +1,86 @@ -## Create-Neat -### README.md -- zh_CN [简体中文](README.md) -- en [English](readme/README-EN.md) +<h1 align="center" style="font-size: 2.5em; color: #333;">Create-Neat</h1> +<hr style="border: 1px solid #ccc;"/> +<p align="center" style="font-size: 1.2em; color: #555; max-width: 800px; line-height: 1.5;"> + <strong>Create-Neat</strong> 是一款轻量级脚手架工具,专为提供 + <span style="color: #007BFF;">开箱即用</span>和 + <span style="color: #007BFF;">零配置</span>体验而设计,旨在帮助用户快速且轻松地构建项目,同时支持多样的技术栈选择。 +</p> -### 一、背景 📖 -在刚开始学习 `React` 的时候,使用的脚手架就是 `create-react-app`,虽然这个脚手架提供的零配置、开箱即用很适合新手,但是要想对其进行扩展就非常麻烦。要想对其进行扩展你必须 `eject` 或者 使用 `carco` 进行配置。 +### 一、背景 📖 -尽管 `Typescript` 已经流行了很久,但是要从零设计一个 `Typescript` 库依旧麻烦,本人也曾有过从零搭建一个 `React` 组件库的想法,但是对一堆陌生的配置望而生畏。 +当前社区中已有众多优秀的前端脚手架工具,如 create-vite、create-next-app 和 create-react-app 等。这些工具在设计上确实优秀且强大,但仍然面临两个主要问题: +- **黑盒环境**:新手在使用这些工具时,配置过程较为复杂,存在较高的学习成本和心智负担。 +- **灵活性不足**:许多脚手架工具仅专注于特定技术栈,若需要集成其他技术栈,往往需寻找额外的脚手架。 -`Create-Neat` 就是为了解决这些问题应运而生的,解决以上所有问题,开箱即用,零配置 🚀🚀🚀 +[Create-Neat](https://create-neat.github.io/docs/) 旨在解决上述问题,使开发者能够快速创建项目,无需担心复杂的配置,同时提供广泛的技术栈选择 🚀🚀🚀。 -### 二、特性 🧰 +### 二、我们的特点 🧰 -- 📦 零配置,开箱即用; -- 🚀 使用 `axios` + `npm` 的方式构建你的项目基础模板,初始化速度要比 `create-react-app` 快; -- 💯 代码风格统一,项目统一配置 `Eslint`、`Prettier`、`Husky`; -- 🥂 使用 `Rollup` 打包你的 `Typescript` 库,支持 `UMD`、`CJS`、`ESM` 输出格式,并生成全局 `.d.ts` 文件; -- 🍻 支持用户自定义 `Rollup` 配置扩展原有的配置,为项目添加特有的功能; -- 🥂 使用 `Webpack` 打包你的 `Web` 应用程序,实现多环境打包部署,代码分割优化,配合官方分析工具,实时优化代码; -- 🍻 支持用户自定义 `Webpack` 配置扩展原有的配置,为项目添加特有的功能; -- 🎯 支用户自定义 `Babel` 配置,让你的程序更健壮; -- 📕 友好的日志输出,让你快速定位问题所在以及增加开发体验; -- 在使用 `Husky` 的情况下使用 `standard-version` 自动生成 `CHANGELOG` 文件; -- 🔸 等等...... +- 📦 **零配置,开箱即用。** +- 🚀 **插件式项目生成**:根据用户需求灵活生成不同基础项目。 +- 🧠 **支持无限扩展的架构**:框架、构建工具和插件的潜力无限。 +- 💯 **丰富的使用教程和代码注释**:帮助每位社区成员快速学习前端工程化相关知识。
要不额外开一个板块,介绍我们的社区,把这两个放进去。 因为这个不能算是这个 cn 的技术特点
create-neat
github_2023
others
278
xun082
uaenaTzx
@@ -1,223 +1,86 @@ -## Create-Neat -### README.md -- zh_CN [简体中文](README.md) -- en [English](readme/README-EN.md) +<h1 align="center" style="font-size: 2.5em; color: #333;">Create-Neat</h1> +<hr style="border: 1px solid #ccc;"/> +<p align="center" style="font-size: 1.2em; color: #555; max-width: 800px; line-height: 1.5;"> + <strong>Create-Neat</strong> 是一款轻量级脚手架工具,专为提供 + <span style="color: #007BFF;">开箱即用</span>和 + <span style="color: #007BFF;">零配置</span>体验而设计,旨在帮助用户快速且轻松地构建项目,同时支持多样的技术栈选择。 +</p> -### 一、背景 📖 -在刚开始学习 `React` 的时候,使用的脚手架就是 `create-react-app`,虽然这个脚手架提供的零配置、开箱即用很适合新手,但是要想对其进行扩展就非常麻烦。要想对其进行扩展你必须 `eject` 或者 使用 `carco` 进行配置。 +### 一、背景 📖 -尽管 `Typescript` 已经流行了很久,但是要从零设计一个 `Typescript` 库依旧麻烦,本人也曾有过从零搭建一个 `React` 组件库的想法,但是对一堆陌生的配置望而生畏。 +当前社区中已有众多优秀的前端脚手架工具,如 create-vite、create-next-app 和 create-react-app 等。这些工具在设计上确实优秀且强大,但仍然面临两个主要问题: +- **黑盒环境**:新手在使用这些工具时,配置过程较为复杂,存在较高的学习成本和心智负担。 +- **灵活性不足**:许多脚手架工具仅专注于特定技术栈,若需要集成其他技术栈,往往需寻找额外的脚手架。 -`Create-Neat` 就是为了解决这些问题应运而生的,解决以上所有问题,开箱即用,零配置 🚀🚀🚀 +[Create-Neat](https://create-neat.github.io/docs/) 旨在解决上述问题,使开发者能够快速创建项目,无需担心复杂的配置,同时提供广泛的技术栈选择 🚀🚀🚀。 -### 二、特性 🧰 +### 二、我们的特点 🧰 -- 📦 零配置,开箱即用; -- 🚀 使用 `axios` + `npm` 的方式构建你的项目基础模板,初始化速度要比 `create-react-app` 快; -- 💯 代码风格统一,项目统一配置 `Eslint`、`Prettier`、`Husky`; -- 🥂 使用 `Rollup` 打包你的 `Typescript` 库,支持 `UMD`、`CJS`、`ESM` 输出格式,并生成全局 `.d.ts` 文件; -- 🍻 支持用户自定义 `Rollup` 配置扩展原有的配置,为项目添加特有的功能; -- 🥂 使用 `Webpack` 打包你的 `Web` 应用程序,实现多环境打包部署,代码分割优化,配合官方分析工具,实时优化代码; -- 🍻 支持用户自定义 `Webpack` 配置扩展原有的配置,为项目添加特有的功能; -- 🎯 支用户自定义 `Babel` 配置,让你的程序更健壮; -- 📕 友好的日志输出,让你快速定位问题所在以及增加开发体验; -- 在使用 `Husky` 的情况下使用 `standard-version` 自动生成 `CHANGELOG` 文件; -- 🔸 等等...... +- 📦 **零配置,开箱即用。** +- 🚀 **插件式项目生成**:根据用户需求灵活生成不同基础项目。 +- 🧠 **支持无限扩展的架构**:框架、构建工具和插件的潜力无限。 +- 💯 **丰富的使用教程和代码注释**:帮助每位社区成员快速学习前端工程化相关知识。 +- 👌 **完善且细致的贡献流程**:手把手指导从学习到贡献的过程。 +- ⚙️ **定期更新与维护**:定期更新工具,修复bug、完善功能、加入新的技术栈支持。 +- 🎉 **用户友好的体验**:专注于用户体验,力求让每一位用户都能享受到流畅、无阻的开发过程。 +- 🔸 **更多特性等待你的贡献!** ### 三、快速开始 🚩 +#### 安装依赖 +```shell +npm install -g create-neat ``` -npx create-neat my-app -cd my-app -npm start -``` - -如果你之前已经通过 `npm install -g create-neat` 全局安装了 `create-neat`,我们建议你使用 `npm uninstall -g create-neat` 或 `yarn global remove create-neat` 来卸载这个包,以确保 npx 总是使用最新的版本。 - -当你在终端中输入 `npx create-neat my-app` 时,控制台会有以下选项功能选择: - -![在这里插入图片描述](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b1423eca147545c698bec5b7f30f2da2~tplv-k3u1fbpfcp-zoom-1.image) - -`create-neat` 会根据你的创建不同的应用程序,这些应用程序都是开箱即用,无需配置,其中: - -- `common-lib`:一个基础的 `Typescript` 库,您可以使用该模板来编写一个类似于 `lodash` 的工具库; -- `react-ui`: 为你快速创建一个 `react` 组件库,内置 `storybook` 让你快速编写你的组件库文档,并且使用 `standard-version` 自动为你生成 `CHANGELOG` 文件; -- 剩下的四个都是为你创建不用的 `web` 应用程序,其中 `vue` 同时支持 `.vue` 和 `.tsx` 的语法。 - -如果项目创建成功,会有如下效果图所示: - -![在这里插入图片描述](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/fe46e77448d54c14aebf4557db949883~tplv-k3u1fbpfcp-zoom-1.image) - -> 更多使用方式后续会在 [掘金](https://juejin.cn/user/3782764966460398/posts) 中以文章方式呈现出来,感兴趣的小伙伴可以关注一下。 - -### 四、 创建应用程序 📕 - -要创建一个新的应用程序,您可以选择以下方法之一: - -#### NPX - -``` -npx create-neat my-app -``` - -#### NPM - -``` -npm init neat my-app -``` - -#### YARN - -``` -yarn create neat my-app -``` - -它将在当前文件夹中创建一个名为 my-app 的目录。 -在该目录中,它将根据你所选择的项目类型生成不同的初始项目结构并根据你所选择的包管理工具进行安装可传递的依赖项,例如当你选择 `react-ui` 时会为你创建一个开箱即用的组件库模板,具体目录结构如下所示: - -``` -├───📁 .husky/ -│ ├───📄 commit-msg -│ └───📄 pre-commit -├───📁 .storybook/ -│ ├───📄 main.js -│ └───📄 preview.js -├───📁 .vscode/ -│ └───📄 settings.json -├───📁 example/ -│ ├───📄 App.tsx -│ ├───📄 index.html -│ ├───📄 index.tsx -│ ├───📄 package.json -│ └───📄 tsconfig.json -├───📁 src/ -│ ├───📁 components/ -│ │ └───... -│ └───📄 index.tsx -├───📁 stories/ -│ └───📄 button.stories.tsx -├───📄 .eslintignore -├───📄 .eslintrc.json -├───📄 .gitignore -├───📄 .prettierignore -├───📄 .prettierrc.json -├───📄 babel.config.js -├───📄 commitlint.config.js -├───📄 package.json -├───📄 pnpm-lock.yaml -└───📄 tsconfig.json -``` - -无需配置或复杂的文件夹结构,只有构建应用程序所需的文件。 -安装完成后,你可以打开你的项目文件夹: - -``` -cd my-app +#### 创建项目 +```shell +create-neat <project-name> ``` -在新创建的项目中,您可以运行一些内置命令: - -#### `npm start`、`pnpm start` 或者 `yarn start` +输入命令 `create-neat my-app` 后,控制台将提供以下功能选择: -如果你使用的是 `web` 相对应的项目类型,则在开发模式下运行应用程序并自动打开 [http://localhost:3000](http://localhost:3000) 在浏览器中进行查看,否则则使用 `Rollup` 中的 `watch` 钩子在命令行终端中监听您文件的变化。 +![功能选择界面](https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/ffd53bd2e3a546b6bbc4da69161e7dae~tplv-k3u1fbpfcp-jj-mark:0:0:0:0:q75.image#?w=987&h=198&s=22353&e=png&b=1e1e1e) -#### `npm build`、`pnpm build` 或者 `yarn build` +根据需求选择对应框架,或通过 `Manually select preset` 进行自由组合。`create-neat` 将根据选择的预设创建不同的开箱即用应用程序,选项包括: -如果您使用的是 `web` 应用程序,使用该命令则会将其应用程序优化构建以获得最佳性能并将其存放与 `dist` 目录下。 +- **框架**:`react`、`vue` 或 `类库/工具库`。 +- **构建工具**:`webpack`、`vite` 等。 +- **插件**:`eslint`、`prettier`、`typescript`、`babel`、`swc` 等。 +- **其他选项**:包管理器、镜像源等。 -如果您在项目初始化的时候选择的 `common-lib` 或者 `react-ui`,那么该应用程序将会使用 `Rollup` 进行打包构建,并根据你所传入的参数构建成不同格式的文件,完整参数配置如下所示: +这些选项通过我们的设计抽象层,在生成器架构中创建最终项目。 -``` -Usage - $ rollup-script build [options] - -Options - --target 指定目标环境 默认使用 web - --name 指定在 UMD 模式构建中全局的名称 - --format 指定模式格式(cjs,esm,umd) 默认是 esm - -Examples - $ rollup-script build --target node - $ rollup-script build --name Foo - $ rollup-script build --format cjs,esm,umd - $ rollup-script build --format umd --name Foo -``` - -### Babel - -您可以将自己的 `Babel` 配置添加到项目的根目录当中, `create-neat` 会将其与自己原有的 `Babel` 转换合并并且将新的预设和插件放在列表的末尾。 +若项目创建成功,可查看如下效果图: -#### Example - -```js -// babel.config.js - -module.exports = { - plugins: ["babel-plugin-styled-components"], -}; -``` +![项目创建成功](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/fe46e77448d54c14aebf4557db949883~tplv-k3u1fbpfcp-zoom-1.image) -### webpack - -> ⚠️ Warning -> 这些修改有可能覆盖 `create-neat` 的默认行为和配置,请谨慎使用! - -如果您想扩展 `webpack` 配置已增加项目对不同功能的支持或者增加项目性能,您可以在 `webpack.config.js` 文件下对 `webpack` 配置进行扩展.并且您可以使用 `process.env.NODE_ENV` 以区分开发环境和生产环境。 - -#### Example - -```js -// webpack.config.js - -const MiniCssExtractPlugin = require("mini-css-extract-plugin"); -const isDevelopment = process.env.NODE_ENV === "development"; - -module.exports = { - plugins: [isDevelopment && MiniCssExtractPlugin()], -}; +#### 启动项目 +```shell +cd <project-name> +npm start ``` -### Rollup +至此,你可以开始项目的开发了!如欲深入了解项目启动方式、架构等细节,欢迎加入我们的社区群或查阅文档网站(建设中)。 -> ⚠️ Warning -> 这些修改有可能覆盖 `create-neat` 的默认行为和配置,请谨慎使用! +### 五、贡献者 -如果你选择的项目类型是 `common-lib` 或者 `react-ui` 并且您希望更改 `Rollup` 配置,可以在项目的根目录下创建一个名为 `rollup.config.js` 的文件,示例代码如下所示: +感谢以下贡献者的支持,诚邀更多技术大佬加入我们的行列! -```js -module.exports = { - rollup(config, options) { - return config; - }, -}; -``` - -#### Example - -```js -const postcss = require("rollup-plugin-postcss"); +<a href="https://github.com/xun082/create-neat/contributors"> + <img src="https://contributors.nn.ci/api?repo=xun082/create-neat" alt="贡献者名单"> +</a> -module.exports = { - rollup(config, options) { - config.plugins.push(postcss()); - return config; - }, -}; -``` - -### 五、贡献 🍵 +### 六、贡献指南 -> 如果你正在使用这个项目或者对这个项目感兴趣,可以通过以下方式支持我: +[查看贡献指南文档]()
链接没有
create-neat
github_2023
others
278
xun082
uaenaTzx
@@ -1,223 +1,86 @@ -## Create-Neat -### README.md -- zh_CN [简体中文](README.md) -- en [English](readme/README-EN.md) +<h1 align="center" style="font-size: 2.5em; color: #333;">Create-Neat</h1> +<hr style="border: 1px solid #ccc;"/> +<p align="center" style="font-size: 1.2em; color: #555; max-width: 800px; line-height: 1.5;"> + <strong>Create-Neat</strong> 是一款轻量级脚手架工具,专为提供 + <span style="color: #007BFF;">开箱即用</span>和 + <span style="color: #007BFF;">零配置</span>体验而设计,旨在帮助用户快速且轻松地构建项目,同时支持多样的技术栈选择。 +</p> -### 一、背景 📖 -在刚开始学习 `React` 的时候,使用的脚手架就是 `create-react-app`,虽然这个脚手架提供的零配置、开箱即用很适合新手,但是要想对其进行扩展就非常麻烦。要想对其进行扩展你必须 `eject` 或者 使用 `carco` 进行配置。 +### 一、背景 📖 -尽管 `Typescript` 已经流行了很久,但是要从零设计一个 `Typescript` 库依旧麻烦,本人也曾有过从零搭建一个 `React` 组件库的想法,但是对一堆陌生的配置望而生畏。 +当前社区中已有众多优秀的前端脚手架工具,如 create-vite、create-next-app 和 create-react-app 等。这些工具在设计上确实优秀且强大,但仍然面临两个主要问题: +- **黑盒环境**:新手在使用这些工具时,配置过程较为复杂,存在较高的学习成本和心智负担。 +- **灵活性不足**:许多脚手架工具仅专注于特定技术栈,若需要集成其他技术栈,往往需寻找额外的脚手架。 -`Create-Neat` 就是为了解决这些问题应运而生的,解决以上所有问题,开箱即用,零配置 🚀🚀🚀 +[Create-Neat](https://create-neat.github.io/docs/) 旨在解决上述问题,使开发者能够快速创建项目,无需担心复杂的配置,同时提供广泛的技术栈选择 🚀🚀🚀。 -### 二、特性 🧰 +### 二、我们的特点 🧰 -- 📦 零配置,开箱即用; -- 🚀 使用 `axios` + `npm` 的方式构建你的项目基础模板,初始化速度要比 `create-react-app` 快; -- 💯 代码风格统一,项目统一配置 `Eslint`、`Prettier`、`Husky`; -- 🥂 使用 `Rollup` 打包你的 `Typescript` 库,支持 `UMD`、`CJS`、`ESM` 输出格式,并生成全局 `.d.ts` 文件; -- 🍻 支持用户自定义 `Rollup` 配置扩展原有的配置,为项目添加特有的功能; -- 🥂 使用 `Webpack` 打包你的 `Web` 应用程序,实现多环境打包部署,代码分割优化,配合官方分析工具,实时优化代码; -- 🍻 支持用户自定义 `Webpack` 配置扩展原有的配置,为项目添加特有的功能; -- 🎯 支用户自定义 `Babel` 配置,让你的程序更健壮; -- 📕 友好的日志输出,让你快速定位问题所在以及增加开发体验; -- 在使用 `Husky` 的情况下使用 `standard-version` 自动生成 `CHANGELOG` 文件; -- 🔸 等等...... +- 📦 **零配置,开箱即用。** +- 🚀 **插件式项目生成**:根据用户需求灵活生成不同基础项目。 +- 🧠 **支持无限扩展的架构**:框架、构建工具和插件的潜力无限。 +- 💯 **丰富的使用教程和代码注释**:帮助每位社区成员快速学习前端工程化相关知识。 +- 👌 **完善且细致的贡献流程**:手把手指导从学习到贡献的过程。 +- ⚙️ **定期更新与维护**:定期更新工具,修复bug、完善功能、加入新的技术栈支持。 +- 🎉 **用户友好的体验**:专注于用户体验,力求让每一位用户都能享受到流畅、无阻的开发过程。 +- 🔸 **更多特性等待你的贡献!** ### 三、快速开始 🚩 +#### 安装依赖 +```shell +npm install -g create-neat ``` -npx create-neat my-app -cd my-app -npm start -``` - -如果你之前已经通过 `npm install -g create-neat` 全局安装了 `create-neat`,我们建议你使用 `npm uninstall -g create-neat` 或 `yarn global remove create-neat` 来卸载这个包,以确保 npx 总是使用最新的版本。 - -当你在终端中输入 `npx create-neat my-app` 时,控制台会有以下选项功能选择: - -![在这里插入图片描述](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b1423eca147545c698bec5b7f30f2da2~tplv-k3u1fbpfcp-zoom-1.image) - -`create-neat` 会根据你的创建不同的应用程序,这些应用程序都是开箱即用,无需配置,其中: - -- `common-lib`:一个基础的 `Typescript` 库,您可以使用该模板来编写一个类似于 `lodash` 的工具库; -- `react-ui`: 为你快速创建一个 `react` 组件库,内置 `storybook` 让你快速编写你的组件库文档,并且使用 `standard-version` 自动为你生成 `CHANGELOG` 文件; -- 剩下的四个都是为你创建不用的 `web` 应用程序,其中 `vue` 同时支持 `.vue` 和 `.tsx` 的语法。 - -如果项目创建成功,会有如下效果图所示: - -![在这里插入图片描述](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/fe46e77448d54c14aebf4557db949883~tplv-k3u1fbpfcp-zoom-1.image) - -> 更多使用方式后续会在 [掘金](https://juejin.cn/user/3782764966460398/posts) 中以文章方式呈现出来,感兴趣的小伙伴可以关注一下。 - -### 四、 创建应用程序 📕 - -要创建一个新的应用程序,您可以选择以下方法之一: - -#### NPX - -``` -npx create-neat my-app -``` - -#### NPM - -``` -npm init neat my-app -``` - -#### YARN - -``` -yarn create neat my-app -``` - -它将在当前文件夹中创建一个名为 my-app 的目录。 -在该目录中,它将根据你所选择的项目类型生成不同的初始项目结构并根据你所选择的包管理工具进行安装可传递的依赖项,例如当你选择 `react-ui` 时会为你创建一个开箱即用的组件库模板,具体目录结构如下所示: - -``` -├───📁 .husky/ -│ ├───📄 commit-msg -│ └───📄 pre-commit -├───📁 .storybook/ -│ ├───📄 main.js -│ └───📄 preview.js -├───📁 .vscode/ -│ └───📄 settings.json -├───📁 example/ -│ ├───📄 App.tsx -│ ├───📄 index.html -│ ├───📄 index.tsx -│ ├───📄 package.json -│ └───📄 tsconfig.json -├───📁 src/ -│ ├───📁 components/ -│ │ └───... -│ └───📄 index.tsx -├───📁 stories/ -│ └───📄 button.stories.tsx -├───📄 .eslintignore -├───📄 .eslintrc.json -├───📄 .gitignore -├───📄 .prettierignore -├───📄 .prettierrc.json -├───📄 babel.config.js -├───📄 commitlint.config.js -├───📄 package.json -├───📄 pnpm-lock.yaml -└───📄 tsconfig.json -``` - -无需配置或复杂的文件夹结构,只有构建应用程序所需的文件。 -安装完成后,你可以打开你的项目文件夹: - -``` -cd my-app +#### 创建项目 +```shell +create-neat <project-name> ``` -在新创建的项目中,您可以运行一些内置命令: - -#### `npm start`、`pnpm start` 或者 `yarn start` +输入命令 `create-neat my-app` 后,控制台将提供以下功能选择: -如果你使用的是 `web` 相对应的项目类型,则在开发模式下运行应用程序并自动打开 [http://localhost:3000](http://localhost:3000) 在浏览器中进行查看,否则则使用 `Rollup` 中的 `watch` 钩子在命令行终端中监听您文件的变化。 +![功能选择界面](https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/ffd53bd2e3a546b6bbc4da69161e7dae~tplv-k3u1fbpfcp-jj-mark:0:0:0:0:q75.image#?w=987&h=198&s=22353&e=png&b=1e1e1e) -#### `npm build`、`pnpm build` 或者 `yarn build` +根据需求选择对应框架,或通过 `Manually select preset` 进行自由组合。`create-neat` 将根据选择的预设创建不同的开箱即用应用程序,选项包括: -如果您使用的是 `web` 应用程序,使用该命令则会将其应用程序优化构建以获得最佳性能并将其存放与 `dist` 目录下。 +- **框架**:`react`、`vue` 或 `类库/工具库`。 +- **构建工具**:`webpack`、`vite` 等。 +- **插件**:`eslint`、`prettier`、`typescript`、`babel`、`swc` 等。 +- **其他选项**:包管理器、镜像源等。 -如果您在项目初始化的时候选择的 `common-lib` 或者 `react-ui`,那么该应用程序将会使用 `Rollup` 进行打包构建,并根据你所传入的参数构建成不同格式的文件,完整参数配置如下所示: +这些选项通过我们的设计抽象层,在生成器架构中创建最终项目。 -``` -Usage - $ rollup-script build [options] - -Options - --target 指定目标环境 默认使用 web - --name 指定在 UMD 模式构建中全局的名称 - --format 指定模式格式(cjs,esm,umd) 默认是 esm - -Examples - $ rollup-script build --target node - $ rollup-script build --name Foo - $ rollup-script build --format cjs,esm,umd - $ rollup-script build --format umd --name Foo -``` - -### Babel - -您可以将自己的 `Babel` 配置添加到项目的根目录当中, `create-neat` 会将其与自己原有的 `Babel` 转换合并并且将新的预设和插件放在列表的末尾。 +若项目创建成功,可查看如下效果图: -#### Example - -```js -// babel.config.js - -module.exports = { - plugins: ["babel-plugin-styled-components"], -}; -``` +![项目创建成功](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/fe46e77448d54c14aebf4557db949883~tplv-k3u1fbpfcp-zoom-1.image)
图片上有掘金水印
create-neat
github_2023
others
278
xun082
uaenaTzx
@@ -1,223 +1,89 @@ -## Create-Neat -### README.md -- zh_CN [简体中文](README.md) -- en [English](readme/README-EN.md) +<h1 align="center" style="font-size: 2.5em; color: #333;">Create-Neat</h1> +<hr style="border: 1px solid #ccc;"/> +<p align="center" style="font-size: 1.2em; color: #555; max-width: 800px; line-height: 1.5;"> + <strong>Create-Neat</strong> 是一款轻量级脚手架工具,专为提供 + <span style="color: #007BFF;">开箱即用</span>和 + <span style="color: #007BFF;">零配置</span>体验而设计,旨在帮助用户快速且轻松地构建项目,同时支持多样的技术栈选择。 +</p> -### 一、背景 📖 -在刚开始学习 `React` 的时候,使用的脚手架就是 `create-react-app`,虽然这个脚手架提供的零配置、开箱即用很适合新手,但是要想对其进行扩展就非常麻烦。要想对其进行扩展你必须 `eject` 或者 使用 `carco` 进行配置。 +### 一、背景 📖 -尽管 `Typescript` 已经流行了很久,但是要从零设计一个 `Typescript` 库依旧麻烦,本人也曾有过从零搭建一个 `React` 组件库的想法,但是对一堆陌生的配置望而生畏。 +当前社区中已有众多优秀的前端脚手架工具,如 create-vite、create-next-app 和 create-react-app 等。这些工具在设计上确实优秀且强大,但仍然面临两个主要问题: +- **黑盒环境**:新手在使用这些工具时,配置过程较为复杂,存在较高的学习成本和心智负担。 +- **灵活性不足**:许多脚手架工具仅专注于特定技术栈,若需要集成其他技术栈,往往需寻找额外的脚手架。 -`Create-Neat` 就是为了解决这些问题应运而生的,解决以上所有问题,开箱即用,零配置 🚀🚀🚀 +[Create-Neat](https://create-neat.github.io/docs/) 旨在解决上述问题,使开发者能够快速创建项目,无需担心复杂的配置,同时提供广泛的技术栈选择 🚀🚀🚀。 -### 二、特性 🧰 +### 二、关于我们 🧰 -- 📦 零配置,开箱即用; -- 🚀 使用 `axios` + `npm` 的方式构建你的项目基础模板,初始化速度要比 `create-react-app` 快; -- 💯 代码风格统一,项目统一配置 `Eslint`、`Prettier`、`Husky`; -- 🥂 使用 `Rollup` 打包你的 `Typescript` 库,支持 `UMD`、`CJS`、`ESM` 输出格式,并生成全局 `.d.ts` 文件; -- 🍻 支持用户自定义 `Rollup` 配置扩展原有的配置,为项目添加特有的功能; -- 🥂 使用 `Webpack` 打包你的 `Web` 应用程序,实现多环境打包部署,代码分割优化,配合官方分析工具,实时优化代码; -- 🍻 支持用户自定义 `Webpack` 配置扩展原有的配置,为项目添加特有的功能; -- 🎯 支用户自定义 `Babel` 配置,让你的程序更健壮; -- 📕 友好的日志输出,让你快速定位问题所在以及增加开发体验; -- 在使用 `Husky` 的情况下使用 `standard-version` 自动生成 `CHANGELOG` 文件; -- 🔸 等等...... +#### 核心特点 +- 📦 **零配置,开箱即用。** +- 🚀 **插件式项目生成**:根据用户需求灵活生成不同基础项目。 +- 🧠 **支持无限扩展的架构**:框架、构建工具和插件的潜力无限。 +- 💯 **丰富的使用教程和代码注释**:帮助每位社区成员快速学习前端工程化相关知识。 +- 👌 **完善且细致的贡献流程**:手把手指导从学习到贡献的过程。 +- 🔸 **更多特性等待你的贡献!** +#### 社区支持 +- 🌈 **活跃的社区氛围**:提供丰富的技术交流和学习资源,帮助开发者快速成长。 +- ⚙️ **定期更新与维护**:定期更新工具,修复bug、完善功能、加入新的技术栈支持。 +- 🎉 **用户友好的体验**:专注于用户体验,力求让每一位用户都能享受到流畅、无阻的开发过程。 ### 三、快速开始 🚩 +#### 安装依赖 +```shell +npm install -g create-neat ``` -npx create-neat my-app -cd my-app -npm start -``` - -如果你之前已经通过 `npm install -g create-neat` 全局安装了 `create-neat`,我们建议你使用 `npm uninstall -g create-neat` 或 `yarn global remove create-neat` 来卸载这个包,以确保 npx 总是使用最新的版本。 - -当你在终端中输入 `npx create-neat my-app` 时,控制台会有以下选项功能选择: - -![在这里插入图片描述](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b1423eca147545c698bec5b7f30f2da2~tplv-k3u1fbpfcp-zoom-1.image) - -`create-neat` 会根据你的创建不同的应用程序,这些应用程序都是开箱即用,无需配置,其中: - -- `common-lib`:一个基础的 `Typescript` 库,您可以使用该模板来编写一个类似于 `lodash` 的工具库; -- `react-ui`: 为你快速创建一个 `react` 组件库,内置 `storybook` 让你快速编写你的组件库文档,并且使用 `standard-version` 自动为你生成 `CHANGELOG` 文件; -- 剩下的四个都是为你创建不用的 `web` 应用程序,其中 `vue` 同时支持 `.vue` 和 `.tsx` 的语法。 - -如果项目创建成功,会有如下效果图所示: - -![在这里插入图片描述](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/fe46e77448d54c14aebf4557db949883~tplv-k3u1fbpfcp-zoom-1.image) - -> 更多使用方式后续会在 [掘金](https://juejin.cn/user/3782764966460398/posts) 中以文章方式呈现出来,感兴趣的小伙伴可以关注一下。 - -### 四、 创建应用程序 📕 - -要创建一个新的应用程序,您可以选择以下方法之一: - -#### NPX - -``` -npx create-neat my-app -``` - -#### NPM - -``` -npm init neat my-app -``` - -#### YARN - -``` -yarn create neat my-app -``` - -它将在当前文件夹中创建一个名为 my-app 的目录。 -在该目录中,它将根据你所选择的项目类型生成不同的初始项目结构并根据你所选择的包管理工具进行安装可传递的依赖项,例如当你选择 `react-ui` 时会为你创建一个开箱即用的组件库模板,具体目录结构如下所示: - -``` -├───📁 .husky/ -│ ├───📄 commit-msg -│ └───📄 pre-commit -├───📁 .storybook/ -│ ├───📄 main.js -│ └───📄 preview.js -├───📁 .vscode/ -│ └───📄 settings.json -├───📁 example/ -│ ├───📄 App.tsx -│ ├───📄 index.html -│ ├───📄 index.tsx -│ ├───📄 package.json -│ └───📄 tsconfig.json -├───📁 src/ -│ ├───📁 components/ -│ │ └───... -│ └───📄 index.tsx -├───📁 stories/ -│ └───📄 button.stories.tsx -├───📄 .eslintignore -├───📄 .eslintrc.json -├───📄 .gitignore -├───📄 .prettierignore -├───📄 .prettierrc.json -├───📄 babel.config.js -├───📄 commitlint.config.js -├───📄 package.json -├───📄 pnpm-lock.yaml -└───📄 tsconfig.json -``` - -无需配置或复杂的文件夹结构,只有构建应用程序所需的文件。 -安装完成后,你可以打开你的项目文件夹: - -``` -cd my-app +#### 创建项目 +```shell +create-neat <project-name> ``` -在新创建的项目中,您可以运行一些内置命令: - -#### `npm start`、`pnpm start` 或者 `yarn start` +输入命令 `create-neat my-app` 后,控制台将提供以下功能选择: -如果你使用的是 `web` 相对应的项目类型,则在开发模式下运行应用程序并自动打开 [http://localhost:3000](http://localhost:3000) 在浏览器中进行查看,否则则使用 `Rollup` 中的 `watch` 钩子在命令行终端中监听您文件的变化。 +![功能选择界面](https://imgur.la/images/2024/10/21/1.png) -#### `npm build`、`pnpm build` 或者 `yarn build` +根据需求选择对应框架,或通过 `Manually select preset` 进行自由组合。`create-neat` 将根据选择的预设创建不同的开箱即用应用程序,选项包括: -如果您使用的是 `web` 应用程序,使用该命令则会将其应用程序优化构建以获得最佳性能并将其存放与 `dist` 目录下。 +- **框架**:`react`、`vue` 或 `类库/工具库`。 +- **构建工具**:`webpack`、`vite` 等。 +- **插件**:`eslint`、`prettier`、`typescript`、`babel`、`swc` 等。 +- **其他选项**:包管理器、镜像源等。 -如果您在项目初始化的时候选择的 `common-lib` 或者 `react-ui`,那么该应用程序将会使用 `Rollup` 进行打包构建,并根据你所传入的参数构建成不同格式的文件,完整参数配置如下所示: +这些选项通过我们的设计抽象层,在生成器架构中创建最终项目。 -``` -Usage - $ rollup-script build [options] - -Options - --target 指定目标环境 默认使用 web - --name 指定在 UMD 模式构建中全局的名称 - --format 指定模式格式(cjs,esm,umd) 默认是 esm - -Examples - $ rollup-script build --target node - $ rollup-script build --name Foo - $ rollup-script build --format cjs,esm,umd - $ rollup-script build --format umd --name Foo -``` - -### Babel - -您可以将自己的 `Babel` 配置添加到项目的根目录当中, `create-neat` 会将其与自己原有的 `Babel` 转换合并并且将新的预设和插件放在列表的末尾。 +若项目创建成功,可查看如下效果图: -#### Example - -```js -// babel.config.js - -module.exports = { - plugins: ["babel-plugin-styled-components"], -}; -``` +![项目创建成功](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/fe46e77448d54c14aebf4557db949883~tplv-k3u1fbpfcp-zoom-1.image) -### webpack - -> ⚠️ Warning -> 这些修改有可能覆盖 `create-neat` 的默认行为和配置,请谨慎使用! - -如果您想扩展 `webpack` 配置已增加项目对不同功能的支持或者增加项目性能,您可以在 `webpack.config.js` 文件下对 `webpack` 配置进行扩展.并且您可以使用 `process.env.NODE_ENV` 以区分开发环境和生产环境。 - -#### Example - -```js -// webpack.config.js - -const MiniCssExtractPlugin = require("mini-css-extract-plugin"); -const isDevelopment = process.env.NODE_ENV === "development"; - -module.exports = { - plugins: [isDevelopment && MiniCssExtractPlugin()], -}; +#### 启动项目 +```shell +cd <project-name> +npm start ``` -### Rollup +至此,你可以开始项目的开发了!如欲深入了解项目启动方式、架构等细节,欢迎加入我们的社区群或查阅文档网站(建设中)。 -> ⚠️ Warning -> 这些修改有可能覆盖 `create-neat` 的默认行为和配置,请谨慎使用! +### 五、贡献者 -如果你选择的项目类型是 `common-lib` 或者 `react-ui` 并且您希望更改 `Rollup` 配置,可以在项目的根目录下创建一个名为 `rollup.config.js` 的文件,示例代码如下所示: +感谢以下贡献者的支持,诚邀更多技术大佬加入我们的行列! -```js -module.exports = { - rollup(config, options) { - return config; - }, -}; -``` - -#### Example - -```js -const postcss = require("rollup-plugin-postcss"); +<a href="https://github.com/xun082/create-neat/contributors"> + <img src="https://contributors.nn.ci/api?repo=xun082/create-neat" alt="贡献者名单"> +</a> -module.exports = { - rollup(config, options) { - config.plugins.push(postcss()); - return config; - }, -}; -``` - -### 五、贡献 🍵 +### 六、贡献指南 -> 如果你正在使用这个项目或者对这个项目感兴趣,可以通过以下方式支持我: +[查看贡献指南文档](https://rwndk8l22n.feishu.cn/docx/IF5id8KlPo7pNAxff5Ic2W8bnzf) -- **Star、Fork、Watch** 一键三连 🚀🚀🚀 +### 七、加入我们 -> 我们很乐意在 `create-neat` 中得到您的帮助,看到您的贡献,如果你想获取到更多信息以及如何开始,请扫描进群: +我们诚挚欢迎大家在 `create-neat` 中贡献力量。若想获取更多信息及如何开始,欢迎扫码加入我们的群聊: <center>
微信群二维码会失效的,换成微信号吧
create-neat
github_2023
typescript
285
xun082
uaenaTzx
@@ -1,9 +1,14 @@ // 插件对框架的协议 -export const pluginToTemplateProtocol = { +exports.pluginToTemplateProtocol = { ENTRY_FILE: "ENTRY_FILE", // 入口文件配置,如:入口文件引入全局 less、scss // …… }; // 插件对构建工具的协议 - +exports.pluginToBuildToolProtocol = {}; // 框架对构建工具的协议 +exports.templateToBuildToolProtocol = { + ENTRY_FILE: "ENTRY_FILE", //入口文件配置,比如根据不同框架引入不同方法
我感觉通用协议可以维护在一个对象里面,通过 ...XXX 的方式存入每个 protocol 中
create-neat
github_2023
typescript
285
xun082
uaenaTzx
@@ -3,6 +3,13 @@ import path from "path"; import Generator from "./Generator"; import PluginToTemplateAPI from "./protocolGenerator/PluginToTemplateAPI"; +import TemplateToBuildToolAPI from "./protocolGenerator/TemplateToBuildToolAPI"; + +const {
怎么一会 esm 一会 cjs 的写法
create-neat
github_2023
typescript
285
xun082
uaenaTzx
@@ -0,0 +1,76 @@ +import path from "path"; + +import { createConfigByParseAst } from "../../utils/ast/parseAst"; +import { relativePathToRoot } from "../../utils/constants"; + +import ProtocolGeneratorAPI from "./ProtocolGeneratorAPI"; + +/** + * 框架对构建工具协议 + * @param protocols 协议内容 + */ +class TemplateToBuildToolAPI extends ProtocolGeneratorAPI { + protected declare protocols: Record<string, object>; // todo 类型考虑优化 + + constructor(protocols) { + super(protocols); + this.protocols = protocols; + } + + generator() { + // todo: 加入优先级调度 + for (const protocol in this.protocols) { + this[protocol](this.protocols[protocol]); + } + } + async loadModule(modulePath: string, rootDirectory: string) { + /** + * 解析后的路径。 + * @type {string} + */ + const resolvedPath = path.resolve(rootDirectory, modulePath); + try { + const module = await require(resolvedPath); + return module; + } catch (error) { + console.error(`Error loading module at ${resolvedPath}:`, error); + return null; + } + } + // 入口的先暂时不做 + // ENTRY_FILE(params) { + // } + async ADD_CONFIG(params) {
强烈建议 ts 类型声明一下
create-neat
github_2023
others
285
xun082
uaenaTzx
@@ -7,4 +9,17 @@ module.exports = (templateAPI) => { "vue-template-compiler": "^2.7.16", }, }); + + templateAPI.protocolGenerate({ + [templateToBuildToolProtocol.ADD_CONFIG]: { + params: { + content: { + buildToolName: 'webpack', //这里怎么拿选项呢?
不应该在这里传入吧,preset 在 Generator 里面就可以拿到
create-neat
github_2023
typescript
281
xun082
uaenaTzx
@@ -1,7 +1,102 @@ +// 通用协议 +export const commonProtocol = {
有问题,configs 只是定义有什么协议,但是具体做什么事情是要在插件里面做的 比如 scss,不应该在这里定义,而是在 plugin-scss 里去配置,注意看看我之前的实现视频
create-neat
github_2023
typescript
279
xun082
uaenaTzx
@@ -0,0 +1,24 @@ +export type BuildToolType = "webpack" | "vite" | "rollup";
感觉和 packages/core/src/constants/ast.ts 那块有耦合
create-neat
github_2023
typescript
279
xun082
uaenaTzx
@@ -0,0 +1,24 @@ +export type BuildToolType = "webpack" | "vite" | "rollup"; + +interface Import {
类名可以再精准一些,直接看 Import 看不出什么东西 可以用 ASTImport 之类的,提高语义
create-neat
github_2023
typescript
279
xun082
uaenaTzx
@@ -0,0 +1,83 @@ +import traverse from "@babel/traverse"; +import { objectExpression, stringLiteral, arrayExpression } from "@babel/types"; + +import type { Plugin } from "../../../types/ast"; +import { Build_Tool } from "../../../constants/ast"; +import { + createImportDeclaration, + createCallExpression, + createObjectProperty, +} from "../uno/commonAst"; + +import { BaseAst } from "./baseAst"; + +export class VitepackAst extends BaseAst {
应该是 VitePackAst 吧
create-neat
github_2023
typescript
279
xun082
uaenaTzx
@@ -0,0 +1,112 @@ +import traverse from "@babel/traverse"; +import { objectExpression, regExpLiteral, stringLiteral, arrayExpression } from "@babel/types"; + +import { Build_Tool } from "../../../constants/ast"; +import { createObjectProperty, createNewExpression } from "../uno/commonAst"; + +import { BaseAst } from "./baseAst"; + +export class WebpackAst extends BaseAst { + private rules; + private plugins; + + constructor(options, ast) { + super(Build_Tool.WEBPACK, options, ast); + + this.rules = options.rules; + this.plugins = options.plugins; + } + + /** + * 合并webpack config ast + * 目前支持loaders、plugins + */ + mergeConfig() { + if (!this.plugins) return; + traverse(this.ast, { + ExpressionStatement: (path) => { + const astNode = path.node; + // 只匹配模板中的module.exports部分 + if (!astNode.expression.left.object) return; + if (astNode.expression.left.object.name !== "module") return; + // 遍历module.exports对象中的每个属性的ast节点 + astNode.expression.right.properties.forEach((property) => { + // 匹配到plugins属性,根据传入的options中的plugin生成ast进行插入 + if (property.key.name === "plugins") { + const pluginAstNodes = []; + this.plugins.forEach((plugin) => { + pluginAstNodes.push(createNewExpression(plugin.name, [])); + }); + pluginAstNodes.forEach((ast) => property.value.callee.object.elements.push(ast)); + } + // 匹配到module属性,将传入的options中的rules转化为ast进行插入 + if (property.key.name === "module") { + const rulesAstNodes = []; + this.rules.forEach((rule) => { + const formatReg = (str) => str.substring(1, str.length - 1); + let parseIncludeAst; + let parseExcludeAst; + let parseLoaderAst; + let ruleAstNode; + // 如果include属性为数组 + if (Array.isArray(rule.include)) { + parseIncludeAst = arrayExpression(rule.include.map((item) => stringLiteral(item))); + } else { + // 如果include属性值为正则表达式 + parseIncludeAst = regExpLiteral(formatReg(`${rule.include}`)); + } + // 如果exclude属性值为数组 + if (Array.isArray(rule.exclude)) { + parseExcludeAst = arrayExpression( + rule.exclude.map((item) => regExpLiteral(formatReg(`${item}`))), + ); + } else { + // 如果exclude属性值为正则 + parseExcludeAst = regExpLiteral(formatReg(`${rule.exclude}`)); + } + if (rule.loader) { + if (Array.isArray(rule.loader)) { + parseLoaderAst = arrayExpression(rule.loader.map((item) => stringLiteral(item))); + } else { + parseLoaderAst = stringLiteral(rule.loader); + } + ruleAstNode = objectExpression([
这块感觉可以抽离出来,我看有复用
create-neat
github_2023
typescript
279
xun082
uaenaTzx
@@ -0,0 +1,112 @@ +import traverse from "@babel/traverse"; +import { objectExpression, regExpLiteral, stringLiteral, arrayExpression } from "@babel/types"; + +import { Build_Tool } from "../../../constants/ast"; +import { createObjectProperty, createNewExpression } from "../uno/commonAst"; + +import { BaseAst } from "./baseAst"; + +export class WebpackAst extends BaseAst { + private rules; + private plugins; + + constructor(options, ast) { + super(Build_Tool.WEBPACK, options, ast); + + this.rules = options.rules; + this.plugins = options.plugins; + } + + /** + * 合并webpack config ast + * 目前支持loaders、plugins + */ + mergeConfig() {
这个函数可以注释的更清楚一些,我看着有些迷糊
create-neat
github_2023
others
248
xun082
uaenaTzx
@@ -0,0 +1,9 @@ +module.exports = (generatorAPI) => { + generatorAPI.extendPackage({ + devDependencies: { + "element-plus": "^2.7.8", + "unplugin-auto-import": "^0.18.2",
为什么需要两个 unplugin 的插件
create-neat
github_2023
others
248
xun082
uaenaTzx
@@ -0,0 +1,4 @@ +{ + "recommendations": ["Vue.volar"]
这个为什么要做
create-neat
github_2023
typescript
274
xun082
uaenaTzx
@@ -166,16 +166,28 @@ async function projectSelect() { ], }; + const useSpecilPligins = await select({
感觉可以进一步优化一下 从用户直觉,看特殊插件,其实看不出来有啥,那也不好做选择,那么最好就把这个选择合并到下面的 specialPlugins 里面去,高亮显示
create-neat
github_2023
typescript
276
xun082
IsDyh01
@@ -225,14 +225,14 @@ class FileTree { */ async renderAllFiles(parentDir: string, fileData: FileData = this.fileData) { // 渲染根fileTree对象中的children中的内容 --> 根目录内的文件 - fileData.children.forEach(async (item: FileData) => { + for (const item of fileData.children) {
为什么要把forEach替换成for of?
create-neat
github_2023
others
267
xun082
uaenaTzx
@@ -5,4 +5,5 @@ rollup.config.js commitlint.config.js packages/*/dist/ -apps/ \ No newline at end of file +apps/ +packages/core/src/**/webpack.config.ejs
ejs 格式不需要忽略,忽略的应该是 文件格式不是 ejs 但是写了 ejs 语法的
create-neat
github_2023
typescript
258
xun082
uaenaTzx
@@ -126,15 +126,21 @@ export default async function createAppTest(projectName: string, options: Record } // 2. 初始化构建工具配置文件 +
hack 的只是一个 element-plus,不应该把整个配置都拿出来
create-neat
github_2023
typescript
258
xun082
uaenaTzx
@@ -1,18 +1,7 @@ import ejs from "ejs"; -import { buildToolType } from "../types"; - -export default function generateWebpackConfigFromEJS( - framework: string, - bundler: buildToolType, - language: string, - template: string, -) { - const config = ejs.render(template, { - framework, - bundler, - language, - }); +export default function generateWebpackConfigFromEJS(options, template: string) {
虽然不影响使用,但是这个命名标准没对上 generateBuildToolConfigFromEJS、generateWebpackConfigFromEJS
create-neat
github_2023
others
258
xun082
uaenaTzx
@@ -104,7 +114,7 @@ const productionPlugins = isProduction ? [ module.exports = { stats: 'errors-warnings', - entry: '<% if (framework === "react") { %><% if (language === "typescript" || (bundler === "swc" && language === "typescript")) { %>./src/index.tsx<% } else if (language === "javascript" || (bundler === "swc" && language === "javascript")) { %>./src/index.jsx<% } %><% } else if (framework === "vue") { %><% if (language === "typescript" || (bundler === "swc" && language === "typescript")) { %>./src/main.tsx<% } else if (language === "javascript" || (bundler === "swc" && language === "javascript")) { %>./src/main.jsx<% } else { %>./src/main.ts<% } %><% } %>', + entry: '<% if (framework === "react") { %><% if (language === "typescript") { %>./src/index.tsx<% } else if (language === "javascript") { %>./src/index.jsx<% } %><% } else if (framework === "vue") { %><% if (language === "typescript") { %>./src/main.ts<% } else if (language === "javascript") { %>./src/main.js<% } else { %>./src/main.js<% } %><% } %>',
首先这个格式太乱了,该换行的换行,其次这样的判断可读性、维护性都很差,可以参考这种方式: <% const paths = { react: { typescript: "./src/index.tsx", javascript: "./src/index.jsx", }, vue: { typescript: "./src/main.ts", javascript: "./src/main.js", } }; // 默认路径(如果框架或者语言不匹配) const defaultPath = "./src/main.js"; // 选择路径:先判断 framework 是否存在映射,如果存在再判断 language 是否存在映射 const selectedPath = paths[framework]?.[language] || defaultPath; %> <%= selectedPath %> <% %> 中定义的变量作用域是全局的,所以可以在最前头用 <% %> 声明相关的变量,做判断然后赋值,在后面的代码中直接用<%= selectedPath %>消费,代码结构会好看很多
create-neat
github_2023
typescript
259
xun082
uaenaTzx
@@ -107,65 +112,116 @@ class FileTree { return file; } + /** + * 借助ejs构造文件树对象 + * @static
static 和 private 不对应
create-neat
github_2023
typescript
259
xun082
uaenaTzx
@@ -107,65 +112,116 @@ class FileTree { return file; } + /** + * 借助ejs构造文件树对象 + * @static + * @param {string} src - 文件或文件夹的真实路径 + * @param {string} parentDir - 创建文件后的父文件夹路径 + * @param {string} options - ejs渲染配置参数 + * @returns {FileData} - 文件树对象 + */ + private buildFileDataByEjs(src: string, parentDir: string, options: any) { + const baseName = path.basename(src); + const file: FileData = { + path: "", + children: [], + describe: {}, + }; + if (isDirectoryOrFile(src)) { + file.type = "dir"; + file.path = path.resolve(parentDir, baseName); + file.describe.fileName = baseName; + const entries = fs.readdirSync(src, { + withFileTypes: true, + }); + for (const entry of entries) { + const subTree = this.buildFileDataByEjs( + path.join(src, entry.name), + path.relative(parentDir, baseName), + options, + ); + file.children?.push(subTree); + } + } else { + const ejsTempalte = fs.readFileSync(src, "utf8"); + const fileContent = ejs.render(ejsTempalte, options); + file.type = "file"; + file.describe = { + fileName: path.basename(src).split(".")[0], + fileExtension: process.env.isTs + ? this.alteration[path.extname(src).slice(1)] + ? this.alteration[path.extname(src).slice(1)] + : path.extname(src).slice(1) + : path.extname(src).slice(1), + fileContent, + }; + file.path = path.resolve( + parentDir, + `${file.describe.fileName}.${file.describe.fileExtension}`, + ); + } + return file; + } + /** * 遍历树的一个方法,对每个fileData对象做一次handleFn处理 * @param {FileData} file - 文件数对象 * @param {(file: FileData) => any} handleFn - 处理文件树对象的函数 */ - traverseTree(file: FileData, handleFn: (file: FileData, getFileByName?: any) => any) { - handleFn(file); - if (file.children.length) { - file.children.forEach((subFile) => this.traverseTree(subFile, handleFn)); - } - } + // traverseTree(file: FileData, handleFn: (file: FileData, getFileByName?: any) => any) {
用不到了就删了?
create-neat
github_2023
typescript
254
xun082
uaenaTzx
@@ -283,6 +286,8 @@ class Generator { useReactRouter: !!this.preset.plugins["react-router"], }, }; + console.log(111);
日志
create-neat
github_2023
typescript
249
xun082
uaenaTzx
@@ -265,6 +266,7 @@ class Generator { `template-${this.templateName}/generator/template`, ); + const preset = await projectSelect();
preset 从 Generator 的 Constructor 里面传进来吧,前面群里说的
create-neat
github_2023
javascript
246
xun082
uaenaTzx
@@ -0,0 +1,95 @@ +// App.js.ejs +import React from "react";
这个文件如果加进去了,会和 template-react 冲突吧,之前说是在 ejs 渲染阶段传入 router 是否使用的一个参数,然后控制 template-reat 中的代码片段是否展示(ejs)
create-neat
github_2023
typescript
246
xun082
uaenaTzx
@@ -176,7 +176,7 @@ class FileTree { */ async fileRender(src: string, file: FileData, options: any) { const rendered = ejs.render(file.describe?.fileContent, options, {}); - await fs.writeFile(src, rendered); + await fs.writeFile(src, rendered,{flag: 'w'});
这个新增是为了什么
create-neat
github_2023
typescript
226
xun082
IsDyh01
@@ -4,12 +4,12 @@ import { exec } from "child_process"; import { confirm } from "@clack/prompts"; import chalk from "chalk"; import { parse } from "@babel/parser"; -import path from "path"; +import path, { join } from "path";
这个直接用path.join()不用再引入了吧
create-neat
github_2023
typescript
225
xun082
uaenaTzx
@@ -151,6 +151,33 @@ async function projectSelect() { required: false, })) as string[]; + // 根据不同框架加载对应的插件列表
这一步的逻辑可以抽象出来,比如用一个 map vue => { plugins:[ {key,value} ], description:“xxxxx” }
create-neat
github_2023
others
225
xun082
uaenaTzx
@@ -0,0 +1,9 @@ +module.exports = (generatorAPI) => { + generatorAPI.extendPackage({ + devDependencies: { + mobx: "^6.6.4", + "mobx-react":"^7.4.0", + }, + }); +}; +
template 文件里写一个初始配置,同时要确保生成的项目可以跑通
create-neat
github_2023
others
222
xun082
uaenaTzx
@@ -0,0 +1,158 @@ +// @see: https://cz-git.qbenben.com/zh/guide
这个文件默认不需要配置那么多的,要考虑到初学者用户,这些配置反而造成复杂度和心智负担
create-neat
github_2023
others
222
xun082
uaenaTzx
@@ -0,0 +1,158 @@ +// @see: https://cz-git.qbenben.com/zh/guide +/** @type {import('cz-git').UserConfig} */
插入用户路径的文件后缀用 cjs 不太好,用户应该默认 js 的
create-neat
github_2023
others
222
xun082
uaenaTzx
@@ -0,0 +1,26 @@ +module.exports = (generatorAPI) => { + generatorAPI.extendPackage({ + scripts: { + prepare: "husky", + commit: "git-cz", + format: 'prettier --write "src/**/*.{js,jsx,ts,tsx,json,css,scss,md}"', + lint: 'eslint "**/*.{ts,tsx,js,jsx}" --fix',
husky 不应该有 script,就只要 lint-stage 就行了
create-neat
github_2023
others
222
xun082
uaenaTzx
@@ -0,0 +1,26 @@ +module.exports = (generatorAPI) => { + generatorAPI.extendPackage({ + scripts: { + prepare: "husky", + commit: "git-cz", + format: 'prettier --write "src/**/*.{js,jsx,ts,tsx,json,css,scss,md}"', + lint: 'eslint "**/*.{ts,tsx,js,jsx}" --fix', + }, + config: { + commitizen: { + path: "node_modules/cz-git", + }, + }, + "lint-staged": { + "*.{ts,tsx,js,jsx}": ["npm run format", "npm run lint"], + }, + devDependencies: { + husky: "^9.0.11", + "lint-staged": "^15.2.0", + "cz-git": "^1.7.1",
这些依赖也确认一下,像 cz-git 这些,是没必要的功能
create-neat
github_2023
others
203
xun082
IsDyh01
@@ -10,7 +10,7 @@ module.exports = { cacheDirectory: true, cacheCompression: false, presets: [], - // plugins: [require.resolve("react-refresh/babel")].filter(Boolean), + plugins: ["react-refresh/babel"],
这个插件需要在generator/index.cjs里边得依赖写一下吗,安装的时候去下载
create-neat
github_2023
others
201
xun082
IsDyh01
@@ -1,27 +1,66 @@ +// 通用的Babel预设和插件 +const commonBabelPresets = [ + [ + "@babel/preset-env", + { + useBuiltIns: "usage", + corejs: 3, + }, + ], + "@babel/preset-typescript", +]; + +const commonBabelPlugins = [ + "@babel/plugin-transform-runtime", + "@babel/plugin-syntax-dynamic-import", +]; + +// 通用的依赖 +const commonDependencies = { + "core-js": "^3.8.3", +}; + +const commonDevDependencies = { + "@babel/core": "^7.24.7", + "@babel/preset-env": "^7.24.7", + "@babel/plugin-transform-runtime": "^7.24.7", + "babel-loader": "^9.1.3", + "@babel/plugin-syntax-dynamic-import": "^7.8.3", + "@babel/preset-typescript": "^7.24.7", +}; + +// React的Babel配置 +const reactBabelConfig = { + presets: ["@babel/preset-react", ...commonBabelPresets], + plugins: commonBabelPlugins, +}; + +// Vue的Babel配置 +const vueBabelConfig = { + presets: [...commonBabelPresets, "@vue/cli-plugin-babel/preset", "@vue/babel-preset-jsx"], + plugins: ["@vue/babel-plugin-jsx", ...commonBabelPlugins], +}; + module.exports = (generatorAPI) => { + // 扩展package.json配置 generatorAPI.extendPackage({ - // babel 的文件内容↓ - babel: { - presets: ["@babel/preset-env"], - plugins: [ - [ - "@babel/plugin-transform-runtime", - { - corejs: 3, - }, - ], - ], - }, - // package.json 的文件内容↓ - dependencies: { - "core-js": "^3.8.3", + react: { + babel: reactBabelConfig, + dependencies: commonDependencies, + devDependencies: { + ...commonDevDependencies, + "@babel/preset-react": "^7.24.7", + },
这种结构extendPackage方法扩展pkg会有问题
create-neat
github_2023
typescript
182
xun082
uaenaTzx
@@ -31,3 +31,11 @@ export interface PackageJsonType { } export type buildToolType = "webpack" | "vite" | "rollup"; +
昨天说的就是这一块,没必要的
create-neat
github_2023
typescript
186
xun082
uaenaTzx
@@ -186,8 +225,22 @@ class FileTree { */ addToTreeByPath(path: string) { this.fileData.children.push(FileTree.buildFileData(path)); - //根据process.env.isTs更改后缀 - process.env.isTs && this.changeFileExtensionToTs(); + //如果有 ts 插件则更改相关文件后缀 + function handleExt(file: FileData) {
和 73 行重复了,仔细看看
create-neat
github_2023
typescript
190
xun082
xun082
@@ -20,7 +23,11 @@ export async function removeDirectory( */ async function deleteDirectory() { try { - await fs.remove(fullPath); + if (CLIENT_OS === "mac") {
const platform:NodeJS.Platform = process.platform; if(platform==="linux"){ xxx }else{ xxx } 直接在这里不是更间接吗,为什么还要额外封装函数
create-neat
github_2023
typescript
191
xun082
xun082
@@ -163,7 +166,19 @@ export default async function createAppTest(projectName: string, options: Record "README-EN.md": createReadmeString(packageManager, template, "README-EN.md"), }); - createSuccessInfo(projectName, "npm"); + // 添加.gitignore + console.log(chalk.blue(`\n📄 Generating gitignore...`)); + + const buildToolGitignore = createTemplateFile("gitignore"); + const gitignoreFilePath = path.resolve(rootDirectory, ".gitignore");
用resolveApp这个函数来读取路径,在utils包封装有
create-neat
github_2023
typescript
184
xun082
uaenaTzx
@@ -0,0 +1,65 @@ +import fs from "fs"; +import path from "node:path"; +import os from "os"; +import process from "process"; +import chalk from "chalk"; + +import { Preset } from "./preset"; + +/** + * @description 获取用户系统主目录下保存预设的文件路径
@description 按照规范是不需要的,直接说函数作用即可
create-neat
github_2023
others
175
xun082
xun082
@@ -0,0 +1,6 @@ +module.exports = (templateAPI) => { + templateAPI.extendPackage({ + dependencies: {},
添加一下相关的依赖,react这些
create-neat
github_2023
others
176
xun082
uaenaTzx
@@ -0,0 +1,15 @@ + +const PluginConfig = require('./generator/index.cjs') + + +const pluginPrettier = (buildTool)=>{ + +
无用的空行
create-neat
github_2023
others
176
xun082
uaenaTzx
@@ -1,18 +1,22 @@ module.exports = (generatorAPI) => { generatorAPI.extendPackage({ prettier: { - singleQuote: false, - tabWidth: 2, - arrowParens: "always", - bracketSpacing: true, - proseWrap: "preserve", - trailingComma: "all", - jsxSingleQuote: false, - printWidth: 100, + tabWidth: 2, // 每个缩进级别的空格数 + printWidth: 80, // 每行代码的最大长度 + useTabs: false, // 使用空格代替制表符进行缩进 + semi: true, // 在语句末尾添加分号 + singleQuote: true, // 使用单引号代替双引号 + trailingComma: "es5", // 尾随逗号的使用方式(es5 对象、数组等使用) + bracketSpacing: true, // 对象文字中的括号间是否加空格 + arrowParens: "always", // 箭头函数参数使用圆括号 + endOfLine: "lf" // 换行符使用 lf (Unix 风格) }, devDependencies: { "@types/prettier": "^3.0.0",
这个不是必要依赖,得考虑后续在依赖处理中间件再做
create-neat
github_2023
others
179
xun082
uaenaTzx
@@ -0,0 +1,6 @@ +module.exports = (templateAPI) => { + templateAPI.extendPackage({
vue 这些依赖需要加
create-neat
github_2023
others
179
xun082
uaenaTzx
@@ -0,0 +1,12 @@ +module.exports = (templateAPI) => { + templateAPI.extendPackage({ + dependencies: { + vue: "^3.2.47", + }, + devDependencies: { + "vue-template-compiler": "^3.2.47", + "css-loader": "^6.7.3",
为啥要 css 相关的依赖
create-neat
github_2023
typescript
170
xun082
uaenaTzx
@@ -197,6 +198,58 @@ class Generator { } } + // 单独处理一个框架相关文件
这一块不要写死吧,而且和 pluginGenerate 有很大程度的耦合,看看能不能解藕操作一下?
create-neat
github_2023
typescript
170
xun082
xun082
@@ -0,0 +1,136 @@ +import Generator from "./Generator"; +import fs from "fs"; +import path from "path"; + +interface ConfigFileData { + file: Record<string, string[]>; +} + +/** + * 通用类,为 generator 和 template 提供 API + * @param plugin 插件名 + * @param generator 生成器实例 + * @param options 传入的生成器选项 + * @param rootOptions 根目录执行选项 + */ +class BaseAPI { + protected generator: Generator; + protected configFilesData: Record<string, ConfigFileData> = {}; + protected packageData = { dependencies: {}, devDependencies: {}, scripts: {} }; + private dependenciesKeys = ["dependencies", "devDependencies"]; + + constructor(generator: Generator) { + this.generator = generator; + } + + /** + * 添加依赖。 + * @param {string} optionsType - 依赖类型。 + * @param {string} name - 依赖名称。 + * @param {string} [version="latest"] - 依赖版本。 + */ + addDependency(optionsType: string, name: string, version: string = "latest") { + if (this.dependenciesKeys.indexOf(optionsType) != -1) { + this.packageData[optionsType][name] = version; + } + } + + /** + * 删除依赖。 + * @param {string} optionsType - 依赖类型。 + * @param {string} name - 依赖名称。 + */ + removeDependency(optionsType: string, name: string) { + if (this.dependenciesKeys.indexOf(optionsType) != -1) { + delete this.packageData[optionsType][name]; + } + } + + /** + * 扩展项目的 package.json + * @param fields 合并内容 + * @param {object} [options] 操作选项 + */ + extendPackage(fields: object, options: object = {}) {
ts类型尽量别写Object
create-neat
github_2023
typescript
170
xun082
xun082
@@ -0,0 +1,136 @@ +import Generator from "./Generator"; +import fs from "fs"; +import path from "path"; + +interface ConfigFileData { + file: Record<string, string[]>; +} + +/** + * 通用类,为 generator 和 template 提供 API + * @param plugin 插件名 + * @param generator 生成器实例 + * @param options 传入的生成器选项 + * @param rootOptions 根目录执行选项 + */ +class BaseAPI { + protected generator: Generator; + protected configFilesData: Record<string, ConfigFileData> = {}; + protected packageData = { dependencies: {}, devDependencies: {}, scripts: {} }; + private dependenciesKeys = ["dependencies", "devDependencies"]; + + constructor(generator: Generator) { + this.generator = generator; + } + + /** + * 添加依赖。 + * @param {string} optionsType - 依赖类型。 + * @param {string} name - 依赖名称。 + * @param {string} [version="latest"] - 依赖版本。 + */ + addDependency(optionsType: string, name: string, version: string = "latest") { + if (this.dependenciesKeys.indexOf(optionsType) != -1) { + this.packageData[optionsType][name] = version; + } + } + + /** + * 删除依赖。 + * @param {string} optionsType - 依赖类型。 + * @param {string} name - 依赖名称。 + */ + removeDependency(optionsType: string, name: string) { + if (this.dependenciesKeys.indexOf(optionsType) != -1) { + delete this.packageData[optionsType][name]; + } + } + + /** + * 扩展项目的 package.json + * @param fields 合并内容 + * @param {object} [options] 操作选项 + */ + extendPackage(fields: object, options: object = {}) { + // 扩展 package.json + // options 就是一个可扩展对象 + const extendOptions = { + // 是否进行修剪操作 + prune: false, + // 合并字段 + merge: true, + // 是否警告不兼容的版本 + warnIncompatibleVersions: true, + // 是否强制覆盖 + forceOverwrite: false, + // 传入的配置项 + ...options, + }; + // 获取当前项目的package.json + const pkg = this.generator.pkg; + // 将fields合并到package.json中 + for (const key in fields) { + const value = fields[key]; + const existing = pkg[key]; + // 如果merge为false或者key不在package.json中 则直接赋值 + if (!extendOptions.merge || !(key in pkg)) { + pkg[key] = value; + } else if (Array.isArray(value) && Array.isArray(existing)) { + // 如果是数组则合并 且去重 + pkg[key] = existing.concat(value.filter((v) => existing.indexOf(v) < 0)); + } else if (typeof value === "object" && typeof existing === "object") { + // 如果是对象则合并 + pkg[key] = { ...existing, ...value }; + } else { + pkg[key] = value;
对象判断严谨一点,万一是个null呢,用typeof不太严谨
create-neat
github_2023
typescript
165
xun082
uaenaTzx
@@ -0,0 +1,135 @@ +import Generator from "./Generator"; +import fs from 'fs' +import path from 'path'; + +interface ConfigFileData{ + file:Record<string,string[]>; +} + +/** + * @description 通用类,为 generator 和 template 提供 API
@description 去掉,只要说明作用就好了
create-neat
github_2023
typescript
165
xun082
uaenaTzx
@@ -0,0 +1,135 @@ +import Generator from "./Generator"; +import fs from 'fs' +import path from 'path'; + +interface ConfigFileData{ + file:Record<string,string[]>; +} + +/** + * @description 通用类,为 generator 和 template 提供 API + * @param plugin 插件名 + * @param generator 生成器实例 + * @param options 传入的生成器选项 + * @param rootOptions 根目录执行选项 + */ +class BaseAPI{ + protected generator:Generator; + protected configFilesData:Record<string,ConfigFileData>={}; + protected packageData={dependencies:{},devDependencies:{},scripts:{}};
这里看起来没有 prettier 格式化
create-neat
github_2023
typescript
165
xun082
uaenaTzx
@@ -0,0 +1,135 @@ +import Generator from "./Generator"; +import fs from 'fs' +import path from 'path'; + +interface ConfigFileData{ + file:Record<string,string[]>; +} + +/** + * @description 通用类,为 generator 和 template 提供 API + * @param plugin 插件名 + * @param generator 生成器实例 + * @param options 传入的生成器选项 + * @param rootOptions 根目录执行选项 + */ +class BaseAPI{ + protected generator:Generator; + protected configFilesData:Record<string,ConfigFileData>={}; + protected packageData={dependencies:{},devDependencies:{},scripts:{}}; + private dependenciesKeys=["dependencies","devDependencies"]; + + constructor(generator:Generator){ + this.generator=generator; + } + + /** + * @description 添加依赖。 + * @param {string} name - 依赖名称。 + * @param {string} [version="latest"] - 依赖版本。 + */ + addDependency(optionsType:string,name:string,version:string="latest"){ + if(this.dependenciesKeys.indexOf(optionsType)!=-1){ + this.packageData[optionsType][name] = version; + } + } + + /** + * @description 添加脚本。 + * @param {string} name - 脚本名称。 + * @param {string} command - 脚本命令。 + */ + addScript(name:string,command:string){
既然 extendPackage 已经满足了 addScrip 这类的插入,那就不用这样冗余了
create-neat
github_2023
typescript
165
xun082
uaenaTzx
@@ -1,80 +1,15 @@ -import fs from "fs"; -import path from "path"; - +import BaseAPI from "./BaseAPI"; import Generator from "./Generator"; /** * @description 为执行 generator 提供系一列 api - * @param plugin 插件名 - * @param generator 生成器实例 - * @param options 传入的生成器选项 - * @param rootOptions 根目录执行选项 + * @param generator Generator实例 */ -class GeneratorAPI { - private generator: Generator; - +class GeneratorAPI extends BaseAPI{ + constructor(generator: Generator) { - this.generator = generator; - } - - /** - * @description 扩展项目的 package.json 内容 - * @param fields 合并内容 - * @param {object} [options] 操作选项 - */ - extendPackage(fields: object, options: object = {}) { - // 扩展 package.json - // options 就是一个可扩展对象 - const extendOptions = { - // 是否进行修剪操作 - prune: false, - // 合并字段 - merge: true, - // 是否警告不兼容的版本 - warnIncompatibleVersions: true, - // 是否强制覆盖 - forceOverwrite: false, - // 传入的配置项 - ...options, - }; - // 获取当前项目的package.json - const pkgPath = path.resolve(this.generator.getRootDirectory(), "package.json"); - // 获取当前项目的package.json - const pkg = this.generator.pkg; - // 将filds合并到package.json中 - for (const key in fields) { - const value = fields[key]; - const existing = pkg[key]; - // 如果merge为false或者key不在package.json中 则直接赋值 - if (!extendOptions.merge || !(key in pkg)) { - pkg[key] = value; - } else if (Array.isArray(value) && Array.isArray(existing)) { - // 如果是数组则合并 且去重 - pkg[key] = existing.concat(value.filter((v) => existing.indexOf(v) < 0)); - } else if (typeof value === "object" && typeof existing === "object") { - // 如果是对象则合并 - pkg[key] = { ...existing, ...value }; - } else { - pkg[key] = value; - } - } - // 如果prune为true 则删除空字段 - if (extendOptions.prune) { - for (const key in pkg) { - if (pkg[key] === null) { - delete pkg[key]; - } - } - } - // 写入package.json - try { - console.log("explosion", pkg); - fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2)); - } catch (err) { - console.error(`Failed to write package.json: ${err}`); - return; - } + super(generator);
不确定只用 super 能否实现一些特化的内容哈,可以看看是否需要根据 插件和框架 的不同,做一些方法的重写(目前看应该不需要) 如果判断后续都没有特化逻辑,其实现在就不需要统一父类,只留一个类就可以了,这个需要你再看一下
create-neat
github_2023
others
165
xun082
uaenaTzx
@@ -34,6 +34,7 @@ "ts" ], "dependencies": { + "@angular/cli": "^15.2.11",
为啥需要这个包
create-neat
github_2023
typescript
165
xun082
uaenaTzx
@@ -110,7 +116,7 @@ async function loadModule(modulePath: string, rootDirectory: string) { class Generator { private rootDirectory: string; private plugins: Record<string, any>; - private files: FileTree; // 键:文件名,值:文件内容 + private files: Record<string, string> = {}; // 键:文件名,值:文件内容
明显是合并出现问题了, private files: FileTree 才是更新的内容
create-neat
github_2023
typescript
177
xun082
uaenaTzx
@@ -105,6 +106,15 @@ export default async function createAppTest(projectName: string, options: Record sourceType: "module", }); + // 根据构建工具为 package.json 新增不同的依赖 + + if (buildTool === "webpack") {
可以写个抽象一点的?webpack、vite……
create-neat
github_2023
typescript
177
xun082
uaenaTzx
@@ -29,3 +29,5 @@ export interface PackageJsonType { config?: { [key: string]: any }; "lint-staged"?: { [globPattern: string]: string | string[] }; } + +export type buildToolType = "webpack" | "vite" | "rollup";
这个直接根据预设的构建工具的值消费就好了,不用额外搞个 Type 吧
create-neat
github_2023
others
172
xun082
uaenaTzx
@@ -0,0 +1,76 @@ +import "./App.css"; + +function App() {
应该参考 test 这个模版: ![image](https://github.com/xun082/create-neat/assets/104181441/dad68a37-95d9-49c0-b110-2e3e3ddf9885) 文件结构参照这个来
create-neat
github_2023
others
172
xun082
uaenaTzx
@@ -0,0 +1,76 @@ +import "./App.css"; + +function App() { + return (
文件格式不用 ejs,按照原本的 jsx、css 来就可以了 我理解格式: index.css index.jsx