使用 babel 7 忽略函数外的 return

Ignore return outside of function with babel 7

我最近更新到 babel 7 和 webpack 4,当 运行 我们的 gulp 构建任务时收到此错误:

gulp build
[00:26:04] Requiring external module @babel/register
[91m[BABEL] Note: The code generator has deoptimised the styling of /node_modules/lodash/lodash.js as it exceeds the max of 500KB.
[0m[91m/node_modules/@babel/core/lib/parser/index.js:95
    throw err;
    ^

SyntaxError: /node_modules/dev-ip/lib/dev-ip.js: 'return' outside of function (41:8)

  39 |     var out = getIp();
  40 |     if (!out.length) {
> 41 |         return console.log(messages.error);
     |         ^
  42 |     }
  43 |     console.log(getIp("cli"));
  44 | }
    at Parser.raise (/node_modules/@babel/parser/src/parser/location.js:41:63)
    at Parser.parseReturnStatement (/node_modules/@babel/parser/src/parser/statement.js:577:12)
    at Parser.parseStatementContent (/node_modules/@babel/parser/src/parser/statement.js:199:21)
    at Parser.parseStatement (/node_modules/@babel/parser/src/parser/statement.js:146:17)
    at Parser.parseBlockOrModuleBlockBody (/node_modules/@babel/parser/src/parser/statement.js:865:25)
    at Parser.parseBlockBody (/node_modules/@babel/parser/src/parser/statement.js:841:10)
    at Parser.parseBlock (/node_modules/@babel/parser/src/parser/statement.js:818:10)
    at Parser.parseStatementContent (/node_modules/@babel/parser/src/parser/statement.js:223:21)
    at Parser.parseStatement (/node_modules/@babel/parser/src/parser/statement.js:146:17)
    at Parser.parseIfStatement (/node_modules/@babel/parser/src/parser/statement.js:570:28)
[0m[91merror Command failed with exit code 1.

这是由浏览器同步 dev-ip 依赖项中的函数外部 return 引起的。

有没有办法配置我的 .babelrc 文件来忽略这个?

我试过以下方法:

  1. 仅安装生产依赖项,但由于浏览器同步已导入到我的 gulp 文件中,因此仍在编译中
  2. 正在使用 yarn 设置工作区,但与 #1 类似的问题
  3. 在我的 gulp 文件中动态导入浏览器同步,我想这还不支持吗?
  4. 告诉 babel 忽略或排除编译 node_modules 文件夹,但这似乎没有任何作用?

显然 babel-parser 有一个选项 allowReturnOutsideFunction: true,但我不知道如何在我的 .babelrc 文件中设置它。

关于如何解决这个问题有什么想法吗?

因为我找不到解决这个问题的方法,所以我最终只分叉了 browser-sync 和 dev-ip。

我给你,browser-stink

使用 Babel7,您可以提供所有 parser options (which include allowReturnOutsideFunction) via parserOpts,例如:

// .babelrc.js
module.exports = {
  parserOpts: { allowReturnOutsideFunction: true }
};