ES6 Generator functions cause error: Uncaught ReferenceError: regeneratorRuntime is not defined

ES6 Generator functions cause error: Uncaught ReferenceError: regeneratorRuntime is not defined

如果我把生成器函数放在

function* someWords() {
  yield "hello";
  yield "world";
}

for (var word of someWords()) {
  alert(word);
}

在 app.js 中,代码产生未捕获的引用错误。

如果我 运行 在我 app.html.eex 的脚本标记中使用相同的代码,它 运行 没问题。

app.html.eex中的代码不会通过babel传递。如果您使用的是支持生成器的浏览器,那么它们就可以工作。

因为你的 app.js 代码是用 babel 转译的,你可能需要使用 https://babeljs.io/docs/usage/polyfill/ 来让生成器工作。


app.js

import "phoenix_html"
import "babel-polyfill"

function* someWords() {
  yield "hello";
  yield "world";
}

for (var word of someWords()) {
  alert(word);
}

brunch_config.js

exports.config = {
  files: {
    javascripts: {
      joinTo: "js/app.js"
    },
    stylesheets: {
      joinTo: "css/app.css"
    },
    templates: {
      joinTo: "js/app.js"
    }
  },

  conventions: {
    assets: /^(web\/static\/assets)/
  },

  paths: {
    watched: [
      "web/static",
      "test/static"
    ],

    public: "priv/static"
  },

  plugins: {
    babel: {
      // Do not use ES6 compiler in vendor code
      ignore: [/web\/static\/vendor/]
    }
  },

  modules: {
    autoRequire: {
      "js/app.js": ["web/static/js/app"]
    }
  },

  npm: {
    enabled: true,
    whitelist: ["phoenix", "phoenix_html", "babel-polyfill"]
  }
};

package.json

{
  "repository": {},
  "dependencies": {
    "babel-brunch": "^6.0.0",
    "babel-polyfill": "^6.3.14",
    "brunch": "^2.1.3",
    "clean-css-brunch": ">= 1.0 < 1.8",
    "css-brunch": ">= 1.0 < 1.8",
    "javascript-brunch": ">= 1.0 < 1.8",
    "phoenix": "file:deps/phoenix",
    "phoenix_html": "file:deps/phoenix_html",
    "uglify-js-brunch": ">= 1.0 < 1.8"
  }
}