“module is not defined in ES module scope”的意思是說你的module並沒有被定義成ES module的scope內。
ES module
ES module又可以稱為ECMAScript module,是官方的標準化module規範,現今多數的瀏覽器都支援ES module的使用。
Node.js早期使用的是CommonJS的module語法,後來才支援ES module,ES module無法直接支援Common JS module,因此在兩個模組都有使用的情況下,經常出現衝突。
要檢查有沒有使用ES module scope,可以去package.json
看看是否有"type": "module"
這一行存在,如果有就代表使用了ES module。
解決方法1. 改檔名
當”module is not defined in ES module scope”這行字跳出來的時候,下面應該都會看到另外一行
This file is being treated as an ES module because it has a '.js' file extension and 'package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
這一行的意思是提示你混用ES module和CommonJS所以發生這個問題,只要將使用CommonJS語法的module.exports
的檔案從.js
改為.cjs
就可以成功編譯。
解決方法2. 將CommonJS語法改為ES module語法
//CommonJS module exports syntax
function example(){}
module.exports
={ example }
/***********************************/
//ES module export syntax
export function example(){}
//or
export default { params }
另外使用了ES module後也不能使用require,可以使用import來代替。