Webpack插件使用asm更改内容

时间:2018-11-13 08:12:35

标签: javascript webpack webpack-4

问题

嗨,我正在尝试编写一个插件,并使用ast来解析文件。但是我无法更改代码。例如,此代码不会将div更改为label。更改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';
              }
            }
          }
        }
      });
    });
  });
}`

我只需要将div更改为return块中的标签或将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>
  );
};

也许有人可以提供一个小的示例,以通过webpack插件中的抽象语法树更改某些内容。

1 个答案:

答案 0 :(得分:3)

正如评论中提到的,并在this question中的webpack代码中指出,webpack忽略了在点击中更改解析器AST的尝试。

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

基于i18n-lang和Define Plugins,使用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;

解析器提供的ast在不同的加载器和输入更改的情况下可能会有很大的不同。