我们使用多个汇总插件将其输入解析为 AST。由于它们在相同的文件上运行,因此每个文件都会被解析多次。是否可以对此进行优化,以便每个文件仅解析一次?最小的例子:
\n// rollup.config.js\nimport {createFilter}\xc2\xa0from \'@rollup/pluginutils\';\nimport {simple} from \'acorn-walk\';\nimport {attachComments}\xc2\xa0from \'astravel\';\nimport {generate} from \'astring\';\n\nexport default {\n input: \'src/main.js\',\n output: {file: \'bundle.js\', format: \'cjs\'},\n plugins: [{\n name: \'plugin1\',\n transform(code, id) {\n const comments = [];\n const ast = this.parse(code, {onComment: comments});\n attachComments(ast, comments);\n simple(ast, {\n Identifier(n) {\n // rewrite wrong to right\n if (n.name === \'wrong\') n.name = \'right\';\n }\n });\n\n return {\n code: generate(ast, {comments: true}),\n ast,\n map: null /* minimal example, won\'t create a source map here */\n }; \n }\n }, {\n name: \'plugin2\',\n transform(code, id) {\n const comments = [];\n const ast = this.parse(code, {onComment: comments});\n attachComments(ast, comments);\n simple(ast, {\n CallExpression(n) {\n // rewrite mylog(...) to console.log(...)\n if (n.callee.type === \'Identifier\' && n.callee.name === \'mylog\') {\n n.callee = {\n type: \'MemberExpression\',\n object: {type: \'Identifier\', name: \'console\', start: n.start, end: n.end},\n property: {type: \'Identifier\', name: \'log\', start: n.start, end: n.end},\n computed: false,\n start: n.start,\n end: n.end\n }\n }\n }\n });\n\n return {\n code: generate(ast, {comments: true}),\n ast,\n map: null /* minimal example, won\'t create a source map here */\n }; \n }\n }]\n};\nRun Code Online (Sandbox Code Playgroud)\n现在我明白transform()可以返回 AST,这样解析就不必发生两次。据我了解,它this.parse()使用 rollup-internal acorn 实例。我简单的想法是,如果可用的话,this.parse()可以返回之前调用创建的 AST transform()。但我假设各种各样的恶魔在那条路上等待着,例如当this.parse()被召唤时有不同的选择。
有其他方法可以实现我所描述的吗?也许是一个不同的钩子?
\n我不想将所有插件集中在一个插件中,并通过选项打开和关闭它们(我认为这将是一种解决方案,但确实很麻烦)。
\n| 归档时间: |
|
| 查看次数: |
860 次 |
| 最近记录: |