Modify objects in ES6 source code by webpack/babel

不羁岁月 提交于 2019-12-25 08:46:53

问题


There is ES6-application which is bundled with webpack and babel plugins. Is it possible to modify some source code, to inject hidden field in every object?

Some babel/webpack plugins, including webpack-replace-plugin and babel-minify-replace, allows to interop field accessing and create some macro-definitions

But problem is wrap all object creation, and insert some field with unique name. It should be everywhere - in object creation literals, in rest-spread copy and so on, so naïve replace by regular expression is not solution.

Original code:

const obj1 = { aaa:10, bbb:20  };
const obj2 = new Object();
const obj3 = { ...obj1, ddd: 20 };
const arr = [1, 2, 3];
const str = new String("ABC");

Transformed code:

const obj1 = { aaa:10, bbb:20, SECRET_PROPERTY: true  };
const obj2 = new Object(); obj2.SECRET_PROPERTY = true;
const obj3 = { ...obj1, ddd: 20, SECRET_PROPERTY: true };
const arr = [1, 2, 3]; arr.SECRET_PROPERTY = true;
const str = new String("ABC"); str.SECRET_PROPERTY = true;

Of course, such operation will decrease optimization of original code, and it's required only for debug/development mode.

Update: Have found babel plugin, which has closest functionality for original task - https://github.com/JonAbrams/elsa . It perform different task, but can easily adapted for original task


回答1:


Task had been solved by manually writing babel plugin, which performs prior modification of source code, and inject meta-information for each live object, including original file name, line and columns in that file, and string representation of object declaration

Plugin is provided as function on gist: https://gist.github.com/IhostVlad/9310188edbdbc9f62dc3107417cc8fe4

Typical usage with webpack is following

if(process.env.NODE_ENV !== 'production') {
    webpackServerConfig.module.rules.forEach(rule =>
        rule.loaders.filter(({ loader }) => loader === 'babel-loader').forEach(
            loader =>
                (loader.query.presets = [
                    {
                        plugins: [babelPluginObjectSource]
                    }
                ].concat(Array.isArray(loader.query.presets) ? loader.query.presets : []))
        )
    );
}

Where webpackServerConfig is original webpack config for production mode, and babelPluginObjectSource is imported referred above babel-plugin

Then is runtime meta-information for each object obj from client code will be available via obj.__SOURCE_DELCARATION__ property



来源:https://stackoverflow.com/questions/46725120/modify-objects-in-es6-source-code-by-webpack-babel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!