本文共 1837 字,大约阅读时间需要 6 分钟。
I write JavaScript without semicolons.
我写JavaScript没有分号。
And I really like that. The language is cleaner, in my opinion.
我真的很喜欢。 我认为这门语言比较干净。
You might not like that, and it’s understandable. But that’s the way it is.
您可能不喜欢它,这是可以理解的。 但这就是事实。
Semicolons are optional. We are not required to add them.
分号是可选的。 我们不需要添加它们。
Sometimes, however, we must pay attention. In particular, in Node.js we use require()
to load external modules and files.
但是,有时我们必须注意。 特别是在Node.js中,我们使用require()
加载外部模块和文件。
This can cause, in some cases, an error like this:
在某些情况下,这可能会导致如下错误:
TypeError: require(...) is not a function
That’s a weird error, right?
那是一个奇怪的错误,对吧?
Let’s look at how I got it.
让我们看看我是怎么得到的。
I required a library, and then I had to run some code at the root level and I created an immediately-invoked async function:
我需要一个库,然后我必须在根级别运行一些代码,然后创建了一个立即调用的异步函数:
const fs = require('fs')(async () => { //...})()
JS does not see a semicolon after require(), and we start a line with a (
, and JS thinks we’re trying to execute a function.
JS在require()之后看不到分号,我们以(
开头,而JS认为我们正在尝试执行一个函数。
It consider require('fs')
as the name of the function, which is something that could actually work if the module export returned a function.
它将require('fs')
作为函数的名称,如果模块导出返回函数,则该函数实际上可以工作。
But it’s not, so we get that ...is not a function
error.
但这不是,所以我们得到的...is not a function
错误。
How do we fix it?
我们该如何解决?
We must add a semicolon. Somewhere.
我们必须添加一个分号。 某处。
This would work:
这将工作:
const fs = require('fs');(async () => { //...})()
and also this would work:
而且这将工作:
const fs = require('fs');(async () => { //...})()
It’s a little price we have to pay to avoid the use of semicolons everywhere.
为了避免在任何地方使用分号,我们必须付出一点代价。
Tip: is now a thing, you can use that instead of this structure, and it will prevent such errors.
提示:现在已成为现实,您可以使用它来代替此结构,这样可以防止此类错误。
翻译自:
转载地址:http://vomgb.baihongyu.com/