Created
May 20, 2020 03:44
-
-
Save eightHundreds/1de06102c32142eacbfdcd6203698b6f to your computer and use it in GitHub Desktop.
jscodeshift工具方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const j = require('jscodeshift') | |
/** | |
* 为代码插入import语句,只能处理import不能处理require,只能插入import语句,其他代码会被忽略 | |
* @param {*} source | |
* @param {*} imports | |
* @copyright 抄自vue-cli/packages/@vue/cli/lib/util/codemods/injectImports.js | |
*/ | |
module.exports.injectImports = function(source, imports) { | |
const root = j(source) | |
const toImportAST = i => j(`${i}\n`).nodes()[0].program.body[0] // 只取第一个语句,一般是Import | |
const toImportHash = node => JSON.stringify({ | |
specifiers: node.specifiers.map(s => s.local.name), | |
source: node.source.raw, | |
}) | |
const declarations = root.find(j.ImportDeclaration) | |
const importSet = new Set(declarations.nodes().map(toImportHash)) | |
const nonDuplicates = node => !importSet.has(toImportHash(node)) | |
const importASTNodes = imports.map(toImportAST).filter(nonDuplicates) | |
if (declarations.length) { | |
declarations | |
.at(-1) | |
// 防止插入后前面多一个空行 | |
.forEach(({ node }) => delete node.loc) | |
.insertAfter(importASTNodes) | |
} else { | |
// no pre-existing import declarations | |
root.get().node.program.body.unshift(...importASTNodes) | |
} | |
return root.toSource() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment