Exploring ways to incorporate conditional imports without the need for personalized webpack settings!

Our project is designed to be compatible with both Cordova and Electron, using a single codebase. This means it must import Node APIs and modules specific to Node for Electron, while ignoring them in Cordova. Previously, we relied on a custom webpack configuration that used an environment variable to determine whether to treat the Node components as 'externals' for Cordova or to 'require' them for Electron. However, with our migration to Angular 9, integrating the builder required to run a custom webpack script (@angular-builders/custom-webpack) with the Ionic dev server builder (@ionic/angular-toolkit:cordova-serve) seems like a daunting task. Is there a way to achieve this without using a custom webpack script?

Answer №1

After much exploration, I stumbled upon the revelation that Webpack offers a hidden gem called __non_webpack_require__(), essentially acting as a runtime stand-in for require. This discovery opened the door to crafting a clever workaround for maintaining type safety with TypeScript:

declare function __non_webpack_require__(path: string): any;

import * as node_hid_typeonly from 'node-hid';
let node_hid: typeof node_hid_typeonly;
try { node_hid = __non_webpack_require__('node-hid'); } catch { }

Here's what this snippet accomplishes:

  1. Informs TypeScript about the existence of __non_webpack_require__()
  2. Imports node-hid solely for type annotations (as tsc can exclude imports used purely for typing purposes)
  3. Attempts to import node-hid into a variable defined with the correct type

This setup allows you to write code like this:

private device: node_hid_typeonly.HID;

and later on,

this.device = new node_hid.HID(path);

We've even managed to repurpose this technique in a non-webpack environment by incorporating:

global['__non_webpack_require__'] = require;

within index.ts before importing anything reliant on __non_webpack_require__.

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

Combining default and named exports in Rollup configuration

Currently, I am in the process of developing a Bluetooth library for Node.js which will be utilizing TypeScript and Rollup. My goal is to allow users to import components from my library in various ways. import Sblendid from "@sblendid/sblendid"; import S ...

Customizing Angular Forms: Set formcontrol value to a different value when selecting from autocomplete suggestions

How can I mask input for formControl name in HTML? When the autocomplete feature is displayed, only the airport's name is visible. After users select an airport, I want to show the airport's name in the input value but set the entire airport obje ...

Reference ngFor for Input Validation Template

I'm currently facing an issue with validating input fields within a *ngFor loop. I am struggling to create unique template references for each input field. Basically, I need all input fields to be required on submit unless at least one of them is fill ...

Presenting a data table in Angular

I'm new to using Angular and need help creating a table to organize my data, which is being fetched from a JSON file on the server. Here's the content of data.component.html: <div class="container"> <h1>Search history</h1> ...

Encountering issues during the installation of the Angular/CLI software

Whenever I execute the command below: npm install -g @angular/cli I encounter this error message: C:\Users\AA>npm install -g @angular/cli npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80f ...

Refresh the Angular2 API at regular intervals to monitor any updates in the response

Is it possible in Angular 2 to monitor changes in the API? Here is my scenario: I upload a document to an API at /document/upload This API returns a DOC ID When I make a call to /document/DOC_ID, the API responds with JSON in this structure: "errorCo ...

There was an issue: Control with the name 'name' could not be located

Whenever I submit the form and try to go back, an error pops up saying "ERROR Error: Cannot find control with the name: 'name'". I'm not sure what I might be missing. Do I need to include additional checks? Below is my HTML file: <div ...

The PrimeNG FullCalendar feature seems to be malfunctioning and cannot be located

I've been working on integrating a FullCalendar module into my Angular 7 project. Despite following the steps provided in this link, I haven't had any luck: After executing this command: npm install <a href="/cdn-cgi/l/email-protection" clas ...

Ordering an array in Angular 2: A step-by-step guide

I am working on an Ionic 2 app with an older version of AngularJS that does not have the orderby pipe by default. As a result, I have an array structured like this: <div *ngFor="let boatBooking of boatBookings" style="padding: 0px; margin:0px;"> ...

TypeScript Library encounters issues when importing a specific data type

I recently integrated a library into my Next.js application to manage layouts using useState in react-grid-layout. To make this work with TypeScript, I had to install the necessary package shown below: npm install --save @types/react-grid-layout The code ...

Combining conditions and CSS classes within the ngClass directive in Angular

Is it possible to combine a condition and a class within the same "ngClass" in Angular? [ngClass]="{cssclass1 : object.cssclass1status , object.cssclass2}" The condition (bold) and CSS class (italic) can be used together. Previously, I have implemented t ...

Tips for indicating errors in fields that have not been "interacted with" when submitting

My Angular login uses a reactive form: public form = this.fb.group({ email: ['', [Validators.required, Validators.email]], name: ['', [Validators.required]], }); Upon clicking submit, the following actions are performed: ...

Unable to transfer variable from a function to the test in Protractor

Currently, I am working on a test to verify the amount of gold in my possession. The test is being conducted using TypeScript and Protractor. Within this testing scenario, I have a method named GetAmountOfChips: public static GetAmountOfChips(): PromiseL ...

Encountered a React TypeScript issue stating that the type '{ ... }' cannot be assigned to the type 'IntrinsicAttributes & IntrinsicClassAttributes<...>'

Embarking on a new journey with a react typescript project, I encountered this puzzling error: Failed to compile. /Users/simon/Code/web/react-news-col/src/MainNewsFeed.tsx TypeScript error in /Users/simon/Code/web/react-news-col/src/MainNewsFeed.tsx(27,35 ...

Automatic renewal of bearer token in Angular 7

My AuthService has two key methods: getAuthToken (returns a Promise to allow lazy invocation or multiple invocations with blocking wait on a single set) refreshToken (also returns a Promise, using the refresh token from the original JWT to request a ...

Steps for sending data from Angular2 or Angular4 to a Node.js server and saving it in a MySQL database:1. In your

I've scoured the depths of the internet on Google but have come up empty-handed in finding a reliable working example. Any assistance would be greatly appreciated as I am relatively new to Angular2 (angular4). My goal is to have my angular2 applicati ...

Testing a NestJS service with multiple constructor parameters can be done by utilizing various techniques such as dependency

Content When testing a service that needs one parameter in the constructor, it's essential to initialize the service as a provider using an object instead of directly passing the service through: auth.service.ts (example) @Injectable() export class ...

The build of the module in ./src/client-app/index.js has encountered an error: It cannot locate the module '@babel/core'

I've been attempting to launch an application using React, Webpack, and webpack-dev-server on Windows. My setup includes Node v8.9.4 Npm v5.6.0 Webpack v3.11.0 Webpack-dev-server v2.9.1. The command I use to start the app is: "start": "webpack-dev-se ...

Troubleshooting a Cache Issue in Your Next.js Application

Whenever I attempt to run 'npm run build', an error crops up that seems to be linked to the css and fonts. Unfortunately, I am unsure of how to tackle this problem. It's perplexing as the app functions perfectly fine in development mode. Th ...

Updating the URL of a Link Message in a React App

Can anyone help me figure out how to change the message "website created using react app" that appears when I share my URL in chat applications? I am currently using the default settings of Mars Heroku React App Webpack. If anyone knows where I can find ...