【问题标题】:Node Error: Cannot use import statement outside a module even though I'm not节点错误:即使我不是,也无法在模块外部使用 import 语句
【发布时间】:2021-12-29 19:40:30
【问题描述】:

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

【问题讨论】:

  • @fast-reflexes 你能举个代码例子吗?对Node不太熟悉。
  • @fast-reflexes 嗯,它说这些都很好。该错误仅出现在import captureWebsite from 'capture-website';
  • @fast-reflexes 这很好,但错误是import captureWebsite from 'capture-website';。那条线是导致错误的原因。我们可以专注于吗
  • 节点只是 javascript。

标签: javascript node.js node-modules pm2


【解决方案1】:

如果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) 中的 import 语句导入 CommonJS 模块。

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

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

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

【讨论】:

    猜你喜欢
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多