简体   繁体   English

mysql节点模块给我一个错误“require is not defined”

[英]mysql node module give me an error "require is not defined"

I'm trying to use mysql module in a node js project (node 18.12, mysql 2.18.1)我正在尝试在节点 js 项目(节点 18.12、mysql 2.18.1)中使用mysql 模块

in my project I must use在我的项目中我必须使用

"type": "module" “类型”:“模块”

in my package.json because the app is constructed with modules.在我的 package.json 中,因为应用程序是用模块构建的。 for example i use this imports in the head of my app.js例如我在我的 app.js 的头部使用这个导入

import { createServer } from 'node:http';
import fs from 'node:fs/promises';
import { createTodo, findTodos } from './functions/storage.js';
import { index,create } from './functions/api/api.js';

then I add the line, like in the doc然后我添加行,就像在文档中一样

var mysql = require('mysql');

but when I launch the app i have this error但是当我启动应用程序时出现此错误

mysql node module "require is not defined in ES module scope, you can use import instead" mysql 节点模块“要求未在 ES 模块范围内定义,您可以改用导入”

I have tried to change type to commonjs but get the same error in the other way, tried to change the extensions of the js file for cjs or mjs.我试图将类型更改为 commonjs 但以另一种方式得到相同的错误,试图将 js 文件的扩展名更改为 cjs 或 mjs。 every time same type of error.每次都出现相同类型的错误。

How can I use mysql with "native" module node app?如何将 mysql 与“本机”模块节点应用程序一起使用?

I'm a beginner in node so, sorry if it is a dumb question, but I can't find any answer by the web.我是节点的初学者,所以如果这是一个愚蠢的问题,我很抱歉,但我无法在网上找到任何答案。

Here is my package.json这是我的 package.json

{
  "name": "project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "type": "module",
  "keywords": [],
  "author": "",
  "license": "ISC",
  "volta": {
    "node": "18.12.1"
  },
  "dependencies": {
    "mysql": "^2.18.1"
  }
}

Try to remove "type":"module" from package.json.尝试从 package.json 中删除"type":"module" From How to fix reference error require is not defined in javascript如何修复参考错误 require is not defined in javascript

I finally found the answer here我终于在这里找到了答案

const require = createRequire(import.meta.url);
var mysql      = require('mysql');

I hope this will be useful for other people;)我希望这对其他人有用;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM