Incorporate typings into your CDN integration

I'm interested in utilizing a CDN to access a JSON validation library, as it's expected to provide faster performance (due to retrieving the file from the nearest server within the CDN).

The JSON validation library in question can be found here: https://github.com/epoberezkin/ajv#using-in-browser

Upon clicking on the link, I was directed to this CDN:

To integrate it into my HTML code:

<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/4.10.4/ajv.min.js" integrity="sha256-LtA3VfycAam30/5e2Fq1f2tg8eIiFMOVWp1NDd6jmUU=" crossorigin="anonymous"></script>
</head>

Next, regarding typings... I executed

npm install --save-dev @types/ajv
and the installation went smoothly.

The path to the package.json file for @types/ajv is:

{
  "_args": [
    [
      {
        "raw": "@types/ajv",
        "scope": "@types",
        "escapedName": "@types%2fajv",
        "name": "@types/ajv",
        "rawSpec": "",
        "spec": "latest",
        "type": "tag"
      },
      "C:\\Users\\si556577\\Documents\\SSWebApp\\app\\Iag.DI.Web.SupplierApp"
    ]
  ],
  "_from": "@types/ajv@latest",
  "_id": "@types/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3253584472031c021c02">[email protected]</a>",
  "_inCache": true,
  "_installable": true,
  "_location": "/@types/ajv",
  "_npmOperationalInternal": {
    "host": "packages-12-west.internal.npmjs.com",
    "tmp": "tmp/ajv-1.0.0.tgz_1482502603556_0.6872997884638608"
  },
  "_npmUser": {
    "name": "types",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="681c1b45061805451c11180d1b2805010b1a071b070e1c460b0705">[email protected]</a>"
  },
  "_phantomChildren": {},
  "_requested": {
    "raw": "@types/ajv",
    "scope": "@types",
    "escapedName": "@types%2fajv",
    "name": "@types/ajv",
    "rawSpec": "",
    "spec&q...

This also resulted in an addition to the package.json file:

"devDependencies": {
    "@types/ajv": "^1.0.0",

In my actual code, I utilize these typings like so:

validateJSONSchema(json) {
    var ajv = new Ajv();
    var valid = ajv.validate(this.schema, json);
    if (!valid) {
        console.log(ajv.errors);
        return false;
    } else {
        return true;
    }
}

While the code functions correctly, I encountered a compile-time error in VS Code: Cannot find name "Ajv"

Is there a way to resolve this issue with the typings? My experience with typings has only involved locally installed packages rather than CDNs. Can typings even function properly when a CDN is being used?

Answer №1

Within the package.json file of ajv, it is mentioned that @types/ajv is now deprecated and the typings are included within the package itself:

The types definition for ajv (https://github.com/epoberezkin/ajv) has been stubbed. Ajv provides its own type definitions, eliminating the need for @types/ajv installation!

However, the included typings within the package should be utilized in this manner:

import * as Ajv from "ajv";
let ajv = new Ajv(...);

TypeScript will not accept these typings without the use of import statements.

This implies that configuring your module bundler is necessary if you intend to utilize the CDN. Simply including the CDN via <script> tag will not make Ajv globally available.

The method for doing so varies based on the bundler being used.

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

While performing compilation, Angular's ngFor triggers an error when used with SVG elements

I am attempting to create a recursive function of lines in order to generate a graph, but I am encountering a strange error in the console. It works fine on node.js. Below is the code snippet: <svg height = "200" width = "300"> ...

invoking a method within an express route to retrieve and utilize middleware functions

For my project, I am working on a custom function to handle API request validation. Here is how it looks: export function validateBody(schema: string): (req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => void { return function ...

Limiting the character input in ion-textarea within Ionic 2: A step-by-step guide

In my Ionic 2 application, I need to limit user comments to less than 500 characters in a text area. What is the best way to implement this restriction? ...

Issues with getOptionLabel in Material UI

I have a constant with the following values : const Reference = [ { label: "RF-100", year: "Test" }, { label: "RF-200", year: "Test2" }, { label: "RF-300", year: "Test3" }, ]; and my Autoco ...

Typescript is failing to perform type checking

I'm encountering an issue while trying to utilize TypeScript type checking with the following code snippet: abstract class Mammal { abstract breed(other: Mammal); } class Dog extends Mammal { breed(other: Dog) {} } class Cat extends Mammal { ...

Accessing React.FC in Another File with TypeScript - A Step-by-Step Guide

code - const Exne: React.FC <IProps> = ({x}) => { console.log('input', x); const [getx, assignx] = useState(x); console.log(getx, assignx); return(getx) }; Could you please provide instructions on how to acc ...

Will adding additional line breaks increase the overall length of the code?

Currently, I am immersed in a project involving Angular 4 and TypeScript. Recently, I came across a video showcasing how VSCODE can enhance the code's appearance. Intrigued, I installed the prettier plugin to achieve the same effect. Running this tool ...

Angular - Enhance User Experience with Persistent Autocomplete Suggestions Displayed

Is there a way to keep the autocomplete panel constantly enabled without needing to specifically focus on the input field? I attempted to set autofocus on the input, but found it to be clunky and the panel could still disappear if I hit escape. I also ...

An issue has occurred while utilizing Angular

I'm diving into the world of Angular and encountering some errors as I try to execute this code. An unexpected token is causing trouble. A constructor, method, accessor, or property was expected. The left side of a comma operator seems to be unused ...

IDE type inferences are wrong for the Polymorphic React component

declare const MyComponent = <A extends {id: bigint|number}>(props: MyProps<A>) => React.FC<{}> interface MyProps<A extends {id: number}> { data: A[] orderBy: keyof A } declare const x: { id: number, foo: string }[] const F ...

A guide on efficiently utilizing combineLatest and mergeMap for handling multiple subscriptions

As I continue to delve into the world of rxjs, I've encountered an issue with managing multiple subscriptions. Specifically, I'm struggling to extract an ID from a response in order to correctly associate photos with products. create(product) { ...

After calling the service, Angular 2 is unable to perform any actions within the subscribe method

I am struggling with what to do after authenticating my user. Once I receive the data, I want to redirect them to the appropriate page based on their role and display their name on that page. I have tried various methods, but it seems like when I try to ca ...

Are there any solutions to refresh a page by clicking a button in next.js?

I am currently learning how to work with next.js and I'm facing an issue where I need to reload my page to make a new API request. As a beginner, I'm not sure how to achieve this. I've tried a few methods but none of them seem to work. Below ...

An issue occurred at line 2, character 16 in the generateReport.service.ts file: TypeScript error TS2580 - The term 'require' is not recognized

I have a requirement in my app to generate a report in the form of a Word document with just a click of a button. Previously, I successfully accomplished this using the "officeGen" module in a separate project. You can find more information about the modul ...

Incorporating a new function into a TypeScript (JavaScript) class method

Is it possible to add a method to a method within a class? class MyClass { public foo(text: string): string { return text + ' FOO!' } // Looking for a way to dynamically add the method `bar` to `foo`. } const obj = new MyCl ...

Using ES6 import declarations within a Node.js application enhanced with Babel and Typescript

Problem with using ES6 import syntax in TypeScript file: import express from "express" const app = express() app.listen(3000, () => console.log("Example app listening on port 3000!!")) Solution using .babelrc: { "presets": ["@babel/preset-typescr ...

Angular 4 enum string mapping reversed

Here is an example of a string enum: export enum TokenLength { SIX = '6', EIGHT = '8', } I am trying to retrieve the string value 'SIX' or 'EIGHT' by reverse mapping this enum. I have attempted various methods: ...

What is the best way to invoke a method in a child component from its parent, before the child component has been rendered?

Within my application, I have a parent component and a child component responsible for adding and updating tiles using a pop-up component. The "Add" button is located in the parent component, while the update functionality is in the child component. When ...

Material UI React Autocomplete Component

I'm currently working on integrating an Autocomplete component using the Material UI library. However, I've encountered a challenge - I'm unsure of how to properly pass the value and onChange functions, especially since I have a custom Text ...

Unable to bring in an exported class from a TypeScript file

I have a TypeScript file named foo.ts that contains an exported class called "Foo" export default class Foo{ } I am attempting to import this class into another file within the same directory import {Foo} from './foo'; However, I am encounter ...