How can we delay an import until runtime in webpack and TypeScript?

I'm currently working on developing code for wix-velo. In order to do this, I need to import various wix-velo libraries, such as

import * as whf from 'wix-http-functions';

To make sure my code runs smoothly, I've created a .d.ts file which makes my code look like this:

/// <reference path="../types/wix-http-functions.d.ts"/>
import * as whf from 'wix-http-functions';

While vscode seems okay with this setup, webpack is having trouble resolving the wix-http-functions import. How can I instruct webpack not to bundle wix-http-functions, but instead leave the import statement as it is? I believe this may have something to do with lazy loading or code-splitting, but I can't figure out from the documentation how to inform webpack (or ts-loader) that this import will be external.

Below is my webpack.config.js. Any help would be greatly appreciated.

const path = require('path');

module.exports = {
  entry: {
    calendar: './ts/calendar.ts',
    poster: './ts/html/poster.ts',
    mailchimp: './ts/mailchimp.ts',
    tcb: './ts/wix/tcb.ts',
    zaikoInject: './ts/zaiko-inject.ts',
  },
  devtool: 'inline-source-map',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        include: path.resolve(__dirname, "ts"),
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  output: {
    library: {
      name: '[name]',
      type: 'var',
    },
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
  },
  "optimization": {
    "minimize": false,
    usedExports: true,
  },
  mode: "development",
};

Answer №1

To achieve this, you can utilize `import type` which will be removed by the TypeScript compiler and won't be passed to Webpack.

Refer to the official documentation for more information.

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

What is the best way to store a set of tuples in a collection so that each tuple is distinct and

I am working with TypeScript and aiming to create a collection of unique objects, each with distinct properties. The combinations of these properties within the collection must be one-of-a-kind. For example, the following combinations would be considered ...

various methods for fetching array types (information retrieved through graphql)

I currently have a functional method that is structured as follows: const handleClickOnFavouriteLocation = (item: any) => { console.log('MY COORD', item.coordinates); if(data){ console.log('DATA COORD', data.personalF ...

Implementing an Angular HttpInterceptor to improve caching efficiency for simultaneous requests by utilizing a shared observable

I am looking to implement caching for HTTP parallel requests by sharing the observable and also storing the response in a Map object. Check out the online demo caching-interceptor.service.ts import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest ...

Issue TS2322: The type 'Observable<any>' cannot be matched with type 'NgIterable<any> | null | undefined'

Encountering an error while attempting to fetch data from the API. See the error image here. export class UserService { baseurl: string = "https://jsonplaceholder.typicode.com/"; constructor(private http: HttpClient) { } listUsers(){ //this ...

Using a template literal with the keyof operator as an interface property

Imagine a scenario where we have a basic interface: interface Schedule { interval: "month" | "day"; price: number; } We can create a template-literal type with TypeScript version 4.4: type PrefixedScheduleKey = `schedule__${keyof S ...

Verify if the date surpasses the current date and time of 17:30

Given a date and time parameters, I am interested in determining whether that date/time is greater than the current date at 17:30. I am hoping to achieve this using moment js. Do you think it's possible? This is what I have been attempting: let ref ...

What strategies can I use to address the problem of 'unable to resolve import in '@/...'" in vitest?

I encountered an error related to a file path defined in the "vite.config.ts" file. Can you assist me with this issue? Error Log Error Message: FAIL tests/utils/ConvertFromDomainToCountryCode.test.ts [ tests/utils/ConvertFromDomainToCountryCode.test.ts ...

How can we effectively test arrow functions in unit tests for Angular development?

this.function = () => { -- code statements go here -- } I am looking to write jasmine unit tests in Angular for the function above. Any suggestions on how to achieve this? it("should call service",()=>{ // I want to invoke the arrow funct ...

Having trouble updating an NPM dependency within package.json that is already installed as a dependency

I encountered an error message while trying to import mongoose with TypeScript node_modules/mongoose/node_modules/mongodb/mongodb.d.ts:3309:5 - error TS2416: Property 'end' in type 'GridFSBucketWriteStream' is not assignable to the same ...

What is the process for configuring vue.config.js with typescript?

Just starting out with typescript and running into an issue while configuring vue.config.js const webpack = require("webpack"); module.exports = { plugins: [ new webpack.DefinePlugin({ __VUE_I18N_FULL_INSTALL__: true, __ ...

Oops! There was an error: Unable to find a solution for all the parameters needed by CountdownComponent: (?)

I'm currently working on creating a simple countdown component for my app but I keep encountering an error when I try to run it using ng serve. I would really appreciate some assistance as I am stuck. app.module.ts import { BrowserModule } from &apo ...

What could be causing the class methods in my NestJS DI to be stored as undefined values in a map?

I came up with an EventService to manage custom events that are added through a special decorator. Everything appears to be functioning correctly, but the issue arises when attempting to access the methods within the stored event class as they return undef ...

When trying to reload Angular 8 pages, encountering an error that reads "Cannot GET /login" and also receiving a notification stating the image '/favicon.ico' cannot be loaded due to a violation of

Encountering an issue with the error message "Cannot GET login/" appearing on the page body of my latest Angular 8 app. Despite attempting various solutions found on forums, I have been unable to resolve this error. Any suggestions or advice would be great ...

The outcome of spawning Node.js is as follows: Python3 is unable to open the file './test' due to the error message [Errno 2] indicating that the file or directory does not exist

I am currently trying to execute a basic python script named test.py using the child process in Node JS, however I keep receiving an error message stating python3: can't open file './test': [Errno 2] No such file or directory. Despite my eff ...

Issues may arise in Typescript when trying to return an array of data from a redux createAsyncThunk function

Below is the code I am using to retrieve a list of users: export const fetchUserById = createAsyncThunk( "users/fetchById", async (_, { rejectWithValue, fulfillWithValue }) => { try { const response = await fetch(`https://reqres. ...

Disregard earlier callback outcome if there has been a change in the state since then

I am facing an issue with my page that displays a list of countries retrieved from an external library. When I click on a country, it should show me all the cities in that specific country. Each country object has a provided method to fetch the list of c ...

Tips for including HTML content in an agm-marker using Angular 2

In my Angular 2 application using agm map for vehicle tracking, I am looking for a way to customize the map marker. Specifically, I want to display the vehicle status by changing the color of the marker (green for running, red for stopped, yellow for idle) ...

Unraveling a commitment within a JSDoc type using ReturnType: Tips and Tricks

Below is the code snippet I need help with: const foo = async () => { return 1 } I am looking to assign a type to a variable that matches the ReturnType of the function, but after the promise has been resolved. When attempting the following: /** @ty ...

Ionic3 attempted lazy loading, however it failed due to the absence of any component factory

When implementing Lazy loading in Ionic3, the browser displays an error message after serving: Error: Failed to navigate - No component factory found for TabsPage. Have you included it in @NgModule.entryComponents? Below is the code snippet: app.modu ...

Issue accessing page from side menu in Ionic 2 application

I am experiencing an issue where the page does not open when I click on it in the side menu. Here is my app.component.ts file: this.pages = [ { title: 'NFC Page', component: NfcPage, note: 'NFC Page' }, ...