gpt4 book ai didi

javascript - Node 错误 : Cannot use import statement outside a module even though I'm not

转载 作者:行者123 更新时间:2023-12-05 03:34:56 25 4
gpt4 key购买 nike

我正在使用 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');

....
});

最佳答案

如果 require 调用没有抛出错误,则在帖子中创建 http 服务器的“实际 .js 文件”将被视为 CommonJS。但是 CommonJS 代码不能使用 import 语句,需要使用 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 ) 中使用导入语句导入 CommonJS 模块。

因此,更好的解决方案可能是重命名发布的主要 js 文件,为其赋予 .mjs 扩展名,并将文件中的所有 require 语句替换为 导入语句:

import http from 'http';
import url from 'url';
import querystring from 'querystring';

这消除了 Cannot use import statement outside a module 语法错误。导入的 CommonJS 模块应该仍然能够使用 require 函数来请求模块。

关于javascript - Node 错误 : Cannot use import statement outside a module even though I'm not,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70027926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com