[英]mysql node module give me an error "require is not defined"
我正在尝试在节点 js 项目(节点 18.12、mysql 2.18.1)中使用mysql 模块
在我的项目中我必须使用
“类型”:“模块”
在我的 package.json 中,因为应用程序是用模块构建的。 例如我在我的 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';
然后我添加行,就像在文档中一样
var mysql = require('mysql');
但是当我启动应用程序时出现此错误
mysql 节点模块“要求未在 ES 模块范围内定义,您可以改用导入”
我试图将类型更改为 commonjs 但以另一种方式得到相同的错误,试图将 js 文件的扩展名更改为 cjs 或 mjs。 每次都出现相同类型的错误。
如何将 mysql 与“本机”模块节点应用程序一起使用?
我是节点的初学者,所以如果这是一个愚蠢的问题,我很抱歉,但我无法在网上找到任何答案。
这是我的 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"
}
}
尝试从 package.json 中删除"type":"module"
。 从如何修复参考错误 require is not defined in javascript
我终于在这里找到了答案
const require = createRequire(import.meta.url);
var mysql = require('mysql');
我希望这对其他人有用;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.