进口
你为什么不改变你图书馆的imports呢?在node_modules 中修补文件看起来像是一种黑客攻击。如果您需要其他一些导出,您可以编写一个新库,仅重新导出您需要的内容。此外,您想要实现的想法使用这样的结构变得更加困难:
export * from './api.js';
您需要遍历所有文件中的所有导出。
如果您与CommonJS,它可以动态地export事物:
buildSomeApiExports();
function buildSomeExports() {
module.exports = {};
}
而且这段代码是正确的,而且由于它的动态特性,这对于统计分析来说确实是一项艰巨的任务ESLint插入。
如果您将使用您的应用程序的imports,您可以使用我正在研究的?Putout 代码转换器,它可以看起来this way:
export const replace = () => ({
'import {old} from "old-library"': 'import {newOne} from "new-library"',
});
这是Replacer,但您可以使用other plugin types 获得更复杂的示例。
出口
如果你想解析导出,这里是more sophisticated example。
输入:
const start = '';
/*
*/
module.exports = () => {};
module.exports.readFile = () => {};
export const writeFile = () => {};
export default () => {};
export * from './abc.js';
可以处理:
export const fix = (path) => {
const {body} = path.scope.getProgramParent().path.node;
const comment = body[0].trailingComments[0];
if (path.isAssignmentExpression())
comment.value += ` CommonJS: ${path.get('left.property')}\n`;
if (path.isExportNamedDeclaration())
comment.value += ` ESM: ${path.get('declaration.declarations.0.id')}\n`;
if (path.isExportDefaultDeclaration())
comment.value += ` ESM: default\n`;
if (path.isExportAllDeclaration())
comment.value += ` ESM: parse: ${path.node.source.value}\n`;
};
export const include = () => [
'module.exports = __a',
'module.exports.__a = __b',
'export default __a',
'export const __a = __b',
'export * from "__"',
];
这是结果:
const start = '';
/*
CommonJS: exports
CommonJS: readFile
ESM: writeFile
ESM: default
ESM: parse: ./abc.js
*/
module.exports = () => {};
module.exports.readFile = () => {};
export const writeFile = () => {};
export default () => {};
export * from './abc.js';
你可以使用eslint-plugin-putout 运行它,或者使用?扑灭directly 在你的 ESLint 插件代码中