Search code examples
node.jssvelterollupsappernode-mysql2

How to use mysql2 library with Sapper?


I am creating an application in Svelte Sapper. I have a routes/account/login.js API route where I am trying to use mysql2. The route itself works (I checked with Postman), but as soon as I import mysql, the server crashes and an error appears:

[rollup-plugin-svelte] The following packages did not export their `package.json` file so we could not check the "svelte" field. If you had difficulties importing svelte components from a package, then please contact the author and ask them to export the package.json file.

- mysql2
import mysql from "mysql2/promise";

export async function post(req, res) {
  //route test
  const { login, password } = req.body;
  res.end(`${login}, ${password}`);
}

What can I do to make this import work? What can I do to make this import work?

The Sapper documentation doesn't say anything about whether you need to change something in the configuration additionally. https://sapper.svelte.dev/docs#Server_routes


Solution

  • I found a solution. I had to create a @lib folder in the src/node_modules folder and there file eg. db.js. In that file instead of import you need to use require()! and then you have to export the function that connects to the database. and then you can import that in the path

    //src/node_modules/@lib/db.js
    const mysql = require("mysql2");
    
    export async function connectToDatabase() {
      return mysql.createConnection({
        host: "localhost",
        ....
      })
    }
    
    //routes/account/login.js
    import { query } from "@lib/db";
    export async function post(req, res) {
      ...
    }