"Exploring the power of Knex in combination with Typescript and Electron. However, encountering node_module errors

I currently have a functioning Electron application that utilizes Typescript. The main.ts file is specifically for the main process.

import { app, BrowserWindow } from 'electron';
import * as path from 'path';
import * as url from 'url';

// import knex from 'knex';
// import config from '../knexconfig';

// const db = knex(config);

let mainWindow: Electron.BrowserWindow | null;

async function init() {
    // db.select('*').from('users').then((rows) => {
    //     console.log(rows);
    // });

    createWindow();
}

function createWindow() {
    mainWindow = new BrowserWindow({
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
        },
    });

    process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = '1';

    if (process.env.NODE_ENV === 'development') {
        mainWindow.loadURL(`http://localhost:4000`);
        mainWindow.webContents.openDevTools();
    } else {
        mainWindow.loadURL(
            url.format({
                pathname: path.join(__dirname, 'index.html'),
                protocol: 'file:',
                slashes: true
            })
        );
    }

    mainWindow.on('closed', () => {
        mainWindow = null;
    });
}

app.on('ready', init);

At the moment, there are 6 lines of code commented out at the top. As it stands, the application works fine with this setup. However, enabling these commented lines triggers 10 errors as follows:

"Module not found. Can't resolve ... in ...\node_modules\knex\lib\dialects..."

Here are the detailed errors:

ERROR in ./node_modules/knex/lib/dialects/better-sqlite3/index.js 7:11-36
Module not found: Error: Can't resolve 'better-sqlite3' in 'C:\Users\timom\WebstormProjects\am-calendar\node_modules\knex\lib\dialects\better-sqlite3'
 @ ./node_modules/knex/lib/dialects/index.js 6:26-53
 @ ./node_modules/knex/lib/knex-builder/internal/config-resolver.js 5:36-61
 @ ./node_modules/knex/lib/knex-builder/Knex.js 7:26-63
 @ ./node_modules/knex/lib/index.js 1:13-43
 @ ./node_modules/knex/knex.js 8:13-35
 @ ./electron/main.ts 8:0-24 10:9-13

<!-- More errors continue -->

webpack 5.89.0 compiled with 10 errors and 2 warnings in 1270 ms

Two errors point to missing postgres and sqlite3, even though mysql is the specified database type in the configuration file. Conversely, one error states that mysql is missing, despite being installed on my system.

Below is the configuration file used to run the Electron app:

const path = require('path');

module.exports = {
    resolve: {
        extensions: ['.tsx', '.ts', '.js'],
    },
    devtool: 'source-map',
    entry: './electron/main.ts',
    target: 'electron-main',
    module: {
        rules: [
            {
                test: /\.(js|ts|tsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                },
            }
        ],
    },
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].js',
    },
};

And here is the package.json file for reference:

{
  "name": "am-calendar",
  "version": "1.0.0",
  "description": "",
  "main": "./dist/main.js",
  
  <!-- Remaining content omitted for brevity -->
}

Answer â„–1

I came across a helpful post on GitHub at https://github.com/knex/knex/issues/1128 that suggested adding the following to my electron configuration:

externals: {
  knex: 'commonjs knex'
}

After implementing this change, my updated configuration now looks like this and it is functioning as intended:

const path = require('path');

module.exports = {
    resolve: {
        extensions: ['.tsx', '.ts', '.js'],
    },
    devtool: 'source-map',
    entry: './electron/main.ts',
    target: 'electron-main',
    module: {
        rules: [
            {
                test: /\.(js|ts|tsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                },
            }
        ],
    },
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].js',
    },
    externals: {
        knex: 'commonjs knex'
    }
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to allocate FormArray

Just delved into learning Angular and encountered a snag. I am trying to add and remove textfields for a form, so I attempted the following code in my component.ts file: import {FormBuilder, FormGroup, FormArray } from '@angular/forms'; This is ...

Error in Angular Material: SassError - The CSS after "@include mat" is invalid. Expected 1 selector or at-rule, but found ".core();"

My Angular 11 project was running smoothly with Angular Material version 11 until I decided to update everything to Angular 12, including Material. However, after the update, the styles.scss file that comes with Material started throwing errors. The comple ...

Ways to display "No records" message when the filter in the material table in Angular returns no results

How can I implement a "No Records Message" for when the current table is displaying empty data? Check out this link for examples of material tables in AngularJS: https://material.angular.io/components/table/examples ...

Transforming the date from JavaScript to the Swift JSON timeIntervalSinceReferenceDate structure

If I have a JavaScript date, what is the best way to convert it to match the format used in Swift JSON encoding? For example, how can I obtain a value of 620102769.132999 for a date like 2020-08-26 02:46:09? ...

Input values that are true, or in other words, fulfill conditions for truthiness

Is there a specific data type in TypeScript to represent truthy values? Here's the method I'm working with: Object.keys(lck.lockholders).length; enqueue(k: any, obj?: any): void It seems like TypeScript allows checking for empty strings &ap ...

When attempting to utilize the Angular2 http.get function to retrieve data from a Restful Webservice, I encountered an issue where the error status 200 was returned

Angular 2 Issue with http.get Request to Restful Webservice When I try jsontest.com, I receive the value properly. getCurrentTime() { //return this.http.get('http://date.jsontest.com') return this.http.get('http://localhost:80 ...

Access a static class property through an instance

New and Improved Question: As I develop a client-side application, I am structuring an event-handling system inspired by the Redux framework. I have defined different event types as subclasses of a custom Event class. Each subclass includes its own stat ...

Loading complex JSON data into objects in TypeScript can be a challenging and intricate task

Dealing with a unique JSON structure that needs to be loaded into a TypeScript model. The challenge arises from receiving the JSON as an object instead of an array from a third party source. Is there a method to successfully load this data into the model ...

Circular function reference in Typescript occurs when a function calls itself

The functionality of this code snippet is rather straightforward; it either returns a function or a string based on an inner function parameter. function strBuilder(str: string) { return function next(str2?: string) { if(typeof str2 === "string& ...

Limitations of MaterialUI Slider

Looking for a solution to distribute 350 points across 8 sliders, each with a range of 0-100 and 5 marks at 0, 25, 50, 75, and 100. With each step consuming or returning 25 points, the challenge lies in allowing users to adjust the points allocation withou ...

Using TypeScript to Trigger Events in Three.js

After recently diving into Typescript, I encountered an issue when using EventEmitter from the ThreeJS library. Whenever I attempt to trigger an event: const event: THREE.EventDispatcher = new THREE.EventDispatcher(); event.addEventListener('test&apo ...

Refreshing HTTP request in Angular

I am currently working with Angular 5 and have encountered the following issue: Within my route, I have a parameter called year. The component related to this route is supposed to display data based on the year parameter, which is fetched from a service. ...

What steps can I take to eliminate the overload error that occurs when I extend the Request object in Express?

I'm having trouble extending Express' Request object to access req.user, and I'm encountering an overload error. I've attempted a couple of solutions, but none of them seem to work for me. EDIT: I am currently using Passport.js and JWT ...

Utilizing React to redirect with parameters

We are currently in the process of transitioning from an older angularJS system to a new system. However, we have encountered a problem with certain URLs that contain double slashes, such as "/#/work/customerDetails//:id". These URLs do not work ...

Add a Filter to the Observer (__ob__) in Typescript

I am trying to implement a filter using this.Grid.option("dataSource").filter(x => x.Placeholder != null) however, it doesn't seem to be working when I run console.log(this.Grid.option("dataSource")); I receive (72) [{…}, {…}, {…}, {†...

Leveraging the useRoute() function with Vue 3 Composition API and Typescript: [Vue alert]: The injection "Symbol(route location)" was not detected when employing Typescript

Just recently, I upgraded a Vue 2 application that heavily uses Vue Router and TypeScript to Vue 3. During the migration process, I switched a function from reading the route using this.$route in the Options API to using useRoute() in the Composition API. ...

Explore the world of data manipulation in Angular by experimenting with different

Embarking on a fresh Angular 2 project centered around Photos and Users. The backend work is all done, with the API in place. I've already constructed those classes. Now, I find myself pondering... To manipulate these objects on the client end, wo ...

Unraveling the mysteries of webpack configuration

import * as webpack from 'webpack'; ... transforms.webpackConfiguration = (config: webpack.Configuration) => { patchWebpackConfig(config, options); While reviewing code within an Angular project, I came across the snippet above. One part ...

Utilizing generics with Swagger in NestJS

export class PaginatedResult<T> { @Expose() @ApiResponseProperty(type: T}) // It's unfortunate that this isn't working because it's a type but being used as a value @Transform(({ obj }) => obj.data.map((data) => new obj.cla ...

The FileSaver application generates a unique file with content that diverges from the original document

I'm attempting to utilize the Blob function to generate a file from information transmitted via a server call, encoded in base64. The initial file is an Excel spreadsheet with a length of 5,507 bytes. After applying base64 encoding (including newlines ...