TypeScript modules located within the node_modules directory and then deployed within the wwwroot folder

Implementing this in an ASP.NET Core 2.x web application should have been straightforward considering it's a standard pattern. However, I seem to be doing something very wrong.

Here is the folder structure that I am working with:

projectRoot
├── node_modules
│   ├── jquery
│   └── // other npm packages
├── wwwroot
│   ├── lib
│   │   ├── jquery
│   |   │   └── dist
|   │   |   │   └── jquery.js
│   │   └── // other files generated by Gulp tasks
│   ├── js
│   │   └── site.js // transpiled from site.ts
│   ├── css
│   └── page.html // script tag pointing to /js/site.js
├── ts
│   └── site.ts
├── gulpfile.js
└── tsconfig.json

The issue arises when trying to import jQuery in my site.ts.

// site.ts
import $ from "???"

I am struggling to find the correct path due to the following criteria:

  1. The path needs to be included in site.js

  2. It should be accessible from the browser

  3. It must be recognized by the TypeScript compiler

  4. The TypeScript compiler seems to refer to node_modules\@types\jquery

Below is my tsconfig.json. I rely on a Gulp task to transpile my .ts files, without any additional configurations besides this setup.

{
    "compilerOptions": {

        "module": "es2015",
        "baseUrl": "./wwwroot/js/",
        "paths": {
            "*": [ "./node_modules/@types/*" ],
            "../lib/jquery/dist/jquery.js": [ "./node_modules/jquery/dist/jquery" ]
        },
        "esModuleInterop": true,
        "moduleResolution": "node"
    }
}

I have experimented with adjusting the baseUrl and paths, but have not found a solution yet.

When Chrome fails to locate the path:

import $ from "lib/jquery/dist/jquery";

Uncaught SyntaxError: Unexpected identifier

Alternatively, if TypeScript fails to resolve the path, compilation is unsuccessful.

It surprises me that such a common setup is causing difficulty.

Answer №1

When incorporating jquery with angular, two packages must be installed.

npm install jquery --save
npm install @types/jquery --save

Subsequently, in the scripts section of the architect => build within the angular.json file, the path for the jquery library will need to be added.

"scripts": [
  "node_modules/jquery/dist/jquery.min.js"
]

Next, in tsconfig.app.json, add jquery to the types section to avoid the necessity of importing $ everywhere.

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": ["jquery"]
  },
  "exclude": ["test.ts", "**/*.spec.ts"]
}

It is important to note that some libraries, like moment or lodash, have export APIs for user convenience, allowing for common imports. However, third-party libraries such as jquery and mathjax only provide a js file, which must be imported into angular.json in order to use it globally.

Ultimately, the method of integration depends on whether the library exports an API for use.

Answer №2

It appears that I don't need to import jquery at all, as some kind of magic allows it to work seamlessly.

Is there a way to import JQuery into a Typescript file?

I decided to remove my import statement and surprisingly, everything still functioned properly.

Although I am uncertain about how to handle importing other JS modules in a similar manner without configuring TypeScript settings for the folder structure, so I have chosen to keep this question unresolved for now.

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

A more concise approach to accessing a generic class method in Typescript

Let's analyze the code snippet below: export class BaseClass<T> { property = this.buildProperty(); buildProperty(){ return someBuilder<T>(); } } Through TypeScript, the type of property is automatically determined based on the ...

What is the proper method for utilizing an object as a dependency when using useEffect?

Currently, I am in the process of developing a react hook that takes in a query object. export function useMyQuery(query: QueryObjectType) { React.useEffect(executeQuery, [ query ]); // ... } Unfortunately, whenever my hook is called during a re- ...

Surprising reaction with automatically organized keys

Just starting out with C# and WCF. I've already checked out this link but still stuck. Here's a simple GET service method: Expected JSON format: {"result":"Hello","add":4} Current JSON format: {"GetDataResult":{"add":4,"result":"Hello"}} E ...

Why is the AngularJS 2 child @Component not being replaced in this scenario?

UPDATE: It seems that the issue lies in how I am structuring and serving the project rather than a coding problem. If I find a solution, I'll be sure to update this post. Thank you for your assistance. I'm currently developing an AngularJS 2 ap ...

Resolving Challenges with AngularJS Form Validation and Submission

I am currently working on a project using AngularJS where the user can activate their account, input their data, and submit JSON data upon completion. My Goal: When the user submits valid user data (within the JSON data), they should be redirected to &a ...

Serialization of nested JObjects results in empty arrays being produced

I've encountered a puzzling scenario where I'm attempting to convert an object received from a third-party API into JSON. Unfortunately, I have no influence over the structure of the API's response or the object it provides. The C# POCO that ...

The data is not populating within JqGrid

I've verified that all the necessary javascript files are properly linked and have set the appropriate locale: <script type="text/javascript" src="http://localhost/Web/Scripts/jqgrid/js/jquery.jqGrid.min.js"></script> <script type= ...

Encountered a GSON error while expecting a String, but instead found an

I am currently using the Gson library to deserialize this object: [ { "_id": "53357a63138c2564feaf187f", "worktypes": [ { "name": "Type one" }, { ...

Displaying elements within a collection of forms

I am currently working on displaying users' names and a list of their courses in an Angular project. Each user has a different number of courses, so I am experimenting with using Angular Form Array to achieve this functionality. Below is a snippet fr ...

Syntax highlighting in VSCode does not seem to be functional when the ?? nullish coalescing operator is being utilized

Hello there! I've recently started using react.js with typescript on a new computer, but I've encountered an issue with syntax highlighting in VSCode. It seems that the problem arises when there's a double question mark (??) in the code, spe ...

No results displayed in the command prompt. No user input required in the command prompt

Recently, I started my journey learning Python 3. As part of our assignment, we were given a JSON file containing word meanings (basically an English dictionary). Our task was to create a program where we input a word and get its definition in return. How ...

Downloading a PDF in a Next.js application

How can I add a button or link that will instantly download my PDF portfolio when clicked? I am currently working on my resume section and would like to provide users with the option to easily download my CV. Is there a way to do this, and if so, how can ...

How to eliminate a particular validator from a form group in Angular

My goal is to eliminate the specific validator from the validator array so that I can reconfigure the controls when certain values have changed. I am aware of the traditional solution where I would need to repeatedly set validators. checked(event: MatC ...

Learn the proper way to specify the return type of a function as a class, rather than an instance, in Typescript

Is there a way to declare that a function returns a generic class definition? I have tried the following for non-generic classes, but it does not work for generic ones: export function composeAll(composeFunction: Function, depsFunction: Function): (compon ...

Learn how to set up browser targeting using differential loading in Angular 10, specifically for es2016 or newer versions

Seeking advice on JS target output for compiled Angular when utilizing differential loading. By default, Angular compiles TypeScript down to ES5 and ES2015, with browsers using either depending on their capabilities. In order to stay current, I've b ...

Is Angular Template Polymorphism Failing?

So I'm working with a base class that has another class extending it. export class Person { public name: string; public age: number; } export class Teacher extends Person { public yearsTeaching: number; } Now, in my component, I need to ...

Here is a way to trigger a function when a select option is changed, passing the selected option as a parameter to the function

Is there a way to call a function with specific parameters when the value of a select element changes in Angular? <div class="col-sm-6 col-md-4"> <label class="mobileNumberLabel " for="mobilrNumber">Select Service</label> <div cla ...

Exploring the capabilities of Dynamic Route integration with Server Side components using Supabase in Next.js

export default async function Page({ searchParams, }: { searchParams?: { [key: string]: string | string[] | undefined }; }) { // const searchParams = useSearchParams(); const id = searchParams?.p ?? "aaa"; // default value is "1" ...

Sending a JSON payload along with a file using Delphi

I am a beginner in Delphi and I am looking to send a JSON string along with additional files using a single HTTP POST method. However, when I use the TIdHTTP class, the sent JSON text breaks and becomes unusable. Can anyone provide guidance on how to sol ...

Unlimited columns in flatlist

Creating a list with varying text lengths in React Native presents a challenge when trying to determine how many items can fit in a single row. The goal is to calculate the maximum number of items that can be included in a row and display them accordingly. ...