美文网首页
使用babel编译自定义代码

使用babel编译自定义代码

作者: DXYang | 来源:发表于2020-12-01 19:40 被阅读0次

    需求

    界面组件支持事件自定义,自定义事件通过代码编辑器输入。

    参考

    https://github.com/babel/sandboxes

    Demo代码

    import React, { useState } from 'react';
    import * as Babel from '@babel/core';
    
    export function compileModule(code: string, globals = {}) {
      const exports = {};
      const module = { exports };
      const globalNames = Object.keys(globals);
      const keys = ['module', 'exports', ...globalNames];
      const values = [module, exports, ...globalNames.map(key => globals[key])];
      // eslint-disable-next-line no-new-func
      new Function(keys.join(), code).apply(exports, values);
      return module.exports;
    }
    
    export function transpilePlugin(pluginString: string) {
      return Babel.transform(pluginString, {
        babelrc: false,
        configFile: false,
        ast: false,
        highlightCode: false,
        presets: [require('@babel/preset-env')],
      }).code;
    }
    
    export default () => {
    
    // 模拟编辑器输入的代码
      const FUNCTION = `function sumFunction(babel) {
        const a = 1;
        const b= 2;
        return a+b;
      }
    
      const data = {
        name:'1',
        age:12
      }
    
      function sumFunction2(x, y) {
        return x+y+data.age;
      }
      export {sumFunction, data, sumFunction2};
      `;
    
      const selfModule = compileModule(transpilePlugin(FUNCTION));
      const {sumFunction, sumFunction2 , data} = selfModule;
    
      return (
        <div>
          {code}
          <br />
          {sumFunction()}
          <br />
          {sumFunction2(2,4)}
        </div>
      );
    };
    
    

    相关文章

      网友评论

          本文标题:使用babel编译自定义代码

          本文链接:https://www.haomeiwen.com/subject/sntewktx.html