Node.js开发:在JS文件最后import语句后插入新导入遇阻
在Node.js CLI工具中给JS文件最后一条import后插入新导入语句
你遇到的document is undefined错误核心原因是:document是浏览器环境的DOM API,Node.js(CLI工具的运行环境)中不存在这个对象,操作本地文件必须使用Node.js内置的fs模块来完成读写操作。
以下是修正后的完整实现代码,适配你的CLI工具场景:
const fs = require('fs').promises; const path = require('path'); updateResourceType: async function(answers) { logger.info(`INFO: Adding the new component to the resoruceType.js file`); // 字符串插入辅助方法 String.prototype.splice = function(index, rem, str) { return this.slice(0, index) + str + this.slice(index + Math.abs(rem)); }; try { // 1. 构建目标文件的完整路径 const filePath = path.join(process.cwd(), process.env.reactRepo, process.env.resourceTypeFile); // 2. 异步读取文件内容 let fileContent = await fs.readFile(filePath, 'utf8'); // 3. 定位最后一条import语句的结束位置 const lastImportStart = fileContent.lastIndexOf('\nimport '); if (lastImportStart === -1) { // 边界情况:文件中无import语句,直接插入到文件开头 const newImport = `import ${answers.componentName} from './components/global/${answers.componentName}/${answers.componentName}';\n`; fileContent = newImport + fileContent; } else { // 找到最后一条import行的下一个换行符,插入到该行的下一行 const nextNewLine = fileContent.indexOf('\n', lastImportStart + 1); const insertPosition = nextNewLine === -1 ? fileContent.length : nextNewLine + 1; const newImport = `import ${answers.componentName} from './components/global/${answers.componentName}/${answers.componentName}';\n`; fileContent = fileContent.splice(insertPosition, 0, newImport); } // 4. 将修改后的内容写回文件 await fs.writeFile(filePath, fileContent, 'utf8'); logger.success(`SUCCESS: Finished adding new import to the resoruceType.js file`); } catch (error) { logger.error(`ERROR: Failed to update file - ${error.message}`); throw error; } }
关键细节说明
- 文件读写逻辑:使用
fs.promises提供的异步方法,适配你代码中的async函数上下文,避免阻塞CLI工具的运行。 - 边界情况处理:考虑了文件中没有任何import语句的场景,确保代码鲁棒性。
- 语法修正:给导入路径添加了单引号,符合ES模块导入的语法要求。
- 错误捕获:通过
try/catch处理文件读写时可能出现的异常(如文件不存在、权限不足等)。
如果需要同步操作(不推荐在异步函数中使用,但特殊场景下可选择),可以替换为fs.readFileSync和fs.writeFileSync,逻辑与上述代码一致,仅需移除await关键字。
内容的提问来源于stack exchange,提问作者TimLavelle
相关产品推荐
相关产品推荐

