使用babel-standalone 让浏览器支持es6特性

babel-standalone 是一个可以在浏览器端运行babel 编译的工具,同时官方也说明了一些使用场景(需要进行实时编译的)

使用

使用比较简单,就是添加依赖

  • 参考
<div id="output"></div>
<!-- Load Babel -->
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<!-- Your custom script here -->
<script type="text/babel">
const getMessage = () => "Hello World";
document.getElementById('output').innerHTML = getMessage();
</script>

支持import 以及export 的hack 模式

因为babel 主要是编译,所以requie 以及exports 是不支持的,会提示undefined,解决方法,就是hack 的模式

  • 参考demo
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>babel learning</title>
</head>
<body>
    <div id="output"></div>
    <script src="https://unpkg.com/core-js-bundle@3.8.2/index.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script>
        const content = {
            userapp:`
                export default  {
                name:"dalong",
                age:333
            }
            `,
            userapp2:`
                export default  {
                name:"dalong",
                age:333,
                type:"v1"
            }
            `,
            platform:`
            import app  from 'userapp';
            import app2  from 'userapp2';
           JSON.stringify({app,app2})
            `
        }
        //  hack for exports && require
        window.exports = window;
        window.require=function require (module) {
            var output = Babel.transform(content[module], { presets: ['env'] }).code;
            console.log(output);
            return eval(output)
        }
        const getMessage = () => require("platform")
        var getMessage2 = function() { 
            return window.require("platform")
        }
        document.getElementById('output').innerHTML = getMessage2();
    </script>
</body>
</html>
  • 代码说明
    一以上基于了json 对象存储了需要的es6 模块,platform 作为入口,依赖了其他两个模块userapp,userapp2
    通过import 模式引入了userapp,userapp2,同时通过JSON 反序列化输出,为了方便使用,自己包装了exports
    以及require的hack,exports比较简单,直接导出就可以了,require 处集成了babel 的编译能力(注意很简单
    没有进行cache,实际最好进行cache,可以减少编译时间),代码部分使用了eval 进行执行(会有安全风险)
  • 运行效果

说明

基于babel 的浏览器能力,我们可以自己搞一个web es6 运行环境

参考资料

https://babeljs.io/docs/en/babel-standalone.html

原文地址:https://www.cnblogs.com/rongfengliang/p/14237980.html