Webpack 插件使用 asm 更改内容

And*_*lov 4 javascript webpack webpack-4

问题

嗨,我正在尝试编写一个插件并使用 ast 来解析文件。但我无法对代码进行更改。例如,此代码不会将 div 更改为标签。更改 ast 的正确方法是什么?

    apply(compiler) {
      compiler.hooks.normalModuleFactory.tap('MyPlugin', (factory) => {
        factory.hooks.parser.for('javascript/auto').tap('MyPlugin', (parser, options) => {
          parser.hooks.program.tap('MyPlugin', (ast, comments) => {

            if (parser.state &&
                parser.state.module &&
                parser.state.module.resource.indexOf('node_modules') === -1) {

            if (parser.state.module.resource.endsWith('tsx')) {
                var g = ast.body.filter(n=> n.type === 'ExportNamedDeclaration');

            for (let a of g) {
              var decl = a.declaration.declarations;

              if (decl && decl[0]) {
                decl[0].init.body.body[0].argument.arguments[0].raw = 'label';
                decl[0].init.body.body[0].argument.arguments[0].value = 'label';
              }
            }
          }
        }
      });
    });
  });
}`
Run Code Online (Sandbox Code Playgroud)

我只需要在返回块中将 div 更改为标签或将 data-attr 添加到 div。我不想使用正则表达式并替换所有文件内容,我想用 ast 制作它。MyComponent.tsx 可以如下:

import * as React from 'react';
import * as style from './MyComponent.css';

export const MyComponent = (props) => {
  return (
    <div className={style['test']}>bla bla</div>
  );
};
Run Code Online (Sandbox Code Playgroud)

可能有人可以提供小例子来改变 webpack 插件中的抽象语法树。

los*_*der 5

正如评论中提到的,并在这个问题的 webpack 代码中指出,webpack 会忽略在点击中更改解析器 AST 的尝试。

插件应该使用 ast 作为只读映射来在依赖图中构建新的依赖关系。(这对于排序和并行执行来说不那么脆弱,因为多个插件可以添加到依赖图中,而不会通过更改引用 AST 使彼此无效。)

基于i18n-lang和定义插件,使用 ast 为转换构建依赖项的示例可能如下所示:

"use strict";
const pluginName = 'MyPlugin';
const NullFactory = require('webpack/lib/NullFactory');
const ConstDependency = require("webpack/lib/dependencies/ConstDependency");

class MyPlugin {

    apply(compiler) {

        compiler.hooks.compilation.tap(
            "MyPlugin",
            (compilation, { normalModuleFactory }) => {
                compilation.dependencyFactories.set(ConstDependency, new NullFactory());
                compilation.dependencyTemplates.set(
                    ConstDependency,
                    new ConstDependency.Template()
                );
            });


        compiler.hooks.normalModuleFactory.tap('MyPlugin', (factory) => {
            factory.hooks.parser.for('javascript/auto').tap('MyPlugin', (parser, options) => {
                parser.hooks.program.tap('MyPlugin', (ast, comments) => {

                    if (parser.state &&
                        parser.state.module &&
                        parser.state.module.resource.indexOf('node_modules') === -1) {

                        if (parser.state.module.resource.endsWith('tsx')) {
                            var g = ast.body.map(n => {
                                try {
                                    let {expression:{left:{property:{name:my}}, right:{body:{body:[{argument:{arguments:[div]}}]}}}} = n
                                    return my == 'MyComponent' && div.value == 'div' ? div: false 
                                } catch(e) {
                                  return false;
                                }
                            }).filter(e=>e);
                            for (let div of g) {
                                let dep = new ConstDependency(JSON.stringify('label'), div.range);
                                    dep.loc = div.loc;
                                    parser.state.current.addDependency(dep);
                            }
                        }
                    }
                });
            });
        });
    }
}

module.exports= MyPlugin;
Run Code Online (Sandbox Code Playgroud)

其中ast由解析器提供可变化相当多的不同的装载机和变化到输入端。

  • 谢谢你,这对我帮助很大! (2认同)