如何解決JavaScript中的“不是函數”錯誤

我寫沒有分號的JavaScript。

我真的很喜歡。我認為這門語言比較乾淨。

您可能不喜歡它,這是可以理解的。但這就是事實。

分號是可選的。我們不需要添加它們。

但是,有時我們必須注意。特別是在Node.js中,我們使用require()加載外部模塊和文件。

在某些情況下,這可能會導致如下錯誤:

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.

It consider require('fs') as the name of the function, which is something that could actually work if the module export returned a function.

But it’s not, so we get that ...is not a function error.

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: top-level await is now a thing, you can use that instead of this structure, and it will prevent such errors.


More js tutorials: