【小程序】 解决 Function(...) is not a function问题

前言

  • 在小程序中,只要写了aync await(或者是你引入的库中写了),如果你使用了babel编译且babel的版本大于7,则会出现这个问题。

原因

  • 小程序中会禁用一些动态写法,在babel/runtime中引入的index.js中写了这么一段:
// TODO(Babel 8): Remove this file.

var runtime = require("../helpers/regeneratorRuntime")();
module.exports = runtime;

// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=
try {
    
    
  regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
    
    
  if (typeof globalThis === "object") {
    
    
    globalThis.regeneratorRuntime = runtime;
  } else {
    
    
  Function("r", "regeneratorRuntime = r")(runtime);
  }
}
  • 这里会走到Function("r", "regeneratorRuntime = r")(runtime);中,小程序不支持该语法,但是浏览器支持,可以在小程序控制台中测试一下。

解决

  • 解决方法很多,一般来说,我们需要使用regenerator-runtime的0.11.0版本,对babel/runtime打个补丁包,去了不合法语法,加上require('regenerator-runtime'),另外,需要配置别名:
  alias: {
    
    
    'regenerator-runtime': path.resolve('./node_modules', 'regenerator-runtime'),
  },
  • 此时即可正常。

猜你喜欢

转载自blog.csdn.net/yehuozhili/article/details/125925470