简体   繁体   中英

Using sqlite3 in webapck with electron, react and typescript

I am trying to create an application using react and electron which uses web pack. I want to use sqlite3 for data storing but I can't seem to be able to use the node modules associated with it.

I am using the boilerplate from: https://github.com/sprout2000/electron-react-ts#readme

I've tried to add to webpack.config.ts

externalsType: 'commonjs',
externals: { 'sqlite3':'sqlite3' },

but it gives me the error of "Uncaught ReferenceError: require is not defined" I've tried other externals type but didn't work out.

This is the only thing I've edited in the main file. app.tsx

import { useState } from 'react';
import './App.css';
import sqlite3 from 'sqlite3';

const db = new sqlite3.Database('./database.db');
db.serialize(function () {
  db.all("select name from sqlite_master where type='table'", function (tables) {
      console.log(tables);
  });
});

const App = () => {
  const [count, setCount] = useState(0);
  
  return (
    <div className="container">
      <h1>{count}</h1>
      <button onClick={() => setCount((count) => count + 1)}>Count</button>
    </div>
  );
};
export default App;

Is there anyone who had this issue and solve it? Thank you in advance!

I should really write a post on how to hook up sqlite3 with Electron, but what you are trying to do is possible. If you aren't familiar with the basics, I encourage you to read this post which talks about using require in Electron apps.

TL;DR - You can't use require in your view with Electron. You have to require in your main.js process/file, and then use this "require'd" module from your view with IPC (inter-process communication).

Something like this should get you started

main.js

const {
    app,
    BrowserWindow,
    ipcMain
} = require("electron");
const sqlite3 = require("sqlite3");
const {
    open
} = require("sqlite");
const fs = require("fs");
const path = require("path");

let win;

async function createWindow() {
    win = new BrowserWindow({
        title: "MyAppTitle",
        webPreferences: {
            preload: path.join(__dirname, "preload.js")
        }
    });

    win.loadFile(path.join(__dirname, "../src/index.html"));

    win.on("closed", () => {
        win = null;
    });
}

app.on("ready", createWindow);

// This is called when requested from the view
ipcMain.on("RequestFromView", (event, args) => {

    (async () => {

        // Open sqlite3 database
        const db = await open({
            filename: path.join(__dirname, "../db/mydatabase.db"),
            driver: sqlite3.Database
        });

        const queryResult = await db.get(args.query);

    })();

    // send back to the renderer process that we are complete
    if (typeof win !== "undefined" && win !== null) {
        win.webContents.send("DoneWithQuery", {
            myResult: true
        });
    }
});

app.on("window-all-closed", () => {
    if (process.platform !== "darwin") {
        app.quit();
    }
});

app.on("activate", () => {
    if (win === null) {
        createWindow();
    }
});

preload.js

const {
    contextBridge,
    ipcRenderer
} = require("electron");

contextBridge.exposeInMainWorld("api", {
    query: function (query) {
        ipcRenderer.send("RequestFromView", {
            query
        });
    },
    doneWithQuery: function (callback) {
        ipcRenderer.on("DoneWithQuery", (event, args) => {
            callback(args);
        });
    }
});

app.tsx

import { useState } from 'react';
import './App.css';
import sqlite3 from 'sqlite3';

window.api.doneWithQuery(function(data){
    console.log(data.myResult); // true
});
window.api.query("select name from sqlite_master where type='table'");


const App = () => {
  const [count, setCount] = useState(0);
  
  return (
    <div className="container">
      <h1>{count}</h1>
      <button onClick={() => setCount((count) => count + 1)}>Count</button>
    </div>
  );
};
export default App;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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