Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I import a library into node without a Typescript/TSD definition?

I'm trying to use a session helper called connect-session-knex which is obscure enough that it does not have a published typescript definition. So when I try to compile my typescript node project, I get the error,

error TS2307 Cannot find module 'connect-session-knex'

Is there a way to ignore TS for this module only? How do I import it without the TSD? I know knex has a tsd, but the wrapper does not. I'm asking this from a generic standpoint of what to do with libraries without type definitions.

For anyone looking: Compiling typescript when it does not have tsd. Missing tsd. Without tsd.

like image 622
FlavorScape Avatar asked Aug 24 '15 00:08

FlavorScape


People also ask

How do I use external plain JavaScript libraries in TypeScript projects?

First include the library source file before the compiled TypeScript file of your project ,using script tag in your HTML file . declare var libGlobal: any; You need to replace libGlobal with your library global object which gives access to the library API . Then just use any library function just like normal .

What is ESM in TypeScript?

ESM is an important step in the JavaScript ecosystem because it allows static analysis of the dependency tree. For bundlers such as Webpack, this is huge as it allows the compiled bundle only to contain code that is required at runtime, which means a smaller download size when loading code over the network.


2 Answers

error TS2307 Cannot find module 'connect-session-knex' Is there a way to ignore TS for this module only? How do I import it without the TSD?

Use var/require instead of import/require. i.e.

var csk = require('connect-session-knex');

Note you should have node.d.ts included for require to be declared.

Also : https://basarat.gitbooks.io/typescript/content/docs/node/nodejs.html

like image 101
basarat Avatar answered Sep 30 '22 14:09

basarat


Another suggestion is to start you own .d.ts file as an empty definition file and export the module. Then if you want to get intellisense on the module you can add definitions to it.

e.g. connect-session-knex.d.ts:


// declare module
declare module "connect-session-knex" {

}
like image 42
Quango Avatar answered Sep 30 '22 13:09

Quango