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

2

7

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.

Foxtail answered 24/8, 2015 at 0:58 Comment(1)
See typescriptlang.org/docs/handbook/release-notes/…, especially Untyped importsBrotherhood
A
13

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

Argos answered 24/8, 2015 at 1:51 Comment(0)
R
5

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" {

}
Raymonraymond answered 24/8, 2015 at 7:52 Comment(4)
How can I connect node_module with my definition file?Seville
Do not quite understand the question @SebastianBusekRaymonraymond
For example with connect-session-knex; I can create file connect-session-knex.d.ts and then add use import * as connectSessionKnex from "connect-session-knex" but how TS transcripter will know that connect-session-knex.d.ts is matching with module connect-session-knex in node_modules directory?Seville
This is controlled by node module resolution. The .d.ts file just tells TypeScript what the module looks like (types, commands etc). It's node that actually connects to the .js file. More at typescriptlang.org/docs/handbook/module-resolution.htmlRaymonraymond

© 2022 - 2024 — McMap. All rights reserved.