简体   繁体   English

如何在同一个文件中使用 import 和 require - Node JS

[英]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.

相关问题 如何在node.js上使用require-js而不需要require(“ requirejs”)和在每个文件中重新定义requirejs? - How to use require-js on node.js without having to require(“requirejs”) and redefine requirejs in each file? 我如何在节点 js 中使用请求和导入语句,在同一个文件中 - How can i use requier and import statments in node js , at the same file 如何在Laravel中使用此JS库? 进口? 要求? - How to use this JS library in Laravel? Import? Require? 如何使用Webpack 2将'require'或'import'插入到js文件中? - How to insert 'require' or 'import' into js file with Webpack 2? Nodejs - 将 mjs 文件中的内容导入 js 文件或如何在 mjs 文件中使用 require? - Nodejs - import stuff from mjs file into js file OR how to use require in mjs file? Node.js:如何像在 Python 中一样导入/请求文件、运行其命令并访问其更新的变量? - Node.js: How to import/require a file, run its commands and access its updated variables like in Python? Node.js不能在同一目录中要求.js文件 - Node.js cannot require a .js file in the same directory 如何导入和使用方法描述在普通js文件中使用require js? - How can I import and use method describe using require js in normal js file? 如何在没有Node.js的情况下使用JS require() - How to use JS require() without Node.js Webpack 如何 require.node 文件(在 Vue Electron 中使用 WebChimera.js package) - Webpack how to require .node file (To use the WebChimera.js package in Vue Electron)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM