Exploring the Integration of OverlayScrollbars with TypeScript

Currently, I am delving into TypeScript utilizing a project built on ASP.NET Core 3.0 and the VS 2019 IDE. Recently, I acquired the OverlayScrollbars plugin via npm: .

npm install overlayscrollbars
npm install @types/overlayscrollbar

Provided below is a straightforward usage example:

/// <reference path="../../libs/npm/@types/overlayscrollbars/index.d.ts" />

import OverlayScrollbars from "../../libs/npm/@types/overlayscrollbars/index"; // ../../libs/npm/overlayscrollbars/js/overlayscrollbars.js

$(() => {
    OverlayScrollbars($("body")[0], { });
    //$("body").overlayScrollbars({ });
});

The solution compiles successfully, the files are transpiled (the target is switched as per the comment - this will be an area of future inquiry for me) and then copied to the wwwroot. At this stage, the files are referenced correctly.

Here is my tsconfig.json configuration file:

{
  "compileOnSave": true,
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "noEmitOnError": true,
    "noImplicitAny": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "target": "es6",
    "typeRoots": [ "node_modules/@types/**" ]
  },
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ]
}

Despite this success, upon executing

OverlayScrollbars($("body")[0], { });
, I am met with
Uncaught SyntaxError: The requested module does not provide an export named 'default'
at runtime.

https://i.stack.imgur.com/4jj6U.png

Alternatively, using the second method (

$("body").overlayScrollbars({ });
), I encounter compilation error
TS2345: (TS) Argument of type '{}' is not assignable to parameter of type string
along with some peculiar intellisense issues:

https://i.stack.imgur.com/zFjW5.png

https://i.stack.imgur.com/iCuPe.png

Addressing this problem in C# would be more straightforward, but due to my limited knowledge of TS, solving it seems challenging without resorting to trial and error.

Attached is a basic project that demonstrates this issue:

Any assistance or guidance provided would be greatly appreciated.

// EDIT 1

@Kewin Dousse

I want to clarify that I specifically reference the declarations because I import the actual files in my .cshtml file.

<link href="~/libs/npm/overlayscrollbars/css/OverlayScrollbars.css" rel="stylesheet" />
...
<script src="~/libs/npm/overlayscrollbars/js/jquery.overlayScrollbars.js"></script>

This approach was chosen to preemptively address the aforementioned issues, whether opting for the JQuery or Vanilla version of OVerlayScrollbars.

My understanding is that when using imports, the browser must directly point to the JavaScript file with the explicit .js extension for functionality.

To resolve this, I have set up gulp to substitute the path to the d.ts file with the one in the comment.

If I include this line:

import OverlayScrollbars from "../../libs/npm/@types/overlayscrollbars/index"; // ../../libs/npm/overlayScrollbars/js/jquery.overlayScrollbars.js

An editor warning pops up in my .ts file:

https://i.stack.imgur.com/pU2wS.png

And there's a runtime error:

https://i.stack.imgur.com/Mvucg.png

When employing this code:

import { OverlayScrollbars } from "../../libs/npm/@types/overlayscrollbars/index"; // ../../libs/npm/overlayScrollbars/js/jquery.overlayScrollbars.js

I encounter compilation error TS2305 displaying an unusual path:

https://i.stack.imgur.com/mwE3R.png

Using this line:

import * as OverlayScrollbars from "../../libs/npm/@types/overlayscrollbars/index"; // ../../libs/npm/overlayScrollbars/js/jquery.overlayScrollbars.js

Errors out with TS2349:

https://i.stack.imgur.com/AInLQ.png

Accompanied by an intellisense error:

https://i.stack.imgur.com/56eza.png

(For potential VS fix, consider changing the path to

import OverlayScrollbars from "../../libs/npm/@types/overlayscrollbars/index";
)

The only method that currently works for me is hand-crafting the declaration for the JQuery extension like so:

interface JQuery {
    overlayScrollbars(
        options: OverlayScrollbars.Options,
        extensions?: OverlayScrollbars.Extensions
    ): JQuery;
    overlayScrollbars(
        filter?: string | ((element: Element, instance: OverlayScrollbars) => boolean)
    ): OverlayScrollbars | OverlayScrollbars[] | undefined;
}

Utilizing it as follows:

$("body").overlayScrollbars({ });

While removing the module import altogether.

I acknowledge that this custom declaration aligns with what the declarations file is intended to accomplish, yet, inspecting its content, the setup fails to function properly.

Answer №1

The issue at hand is that you are not correctly importing the code for OverlayScrollbars into your file; instead, you are only importing its type definitions.

When referring to type definitions like

"../../libs/npm/@types/overlayscrollbars/index"
, it points to the @types/overlayscrollbars npm package, which solely consists of declaration files. Declaration files add TypeScript types to JavaScript libraries for efficient usage with TypeScript, meaning they only specify types and do not execute any JavaScript code.

You have imported the declaration file for the overlayscrollbars package, allowing TypeScript to understand the types used by that JS library. However, you still need to import the actual library code itself.

To import the library, follow a similar approach as if you were working with JS. While I'm unsure of the specific exports of this library, your import statement may resemble the following:

import OverlayScrollbars from "../../libs/npm/overlayscrollbars";

If the above doesn't work, you can also try these alternatives:

import { OverlayScrollbars } from "../../libs/npm/overlayscrollbars";
import * as OverlayScrollbars from "../../libs/npm/overlayscrollbars";

The way in which the module exports its symbols might vary, necessitating different import methods (which would require inspecting the lib's export structure).

The second error message indicates that you are invoking overlayscrollbars incorrectly, with the first argument expected to be a string.

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

Issue with Angular 6 Share module functionality not functioning as expected

While creating my Angular 6 application, I encountered an issue with sharing a header across multiple pages. I tried including it but it doesn't seem to be working. Can anyone point out what I might be doing wrong? For a demonstration, you can visit . ...

problem encountered while attempting to drag and drop list elements on a web application utilizing dhtmlx 5.0 and wijmo grid

My web application utilizes Dhtmlx 5.0, Wijmo grid, and Typescript. One feature of the app is a dialog box that displays a list of items which can be rearranged using drag and drop functionality. This feature works without any issues on Windows PCs but enc ...

Is it possible to implement a feature in Angular and Bootstrap where the toggle menu can be closed by clicking anywhere on the page, rather than just the toggle button

I'm working on an Angular project where I've implemented a navbar component. The navbar is responsive and includes a toggle button that appears when the browser window is resized. This button allows users to hide or display the menus. One issue ...

Enhanced string key indexer type safety in TypeScript

Discover and explore this online TypeScript playground where code magic happens: export enum KeyCode { Alt = 'meta', Command = 'command', // etc. } export type KeyStroke = KeyCode | string; export interface Combination { comb ...

`Angular 6 and the expiration of Jwt tokens`

I am currently developing an angular application that utilizes jwt for authenticating database calls. However, I encountered a problem where, when the token expires on the server, the app starts displaying blank pages instead of the expected data. This hap ...

Using object in TypeScript to reduce arrays

Is there a way to set the return value for my reducer in TypeScript? I am looking to achieve: Instead of using 'any', what should I assign as the type for acc? How can I define my return type so that the output will be {temp: 60, temp: 60}? retu ...

Prevent the Vue page from loading until the data has been fetched successfully

I'm in the process of finding a way to prevent my page from loading until my fetch task is completed. I'm facing some issues that need to be addressed: I have to re-fetch the data each time because I can't reuse the same data. (Changing vie ...

What is the best way to implement CSS Float in typescript programming?

For a specific purpose, I am passing CSS Float as props. To achieve this, I have to define it in the following way: type Props = { float: ???? } const Component = ({ float }: Props) => {......} What is the most effective approach to accomplish this? ...

Navigating horizontally to find a particular element

I developed a unique Angular component resembling a tree structure. The design includes multiple branches and nodes in alternating colors, with the selected node marked by a blue dot. https://i.stack.imgur.com/fChWu.png Key features to note: The tree&ap ...

Tips on effectively rendering child components conditionally in React

My components currently consist of an AddBookPanel containing the AddBookForm. I am looking to implement a feature where the form is displayed upon clicking the 'AddBookButton', and hidden when the 'x' button (image within AddBookForm c ...

Behavior of Shadow DOM role when using the <a> element without an href attribute

Recently, I started working with the shadow DOM and encountered a strange issue: In my Ionic Angular application, there is a text styled like a link in this form (simplified): <a href="${ifDefined(this.href)}">link</a> When testing ...

The issue with Angular's Mat Option selected values not functioning properly

We have a scenario where there are two form fields, and the second field needs to be disabled or enabled based on the selected value from the first field. The first field contains 5 values: 'a', 'b', 'c', 'd', ' ...

The current date is cycling back to the month before

There is a datetime received from my api as 2018-09-01T00:00:00.000Z, referred to as frame.scandate. Another date is generated within the program as 2018-09, simply known as scandate. These examples can represent any year/month combination. In my code: ...

Utilize the identical function within the reducer for numerous mat-slide-toggle and checkboxes in component.html

I'm currently diving into the world of Angular and ngrx while tackling a project focused on enabling users to create forms. In this project, users can add various form elements (such as labels, text fields, dropdown menus, checkboxes, etc.) from a sid ...

Listening for Angular 2 router events

How can I detect state changes in Angular 2 router? In Angular 1.x, I used the following event: $rootScope.$on('$stateChangeStart', function(event,toState,toParams,fromState,fromParams, options){ ... }) In Angular 2, using the window.addEv ...

Fix the TypeScript issue encountered during a CDK upgrade process

After upgrading to version 2.0 of CDK and running npm install, I encountered an issue with the code line Name: 'application-name'. const nonplclAppNames = configs['nonplclAppNames'].split(','); let nonplclAppNamesMatchingState ...

Creating React components with TypeScript: Defining components such as Foo and Foo.Bar

I have a react component defined in TypeScript and I would like to export it as an object so that I can add a new component to it. interface IFooProps { title:string } interface IBarProps { content:string } const Foo:React.FC<IFooProps> = ({ ...

Using React hooks and Typescript: I was expecting to see an assignment or function call, but instead, an expression was

After working as a React developer for quite some time, my workplace recently introduced Typescript, which I am still getting familiar with. I implemented a custom hook for managing cookies, but the function it returns is generating an error. Here's ...

Step-by-step guide on importing CSS into TypeScript

I have a global CSS file where I've defined all the colors. I attempted to import that value into TypeScript but it didn't work. This is my latest attempt: get sideWindowStyle(): any { switch (this.windowStyle) { case 'classicStyl ...

Generating a d.ts file for images in Typescript using automation techniques

Currently, I am working on a React application that utilizes TypeScript and webpack. I am aware that in TypeScript, when importing an image file, it is necessary to create a d.ts file in the current directory and include the following code: // index.d.ts ...