简体   繁体   中英

How to roughly import .js libraries without type declaration in typescript?

I'm using Vue.js with cli and starting project on Typescript. I didn't have any problem with it except of cases when I have to use js libraries. I know about this https://github.com/DefinitelyTyped/DefinitelyTyped and I use it when possible. But there is one big problem when js library is new, old or unpopular and has no type definitions. I spend a lot of time, looking for solution and it seems like there is only few of options:

In my case first option is unavailable. Second - very depends on library, which may have difficult structure to declare. So, what I can do if I want just import js library as is? I tried these ways:

import { } from 'velocity-animate';
import Velocity from 'velocity-animate';
import { Velocity } from 'velocity-animate';
import Velocity from '../../node_modules/velocity-animate';
import * as Velocity from 'velocity-animate';
const Velocity = require('velocity-animate');
const Velocity: any = require('velocity-animate');
const Velocity = require('../../node_modules/velocity-animate/velocity.js');

Also, tried add different variations and combinations with imports above like:

declare var Velocity: any;
declare module 'velocity-animate';

etc. And nothing, I just have errors in console like:

Uncaught ReferenceError: Velocity is not defined

It's not my typo in code, in regular js same code works fine ie https://codepen.io/anon/pen/YLBZMd

Another my suspicion is tscompiler and his rules/settings. Here is mine:

{
  "compilerOptions": {
    "target": "es2015",
    "module": "es2015",
    "strict": true,
    "allowJs": true,
    "jsx": "preserve",
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "noImplicitAny": false,
    "types": [
      "node",
      "googlemaps"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    }
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.vue",
    "tests/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

Can someone explain me what I'm doing wrong? Why so simple thing causes so big problems?

Uncaught ReferenceError: Velocity is not defined

This is a runtime error not a compile time typescript error .

Fix

Make sure Velocity global is available. eg add : https://raw.githubusercontent.com/julianshapiro/velocity/master/velocity.min.js as a script tag before your application code runs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM