账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    @babel/plugin-transform-runtime 能否不要在编译后的文件中单独使用 import 引入 呢?
    38
    0

    @babel/plugin-transform-runtime 能否不要在编译后的文件中单独使用 import 引入 呢?

    场景

    使用 babel-cli 对传统前端中的 js 文件进行编译,然而在吾辈引入了 @babel/plugin-transform-runtime 插件后却发现编译后的 js 文件顶部使用 import 引入了 helpers 中的函数,问题是吾辈不可能使用模块化,所以有什么解决方案么?

    babel 配置

    {
      "presets": [
        [
          "@babel/preset-env",
          {
            "modules": false
          }
        ]
      ],
      "plugins": [
        "@babel/plugin-proposal-class-properties",
        "@babel/plugin-transform-runtime"
      ]
    }

    源代码

    /**
     * 公共的 JavaScript 代码片段
     * @author rxliuli
     */
    const global = new class Global {
    }()

    编译后的代码

    import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
    
    /**
     * 公共的 JavaScript 代码片段
     * @author rxliuli
     */
    var global = new function Global() {
      _classCallCheck(this, Global);
    }();

    吾辈不想在源文件中使用 import 引入函数,而更想要在公共的 html 头文件中使用 script 引入 helpers 下面用到的函数,有什么解决方法么?

    理想的效果

    全局引入 js 文件

    <!doctype html>
    <html
      lang="zh-CN"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
    >
    <body>
        <!--全局引入帮助函数 js 文件-->
        <script src="/static/js/lib/babel/babel-runtime.min.js"></script>
    </body>
    </html>

    编译后的代码

    /**
     * 公共的 JavaScript 代码片段
     * @author rxliuli
     */
    var global = new function Global() {
      _classCallCheck(this, Global);
    }();
    1
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 10 元积分
        全部回答
    • 0
    • 最独立的小人物° 普通会员 1楼

      是的,@babel/plugin-transform-runtime 可以在编译后的文件中不单独使用 import 引入,因为它是用于处理运行时的导入。当运行时导入代码时,它会自动转译为 CommonJS 或 ES6 的语法,因此不需要使用 import 或 export。

      例如,如果你在你的组件中使用了 import,但你知道你的组件将在生产环境中运行,那么你可以直接在组件的代码中使用 import,而不是在编译后使用。在生产环境中,编译后的文件会被当作一个 JavaScript 函数调用,因此不需要使用 import。

      另外,如果你的项目使用了 CommonJS 或 ES6 的语法,那么你可以直接在运行时导入,而不需要在编译后使用。这是因为 CommonJS 或 ES6 的语法已经被编译成运行时的代码,因此不需要使用 import。

      因此,@babel/plugin-transform-runtime 可以在编译后的文件中不单独使用 import 引入。

    更多回答
    网站公告
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部