skip to Main Content

I’m trying to use mysql module in a node js project (node 18.12, mysql 2.18.1)

in my project I must use

"type": "module"

in my package.json because the app is constructed with modules. for example i use this imports in the head of my 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"

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 . every time same type of error.

How can I use mysql with "native" module node app ?

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

{
  "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"
  }
}

2

Answers


  1. Chosen as BEST ANSWER

    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 ;)


  2. Try to remove "type":"module" from package.json.
    From How to fix reference error require is not defined in javascript

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search