Could not find a declaration file for module 'vimeo' - javascript

I'm using typescript v^3.4.2, in an express app (^4.14.1), using node v11.3.0.
When I run my build for typescript, I get the following error:
Could not find a declaration file for module 'vimeo'. '/Users/me/Code/MyServer/node_modules/vimeo/index.js' implicitly has an 'any' type.
Try `npm install #types/vimeo` if it exists or add a new declaration (.d.ts) file containing `declare module 'vimeo';`
1 import { Vimeo } from "vimeo";
I am using the Vimeo api client for nodejs vimeo.js, version 2.1.1.
I've attempted to run yarn add --dev #types/vimeo, but unfortunately that library is for the other vimeo library, vimeo/player.js. Installing it is of no use.
I've tried to follow this article on creating my own custom type declaration.
Here is my tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"noImplicitAny": true,
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
"paths": {
"*": ["node_modules/*"]
},
"typeRoots": ["./types", "./node_modules/#types"]
},
"include": ["src/**/*", "controllers/**/*", "routes/**/*", "models/**/*"],
"exclude": ["node_modules", "types"]
}
And I've created: /Users/me/Code/MyServer/types/vimeo/vimeo.d.ts, which contains:
declare module vimeo {}
When I add that the error changes to:
yarn run v1.15.2
$ yarn build
$ tslint -c tslint.json -p tsconfig.json --fix
$ tsc
error TS2688: Cannot find type definition file for 'vimeo'.
The article also suggests adding a root global.d.ts with the same definition in it, but that has no effect.
I'm stumped. Any help would be appreciated.
(This is my package.json scripts block:)
"main": "dist/app.js",
"scripts": {
"prebuild": "tslint -c tslint.json -p tsconfig.json --fix",
"build": "tsc",
"prestart": "yarn build",
"start": "babel-node dist/app.js --presets es2015",
"test": "echo \"Error: no test specified\" && exit 1"
},
And here's my tslint.json:
{
"defaultSeverity": "error",
"extends": ["tslint:recommended"],
"jsRules": {},
"rules": {
"trailing-comma": [false],
"curly": [true, "ignore-same-line"],
"ban-types": false
},
"rulesDirectory": []
}

If I recall correctly, setting "noImplicityAny": false, can solve the issue of declaration files... or you can look for some .d.ts for that module (or even make your own and do a pull request in GitHub)

Related

Enabling the use of a mixture of Typescript and JS in a Node Project

In an existing node project written in JS we're trying to enable the use of Typescript so we can use it in our ongoing refactoring.
I've added a tsConfig like so:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"sourceMap": true,
"rootDir": "./",
"outDir": "./tsOutput",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true
},
"include": ["./"]
}
I've also installed the following as dev dependencies:
"#types/express": "^4.17.14",
"#types/node": "^18.11.9",
"#types/node-fetch": "^2.6.2",
"ts-node": "^10.9.1",
"ts-node-dev": "^2.0.0",
"typescript": "^4.9.3"
And I run tsc on build, which runs and generates a js and mapping file. I've run tried this both outputting to a separate directory and removing the outDir in the tsConfig.
To test it works, I added the following class in my test project:
class ExampleClass {
logSomeStuff(stringToLog : string, numberToLog : number, booleanToLog : boolean)
{
console.log(stringToLog);
console.log(numberToLog);
console.log(booleanToLog);
}
}
export default ExampleClass;
Consume it with this JS file:
const { Example } = require("./Example.ts");
function TypescriptConsumerExample() {
const blah = new Example();
blah.logSomeStuff("String", 2, false);
}
module.exports = TypescriptConsumerExample;
And attempt to run this JS test:
const TypescriptConsumerExample = require("../TSExample/TSConsumerExample");
describe("TS test", () => {
it("Should be able to call TS code", () => {
TypescriptConsumerExample();
console.log("Built");
});
});
But I get this warning, which implies that it doesn't understand what TS is:
logSomeStuff(stringToLog : string, numberToLog : number, booleanToLog : boolean)
^
SyntaxError: Unexpected token ':'
Equally, if I run the main project and try and call this TS class from index.js:
function TSTest()
{
console.log("Success!");
}
export default TSTest;
I get this error:
TypeError: TSTest is not a function at Object.<anonymous>
Your tsconfig.json probably should have allowJs: true to allow js in the project at all.
Use tsx watch --inspect src/server for development, tsx src/server to launch.
tsx allows running whatever import/require js/ts modules at once (conpability list)
I would recomment you to convert the entire project into .ts first (by renaming), so file extensions are consistent, in one big git commit, so blame don't break on files that were renamed and edited at once
Two ways you can go about this. You can set a script in your package.json to compile the TS and then run that compiled typescript like so:
"scripts": { "start": "tsc && node dist/server.js" },
Alternatively, nodemon is a super useful tool that you may already be using..and it understands typescript. You can set another script like so:
"dev": "npx nodemon ./src/server.ts",
This article by Cole Gawin goes into the details of standing up the latter https://blog.logrocket.com/configuring-nodemon-with-typescript/
In addition to the answer provided by Dimava - adding the allowJs flag to tsconfig.json, it also turned out I missed changing this line in package.json to point to the outputs index.js file:
"main": "./tsOutput/index.js",
In combination with the following:
"scripts": {
"start": "tsc && node --unhandled-rejections=warn ./tsOutput/index.js",
"dev": "tsc && node --unhandled-rejections=warn ./tsOutput/index.js",

How to ignore files with #swc/cli?

I am using swc to transpile my Typescript code on a side project and am struggling ignoring the tests files from the final output using the cli --ignore option.
lib versions:
#swc/cli: ^0.1.57
#swc/core: ^1.2.173
command:
swc ./src --out-dir dist --ignore **/*.test.ts
.swrc config
{
"jsc": {
"target": "es5",
"paths": {
"#src/*": ["./src/*"]
},
"parser": {
"syntax": "typescript",
"decorators": true,
"dynamicImport": true
}
},
"minify": true,
}
I still saw all tests files in my dist output folder. Note that using the exclude property in the .swcrc like this "exclude": [".*\\.spec|test\\.(j|t)s$", "mocks", "types"] works, but how is the --ignore arg supposed to be used ?

Creating a modular TypeScript library with classes

I have a Web API for which I want to build a library so that I don't need to write the same code in every new project I'm talking to this API.
I also want to split my code, so I have one class for each endpoint structure, so, for example, let's say I have multiple User endpoints which do stuff like
Register
Login
I would have one UserClient which offers both methods
export default class UserClient
{
register(email: string, password: string)
{
// code here
}
login(email: string, password: string, remember: bool)
{
// code here
}
}
So, I structured my code like this
package.json
tsconfig.json
--src
----api
------user-client.ts
----models
------user
--------logindata.ts
my tsconfig.json looks like this
{
"compilerOptions": {
"declaration": true,
"declarationDir": "./dist",
"module": "commonjs",
"noImplicitAny": true,
"lib": ["es2017", "es7", "es6", "dom"],
"outDir": "./dist",
"target": "es2015",
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
},
"typedocOptions": {
"mode": "modules",
"out": "docs"
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"dist"
]
}
and my package.json
{
"name": "xxx",
"version": "1.0.0",
"description": "xxx",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"/dist"
],
"repository": "xxx",
"author": "xxx",
"license": "MIT",
"private": true,
"scripts": {
"build": "tsc",
"prepare": "npm run build",
"test": "echo \"Error: no test specified\" && exit 1"
}
}
So what I can already see is that I say my main is dist/index.js and types are dist/index.d.ts and I don't have an index file
So I have multiple questions
Do I need an index.ts in src? If yes, what will be in there?
Do I need to change types to something else?
I basically want to have typings for every class I create and then use it in another library like
import {UserClient} from "myLib"
import {BooksClient} from "myLib"
However, when I now build my library with tsc it doesn't create an index.d.ts (since I don't have an index.ts) and just creates the user-client.js and user-client.d.ts directly in the dist folder (without respecting the existing structure) and I also coannot use them in my other library
Okay, so I fixed it. First of all, what we need is, that the client will be exported
so user-client.ts should look like this
export class UserClient
{
// code
}
Then, what I was missing (or doing wrong) in your index.ts you need to EXPORT instead of import the client
export {UserClient} from "./api/user-client"
Then, I built my files with the tsc command and then in my consuming library, I was able to use npm link ../jsapi and then simply use
import {UserClient} from 'jsapi'
without any problems.
I used this tutorial as a help: https://www.tsmean.com/articles/how-to-write-a-typescript-library/ but had to actually look at their https://github.com/bersling/typescript-library-starter/blob/master/library-starter/src/index.ts to get the correct answer

Package do not import correctly in project

I recently created a Typescript Package that I would like to test in an app before publishing on NPM.
The entry file (index.ts) looks like this =>
import Builder from './core/builder';
export default Builder;
Basically, there is many files, but I want the user to just use a "static" class Builder that I export in the index. so the user can just do import Builder from 'builderts'
My package.json folder is the following
"name": "builderts",
"main": "./dist/builderts.js",
"types": "./dist/builderts.d.ts",
"files": [
"dist/*"
],
"scripts": {
"preversion" : "npm run lint",
"prepare": "npm run build",
"prepublishOnly": "npm test && npm run lint",
"version" : "npm run format && git add -A src",
"postversion" : "git push && git push --tags",
"build": "tsc",
"watch": "tsc-watch",
"format": "prettier --write \"src/**/*.ts\" \"src/**/*.js\"",
"lint": "eslint tsconfig.json"
},
and my tsconfig.json
{
"compilerOptions": {
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "amd", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
"declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
"outFile":"./dist/builderts.js", /* Concatenate and emit output to single file. */
"outDir": "dist", /* Redirect output structure to the directory. */
"strict": true, /* Enable all strict type-checking options. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}
The problem I face is, I tried to create a small test project and install the module using
npm install absolute/path
it install correctly, but when I try to import the package using
import Builder from 'builderts';
I do not have neither autocompletion, and I have an error saying
File 'D:/User/Local/gitRepo/builderts/dist/builderts.d.ts' is not a module.
I do not quite understand what I am missing in the process.
Looks to me that you need to update the types in package.json
You stated above that the file name was index.ts, have you considered updating package.json ? :
{
...
"types": "./dist/index.ts",
...
}

TypeScript 2.1 Feature of Implicit Import Not Working

I was very excited about the latest TypeScript 2.1.4 release in that a big factor in convincing my team to use TS is the ability to import an installed module without having to find or create type definitions for it, which implicit any imports provide. For some reason, however, this doesn't seem to be working as advertised, as I still get error messages telling me that a module cannot be found. When I install types for my module (React in this case) it works just fine.
Here's my package.json:
{
"name": "my_app_name",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --colors --port 8282"
},
"dependencies": {
"react": "^15.4.1",
"react-dom": "^15.4.1"
},
"devDependencies": {
"awesome-typescript-loader": "^3.0.0-beta.9",
"source-map-loader": "^0.1.5",
"typescript": "^2.1.4",
"webpack": "^1.14.0",
"webpack-dev-server": "^1.16.2"
}
}
My tsconfig.json:
{
"compilerOptions": {
"outDir": "./dist/",
"module": "commonjs",
"target": "esnext",
"jsx": "react"
},
"include": [
"./**/*"
]
}
And a sample .tsx file for a React component that replicates this issue:
import * as React from "react";
export interface HelloProps { compiler: string; framework: string; }
export const Hello = (props: HelloProps) => {
return <h1>Hello from {props.compiler} and {this.props.framework}!</h1>
};
I also went ahead and created another project replicating this issue and uploaded it to BitBucket for anyone interested. Any help would be greatly appreciated. If this turns out to be an issue with TypeScript itself, I'll make sure to create an Issue on the Github repo.
Looks like implicit import does not always work. When I fixed your package.json (removed trailing comma in scripts) and tsconfig.json (added bin to exclude), I'm getting these errors with typescript 2.1.4:
src/greeter.tsx(2,24): error TS2307: Cannot find module 'react-modal'.
src/greeter.tsx(19,26): error TS2339: Property 'setState' does not exist on type 'Greeter'.
I think I khow the explanation for the first one. In package.json for react-modal, the main property is
"main": "./lib/index",
but the actual file has .js extension, that is, it's ./lib/index.js.
When I change main in node_modules/react-modal/package.json to
"main": "./lib/index.js",
the first error goes away.
I think it's indeed an issue with TypeScript.
try and add you tsconfig and enable and disable noImplicitAny :
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es2015", "dom"],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"typeRoots": [
"../../node_modules/#types/"
]
}
}

Categories

Resources