我最近開始學習 node.js。我正在使用 vs 代碼并通過 url 模塊并收到此錯誤。
PS G:\node js> node "g:\node js\urlmodule.js"
(node:1964) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
g:\node js\urlmodule.js:1
import url from 'url';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1033:15)
at Module._compile (node:internal/modules/cjs/loader:1069:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
代碼是-
import url from 'url';
const myURL = new URL('https://example.org');
myURL.pathname = '/a/b/c';
myURL.search = '?d=e';
myURL.hash = '#fgh';
console.log(myURL)
console.log(myURL.href)
uj5u.com熱心網友回復:
看起來您沒有設定來支持 es6 匯入。嘗試使用 commonjs 匯入:例如: const url = require('url'); 如果您想使用 es6 匯入,請關注:https ://www.geeksforgeeks.org/how-to-use-an-es6-import-in-node-js/
uj5u.com熱心網友回復:
嘗試設定:
"type": "module"
在你的 package.json 檔案中。
uj5u.com熱心網友回復:
您必須在 package.json 檔案中包含“型別”:“模塊”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/481015.html
