我正在使用 Pm2,這是錯誤:
SyntaxError: Cannot use import statement outside a module
Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
問題是,package.json已經設定為"type": "module"。
此外,在我重新啟動服務器之前,一切都可以正常作業。
這是實際.js檔案:
const http = require('http');
const url = require('url');
const querystring = require('querystring');
const hostname = 'localhost';
const port = 8080;
import captureWebsite from 'capture-website';
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World!\n');
....
});
uj5u.com熱心網友回復:
如果require呼叫沒有拋出錯誤,則.js在帖子中創建 http 服務器的“實際檔案”將被視為 CommonJS。但是 CommonJS 代碼不能使用import陳述句,需要使用匯入運算式(參見node和MDN檔案)。
如果您使用動態匯入(異步),您還需要在await陳述句之后(在async函式內)或在then方法中提供的成功處理程式中使用匯入的模塊:
// ....
import('capture_website')
.then( capture_website => {
// code requiring existence of `capture_website`
})
.catch( err=> console.error("Import of capture_website failed", err));
但是,您可以使用 ES6 檔案(Node doc)中的 import 陳述句匯入 CommonJS 模塊。
因此,更好的解決方案可能是重命名js發布的主檔案以賦予其.mjs擴展名,并用以下陳述句替換檔案中的所有 requireimport陳述句:
import http from 'http';
import url from 'url';
import querystring from 'querystring';
這擺脫了Cannot use import statement outside a module語法錯誤。匯入的 CommonJS 模塊應該仍然能夠使用該require函式來要求模塊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/360720.html
標籤:javascript 节点.js 节点模块 下午2
上一篇:操作陣列時出現錯誤
