Using async/await with babel - require(“babel-polyfill”) line not at the top in built file

后端 未结 3 1771
予麋鹿
予麋鹿 2021-01-18 11:43

I am trying to use ES2017 async/await syntax with Babel. In package.json, I have

\"babel\": {
    \"plugins\": [
      \"babel-plugin-transform         


        
相关标签:
3条回答
  • 2021-01-18 12:31

    I think that the require() call must come before the async function (and since functions are hoisted, and you set them up in the same file, the polyfill is loaded later).

    Try to require('babel-polyfill') in an earlier stage in the module system. Something like this:

    // A.js
    require('babel-polyfill');
    const foo = require('./B.js');
    
    foo().then(console.log);
    
    // B.js
    async function foo() {
      return 10;
    }
    
    module.exports.foo = foo;
    
    0 讨论(0)
  • 2021-01-18 12:31

    A different, and probably better solution would be to modularise your code:

    • add an index.js which only exports the stuff you want to export and includes the polyfill
    • add the real functions to small files that only do one thing
    0 讨论(0)
  • 2021-01-18 12:36

    Since functions defined such as

    async function foo() {
        return 10;
    }
    

    can be used before they're defined in javascript, Babel is moving it to the top of the file during transpilation.

    To work around this, this try adjusting your syntax if possible:

    const foo = async function() {
        return 10;
    }
    
    0 讨论(0)
提交回复
热议问题