[英]How to use import and require in the same file - Node JS
I'm trying to use normalize-url package but it must be imported instead of required, as it is not supported in ES module.我正在尝试使用 normalize-url package 但它必须导入而不是必需,因为它在 ES 模块中不受支持。 I tried to get around this issue by adding two lines of code I found online that supposedly would solve the problem but it ain't working for me.
我试图通过添加我在网上找到的两行代码来解决这个问题,这应该可以解决问题,但它对我不起作用。 Here is the link for the solution https://www.kindacode.com/article/node-js-how-to-use-import-and-require-in-the-same-file/
这是解决方案https 的链接://www.kindacode.com/article/node-js-how-to-use-import-and-require-in-the-same-file/
import { createRequire } from "module";const require = createRequire(import.meta.url);
import normalizeUrl from 'normalize-url';
const express = require('express');
const router = express.Router();
const config = require('config');
const axios = require('axios');
I also included "type": "module",
in my package.json.我还在 package.json 中加入了
"type": "module",
。 The error msg: ` [0] const express = require('express');错误消息:` [0] const express = require('express');
[0] ReferenceError: require is not defined in ES module scope, you can use import instead [0] This file is being treated as an ES module because it has a '.js' file extension` [0] ReferenceError: require is not defined in ES module scope, you can use import instead [0] 此文件被视为 ES 模块,因为它具有“.js”文件扩展名
You should just use import from all of them.您应该只使用从所有这些中导入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.