【问题标题】:Unexpected mix of '||' and '&&' when using babel'||' 的意外混合和 '&&' 使用 babel 时
【发布时间】:2019-10-26 23:24:05
【问题描述】:

我正在尝试构建一个包并将其发布到npm,并且我正在使用 babel。但是当它的构建时,它向我显示了这个警告:

第 1 行:在严格的模块中不需要“使用严格”

第 23 行:“||”的意外混合和 '&&' 非混合运算符

这是我的方法:

function required(value) {
  if (
    value === null ||
    value === undefined ||
    ("string" === typeof value && value.trim().length === 0) ||
    value.length === 0
  )
    return false;
  return true;
}

这是它的转换方式:

function required(value) {
  if (value === null || value === undefined || "string" === typeof value && value.trim().length === 0 || value.length === 0) return false;
  return true;
}

我将在 "string" === typeof value && value.trim().length === 0 中删除 (),并在每个 if else 块中执行此操作

这是我的babel.config.js

module.exports = function(api){
    api.cache(true);

    const presets = [ "@babel/preset-env", "@babel/preset-react" ];
    const plugins = [ ];

    return {
        presets,
        plugins
    };
}

这是我的package.json:

{
  "scripts": {
    "prepublishOnly": "babel ./src --out-dir ./dist -s inline"
  },
  "devDependencies": {
    "@babel/cli": "^7.4.4",
    "@babel/core": "^7.4.5",
    "@babel/preset-env": "^7.4.5",
    "@babel/preset-react": "^7.0.0",
    "moment": "^2.24.0",
    "react-dom": "^16.8.6"
  },
  "dependencies": {},
  "peerDependencies": {
    "react": "^16.8.6"
  },
  "files": [
    "dist/*"
  ]
}

【问题讨论】:

  • 你建设得怎么样?什么 linter 写了这些警告?
  • 该消息可能来自ESLint。问题是你为什么要检查编译的文件?我预计会有更多错误,因为它们不需要符合编码标准,只要语义正确。
  • @VLAZ 为什么会出现更多错误?
  • @ErtanHasani 正如我所说,编译后的输出不需要符合编码准则,Babel 只会编译成在语义上与输入代码相同的东西。一旦这样做,它可能会生成不符合 linter 规则的代码,您不应该期待其他情况,但确实假设它会吐出不符合要求的代码。
  • @VLAZ 哦,好的,我现在明白了。谢谢!

标签: javascript reactjs npm babeljs


【解决方案1】:

Babel 就在这里:不需要括号,因为operator precedence&& 的优先级高于||

linter 说这段代码不可读是正确的。

但是 Babel 的输出并不适合你的人眼或 linter,而是用于浏览器。

不要对 Babel 的输出进行 lint。该错误在您的构建链中。

旁注:你可以替换

if (a) return false;
return true;

return !a;

【讨论】:

  • "不要对 Babel 的输出进行 lint。错误在你的构建链中。"是的,这听起来像是一个有效的观点?谢谢你,我意识到我可能把一些事情搞砸了^^
猜你喜欢
  • 2020-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-15
  • 2016-02-23
  • 2016-02-16
  • 2013-05-25
相关资源
最近更新 更多