Leveraging jQuery within a webpack module shared across multiple components, located outside the webpack root directory

When working with multiple layouts that rely on shared typescript files, it is important to ensure these files are accessible across different layouts using webpack.

While attempting to include jquery in my ajax.ts, I encountered the following error:

ERROR in ../_shared/ajax.ts
    Module not found: Error: Can't resolve 'jquery' in '{...}/layouts/_shared'

_shared/ajax.ts:

import * as $ from 'jquery';
export class AjaxListener {
    constructor(){
        // utilizing jquery with $
    }
}

layoutA/app.ts:

import { AjaxListener } from "../_shared/ajax";
import { App } from "../_shared/app";


let app = new App();
let ajaxListener = new AjaxListener();

The Folder Structure is as follows:

/layouts
    /_shared
        /ajax.ts
        /app.ts
    /layoutA
        /app.ts
        /webpack.config.js
        /package.json (includes "@types/jquery": "^2.0.47" and "jquery": "^3.2.1")
        /tsconfig.json

tsconfig.json:

{
  "compilerOptions": {
    "module": "es6",
    "target": "es6",
    "sourceMap": true
  },
  "exclude": [
    "node_modules",
    "typings/browser",
    "typings/browser.d.ts",
    "typings/main",
    "typings/main.d.ts"
  ]
}

webpack.config.js:

const ExtractTextPlugin = require("extract-text-webpack-plugin");
var path = require("path");

var distPath = path.join(__dirname, "dist");

module.exports = [
    {
        entry: {
            app: ['./app.sass', './app.ts']
        },
        resolve: {
            extensions: [".tsx", ".js", ".ts", ".sass"]
        },
        cache: false,
        output: {
            path: distPath,
            filename: "[name]_scripts.js"
        },
        module: {
            rules : [
                {
                    enforce: 'pre',
                    test: /\.js$/,
                    loader: "source-map-loader"
                },
                {
                    test: /\.tsx?$/,
                    exclude: [/node_modules/],
                    use: [ 'babel-loader', 'ts-loader' ]
                },
                {
                    test: /\.sass$/,
                    use: [
                        {
                            loader: "style-loader"
                        },{
                            loader: "css-loader", options: { sourceMap: true } 
                        },{
                            loader: "sass-loader", options: { sourceMap: true }  
                        }
                    ]
                }
            ]
        },
        devtool: "eval"
    }
]

If attempting to import jquery within the layoutA/app.ts file (root of webpack), it functions correctly. Given that ajax.ts resides outside this folder, what is the most effective approach for importing libraries like jquery, lodash, etc. in these files?

Answer №1

When it comes to loading js libraries in your specific context, there are certain key points to keep in mind:

  1. Make sure to install every js library (such as jquery) using a package manager like npm
  2. For each library, you'll need a TypeScript definitions file (for example, @types/jquery, which can be found on npmjs.com)
  3. Install the TypeScript definition files with npm as well
  4. Remember to include each TypeScript definition in the tsconfig.json under "files" like so:

"files":[
    "node_modules/@types/jquery/index.d.ts",
    "node_modules/@types/requirejs/index.d.ts",
    ]

  1. Follow these steps (points 1-4) diligently when dealing with the library requirejs, which is a js file and module loader
  2. Once done, you can proceed to load the js library in your TypeScript main file like this:

require(["jquery", "urijs"], function($, uri) {
// your code
});

Additional tips:

  • In your index.html file, only reference the js bundle files under the script tags, built for example by webpack
  • Remember that Webpack requires a TypeScript loader
  • Reference exported TypeScript classes in the tsconfig.json file under 'files' and also in your TypeScript file like this:

import {Car} from "./classes/Car";

I hope this helps you establish a proper structure!

Additionally:

Try referencing a js library in your ayax.ts file like:

private example = require("./[path to npm library]/node_modules/test/src/test.js");

If you use the library name 'test' in the require command, it may not resolve correctly as it tries to do so via the package.json and fails to find it outside of the root directory.

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

Transform a single attribute in an array of objects using angularjs and Javascript to a different value

Within an angularjs controller, the following code is used: var ysshControllers = angular.module('theControllers', []); ysshControllers.controller('CommonController', function($scope, $http, $route) { $scope.dbKey = $route ...

Elegant Bootstrap 4 Carousel featuring a glimpse of the upcoming slide alongside the primary carousel item

I am in search of a straightforward Bootstrap 4 carousel that showcases a glimpse of the next slide on the right. Despite exploring similar questions, I have not found a suitable solution. The links to those questions are: 1)Bootstrap carousel reveal part ...

Working with JSON objects in AngularJS

I have a JSON dataset in the following structure. I need to extract information from the JSON and display it on an HTML table. [region: [name:"", code:""IntradayBalance:{ currency:,Time:,Balance: }.... ], acccountcurrencyBalance:[{ c ...

Looking for a simple method to display a popover using conditional if/else statements?

On my website, I am utilizing JavaScript to determine the user's Facebook status. This includes checking if the user is already logged in and has allowed our app, if they are logged in but haven't authorized our application, or if they are not lo ...

How to use Javascript to toggle a popup containing an autoplaying Vimeo video

I am looking to create a pop-up window containing a Vimeo video inside. I have a div on my webpage with an id of "showVideo". When this div is clicked, I want to display a pop-up (new div with the id of "opened-video"). The "opened-video" div contains an i ...

The component next/image is experiencing issues when used in conjunction with CSS

I struggled to create a border around an image because the custom CSS I wrote was being overridden by the Image component's CSS. Despite trying to leverage Tailwind and Bootstrap to solve the problem, my efforts were unsuccessful. Now, I am at a loss ...

Learn how to configure and utilize an AngularJS factory using ngResource along with passing parameters in the call

As a newcomer to Angular, I'm seeking guidance on creating a new factory utilizing ngResource instead of $http, with the ability to pass parameters. Following an example provided here, I have defined my factory as shown below: app.factory('abst ...

Upon initiating npm start in my React application, an error was encountered: internal/modules/cjs/loader.js:834

Upon downloading my React course project, I proceeded to install dependencies and run npm start. To my dismay, I encountered the following error: PS C:\Users\Marcin & Joanna\Desktop\react-frontend-01-starting-setup> npm start &g ...

The specified property 'toString' is not found in the Typescript type

This particular situation was a bit perplexing for me. When I use the search function, I am seeking substring matches of the search keywords. Therefore, before comparing any object, I convert all properties to strings and check for substrings. Based on my ...

Filtering options in a dropdown box with jQuery

I have implemented a feature where the content of one select box is filtered based on the option selected in another select box. Below is the code snippet that achieves this functionality: // Filter content based on the selected option in a region select ...

Unexpected behavior encountered in Rails app with unobtrusive JavaScript

I'm facing an issue with my link_to setup. Here's what I have: <%= link_to "Load More", comments_feed_path(@post.id), :id => 'my-link', :remote => true %> In my application.js file, I have the following code: $( document ...

AngularJS is encountering issues with dependency injections when using WebStorm and TypeScript

A TypeScript AngularJS component: class MyComponentCtrl { static $inject = ['MyService']; constructor(private MyService) { MyService.testfn(55); // No error in typescript } } class MyComponent implements ng.IComponentOptions { ...

best typescript configuration for node 8 suggested

When configuring TypeScript for use with Node 8, what is the optimal setup? Many tutorials recommend using the following tsconfig.json: { "compilerOptions": { "target": "es6", "module": "commonjs" } } However, it has come to my attention tha ...

Remove the ID, class, and other attributes from an HTML string using JavaScript for sanitization purposes

Can someone help me with sanitizing HTML text provided by a user? The HTML code in question is as follows: var htmlStr = `<p id="test" class="mydemo">TEhis is test</p> <pre class="css"> &lt;html> &lt;body cl ...

React.js is throwing a 429 error message indicating "Too Many Requests" when attempting to send 2 requests with axios

Currently, I am in the process of learning React with a project focused on creating a motorcycle specifications search web application. In my code file /api/index.js, I have implemented two axios requests and encountered an error stating '429 (Too Ma ...

JavaScriptCore now includes the loading of AMD modules

I am trying to incorporate a JavaScript module into JavascriptCore on iOS. To achieve this, I am fetching the file's text through a standard HTTP request on the iOS platform. Once I have obtained the entire string, I plan to parse it into the JSconte ...

Does the Apps Script parser JSON.parse() incorrectly remove leading zeros from string object keys?

I am facing an issue with my Apps Script Web App where JSON data is being manipulated when I try to parse it. Specifically, keys with leading zeros are being altered (e.g "0123" becomes "123") during the JSON.parse() function call. It seems like the functi ...

Using JavaScript to convert an image URL to a File Object

Looking to obtain an image file from a URL entered into an input box, leading to the transformation of an image URL into a file object. To illustrate, when selecting a random image on Google Images, you can either copy the Image or its URL. In this scena ...

The Tanstack react-table feature is limited in its ability to output tsx from the cell

Currently conducting a test on Tanstack react-table library using React and TypeScript. It appears that I am encountering an issue with returning tsx/jsx from the cell function of ColumnDef: Is there something crucial that I seem to be overlooking in this ...

Changing dot notation to bracket notation in Angular

Having trouble using dynamic columns in a Primeng table? The column fields need to be in bracket notation for this setup. What if you have a column with nested JSON structure and you're not sure how to write that in bracket notation? Don't worry, ...