Using TypeScript and webpack 2 to integrate typeahead.js into your project

I am encountering an error message coming from webpack.

ERROR in ./wwwroot/js/admin/infrastructure/typeaheadComponent.ts Module not found: Error: Can't resolve 'typeahead' in ...

I have the following dependencies installed

npm install typeahead.js
npm install @types/typeahead

This is my TypeScript code, using node module resolution.

import { module } from "angular";
import "typeahead";
// necessary to import typeahead into JQuery, as otherwise
// typeahead below is not defined.

class TypeAheadController {
    foo(e) {
       $(e).typeahead(...)
    }
}

which translates to JavaScript like this:

"use strict";
var angular_1 = require("angular");
require("typeahead");
var TypeAheadController = (function () { ...

This is my webpack.config.js setup:

module.exports = {
    context: __dirname,
    entry: [
        "./app.ts",
        "./tab.ts",
        "./client/clientService.ts",
        "./client/clientSearchComponent.ts",
        "./infrastructure/messageComponent.ts",
        "./infrastructure/typeaheadComponent.ts",
        "./url.ts"],
    output: {
        filename: "./wwwroot/js/admin/admin.js"
    },
    devtool: "source-map",
    module: {
        rules: [
            { test: /\.ts$/, use: 'ts-loader' }
        ]
    }
};

including a gulp task.

How can I specify that typeahead is located at

node_modules/typeahead.js/dist/typeahead.bundle.js

Answer №1

Ensure to include the typeahead.js module instead of typeahead when working with the typeahead.js module.

import "typeahead.js";

The import statement should match the name used during installation via npm. It simply searches for the specified directory within node_modules and then refers to the file mentioned in the main field of the package.json. For more information, refer to Node.js - Folders as Modules.

In certain cases, you can utilize resolve.alias to modify the import name, although it may not be necessary in this scenario.

Answer №2

I was able to fix this issue by implementing the following adjustments.

Make sure to import Bloodhound and Typeahead separately. Modify your webpack.config.js accordingly.

  resolve: {
    extensions: ['.js', '.ts'],
    alias: {
      typeahead: 'corejs-typeahead/dist/typeahead.jquery.min.js',
      bloodhound: 'corejs-typeahead/dist/bloodhound.min.js'
    }
  },

In your .ts file:

import "typeahead";
import * as Bloodhound from "bloodhound";

Answer №3

To address this issue, you can utilize aliasing in your configuration file. Here is a simple example of the changes to make in your webpack.config.js:

module.exports = {
  /* ... all existing configurations */
  resolve: {
    alias: {
      typeahead: 'typeahead.js'
    }
  }
}

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

The Slack Bot is having trouble downloading files from direct messages, but it is successfully downloading them when uploaded to a channel

I have developed a program to retrieve files using a code snippet provided by a Slack bot. Below is the code: var https = require('https'); var fs = require('fs'); var downloadFile = function (url, dest){ var slug = url.split(&apos ...

Why is React's nested routing failing to render properly?

click here for image portrayal I am currently attempting to integrate react router, specifically a nested router. However, when I click the links on the contact page, no results are being displayed. Any assistance would be greatly appreciated. For more in ...

Eliminating the table header in the absence of any rows

I have successfully implemented a Bootstrap table in my React application, where users can add or delete rows by clicking on specific buttons. However, I want to hide the table header when there are no rows present in the table. Can anyone guide me on how ...

Empty Data Table Search After Refresh While Filter Remains Active

After testing the data tables library using their example code in a jsfiddle, it seems like there might be a bug. To recreate the issue, follow these steps: Open the JS Fiddle link https://jsfiddle.net/t4rphnuc/ Click "Run" In any footer search box, fil ...

What is the best way to display the key within an object in a mui-datatable?

I attempted to define it in the following manner: { name: "colorList", label: "Color", options: { filter: true, sort: true, customBodyRender: (value, tableMeta, updateValue) => { ...

The dependency that was installed in the node_modules directory is now showing as missing the

I have encountered an issue with 2 TS packages. The first package, project-1, is installed as a dependency in the second package, project-2. While I am able to import and access all type definitions of project-1 in project-2, the dependencies (node_modules ...

The functionality of the KendoReact Grid for filtering and sorting is not functioning correctly when data is grouped

Once I group the data, the filter and sort functions in the KendoReact Grid stop working. Interestingly, if I bypass the grouping step and show the data without grouping, the filter and sort functions function perfectly fine. My main objective is to figu ...

Tips for removing markers from personal Google Maps

I am having trouble deleting markers from my Google Maps using my code. The markers array seems to be empty even after adding markers. Can anyone help me troubleshoot this? Thank you! When I use console.log(markers.length) in the removeMarkers() function, ...

Automating testing with WebdriverIO in scenarios where JavaScript is turned off

Is it possible to launch the browser with JavaScript disabled in the WebdriverIO framework? I am looking to automate a scenario that requires JavaScript to be disabled. However, when I try to disable JavaScript manually in Chrome or Firefox and run WDIO s ...

Are there any comparable features in JavaScript and TypeScript that mirror Julia's metaprogramming and macros?

Having experience with Julia macros for metaprogramming, I find them to be a convenient way of generating versatile code. I'm curious if there is an equivalent approach in JavaScript or TypeScript. Is there a package or method that offers similar fun ...

Utilize utility functions within the onCreated lifecycle event in Meteor

Here is my current setup: Template.myTemplate.helpers({ reactiveVar: new ReactiveVar }); How can I initialize reactiveVar within the onCreated function? Template.restaurantEdit.onCreated(function() { // I want to initialize helpers.reactiveVar here ...

Discovering the worth in Meteor MongoDB

As someone who is new to web programming, I have been experimenting with Meteor and MongoDB lately. I have a form that sends data to MongoDB, and by using the query below, I was able to retrieve the most recent entry: database.findOne({}, {sort: {'t ...

Changing the Express.Request.user type from optional User to required User for authorized routes: A guide

Currently, I am developing a server using Express and Typescript. I have integrated passport js for authenticating the routes I have set up. However, one issue that I encounter is that Express.Request.user is defined as Express.User | undefined. This means ...

sending a parameter in the reverse url using JavaScript

coding in javascript let address = '{% url candidate_resume "cnd_id" %}'; address = address.replace("cnd_id",id); document.getElementById('cell2').innerHTML= '<a href="' + address + '"> View Resume < ...

Ways to showcase multiple elements using introjs

I am attempting to highlight multiple DOM elements using the JS library intro.js, but I am encountering an issue. It seems that I can only define one element to be highlighted at a time. introjs.setOptions({ steps: [ { ...

Learn how to activate a JS native event listener using jQuery for the 'change' event

This question is unique from the one found at How to trigger jQuery change event in code. The focus here is on the interaction of jQuery with native event listeners, rather than jQuery event listeners. I am using addEventListener to bind a change event fo ...

Error in TypeScript when type-checking a dynamic key within a record

When explicitly checking if a property is not a string using a variable key, Typescript throws an error saying Property 'forEach' does not exist on type 'string'. let params: Record<string, string | string[]>; const key = 'te ...

Can local storage be accessed within a function and utilized during the Windows.onload event?

I have an onclick function that dynamically returns 'x' and stores it in a div. However, after a page refresh, the dynamic div resets and the data is lost. To prevent this, I stored the data in local storage within the 'test' function a ...

Tips for correctly loading all elements on an HTML page before making CSS modifications

This question has been asked several times in the past. I am asking because when I used the on ready callback in jQuery, it did not change the placeholder text of my element "search_input". $( document ).ready(function() { $("#search_input").attr(' ...

Is it a guarantee that a function called in the head section of a JavaScript for-of loop will only be executed once?

In both Firefox and Chrome, I tested the code snippet below: function test() { console.log("***") return [1,2,3] } for (const t of test()) { console.log(t) } After running this code, I noticed that the test function was only called once. T ...