disable wrong typescript error - javascript

I have installed 'interact.js' with jspm (and npm for typescript to be happy). The app runs fine but my code shows errors:
import { interact } from 'interact.js/interact'
// ==> typescript error: TS2307: Cannot find module 'interact.js/interact'
I suppose the problem has something to do with the npm module containing '.js' but I am not sure. Anyway, is there a way to fix this either by
A. Help Typescript find the module
B. Disable this specific error (since it works fine)
PS: here is my tsconfig.json file:
{ "exclude":
[ "node_modules"
, "jspm_packages"
, ".git"
, "typings/browser"
, "typings/browser.d.ts"
]
, "compilerOptions":
{ "outDir": "dist"
, "target": "es5"
, "sourceMap": true
, "experimentalDecorators": true
}
, "compileOnSave": false
}

The TypeScript compiler/language service doesn't actually resolve module names through the filesystem or your package.json like you might expect - it instead uses the definition (.d.ts) files that define the type information.
While it's not the most intuitive thing in the world, their reasoning for it wasn't entirely unreasonable - without a definition file, it's impossible to know what type the thing being imported is, and they were somewhat cagey about making the compiler default to just setting imports to the any type.
So in short, the solution to this problem is simply to install the definition files if available, or write/stub out your own if not. They'll be making this easier in TypeScript 2.0 by the sounds of it, but even as it stands, it takes very code to create a dummy definition:
declare module "interact.js/interact" {
export var interact: any;
}

Related

TypeScript: Pixi.js types with 'none' Module Settings

I have a 100% JS project that runs in the browser with about 20 JS files or so that have all function names in the global scope. Currently I can just modify a JS file and refresh and immediately see the change.
However, I would like the benefits of static type checking; enter TypeScript. I added type annotations to variables and functions and set module to none. This works well! tsc will read in the .ts, do type checking, and then emit the same .js I had previously which I can run in-browser with no modifications.
The problem is when I want to integrate with a 3rd party library. In my case, pixi.js.
If I try to do something like let x = PIXI.settings.TARGET_FPMS;, then tsc complains Cannot find name 'PIXI'. I tried adding /// <reference path="pixi.min.js"/>, and while the path resolves, it still can't find the name.
Solutions online suggest I do npm install pixi.js and then import * as PIXI from 'pixi.js'. However, if I do that, I can no longer use the none module setting which means now I have to put import and export statements everywhere, which means the emitted .js files now have browser-incompatible require or import statements, which means now I need webpack or something to get rid of those, etc... the complexity is ballooning.
Is there a way have TypeScript access pixi.js type information without all the import/export/modules/webpack business? Basically I just want tsc to check that the shape of things is correct without radically changing the current app architecture.
Barring that, it seems like the only solution is to add: declare var PIXI: any; somewhere in the file.
From an HN post:
Here is a minimum "repro" of your use case:
tsconfig.json
{
"include": ["index.d.ts"],
"compilerOptions": {
"target": "es2015",
"lib": ["es2015", "dom"],
"moduleResolution": "node",
"allowSyntheticDefaultImports": true
}
}
index.d.ts
import * as PIXI from 'pixi.js'
declare global {
interface Window {
PIXI: typeof PIXI
}
}
index.ts
console.log(window.PIXI)
There is still an import but because it is in the .d.ts file it won't
be included in the runtime code.

Implicit VSCode Intellisense no longer work after renaming the JS file

Earlier, I have two JS files:
old-file.js
new-file.js
I later noticed that my app.js' intellisense was always referring to the old-file.js but not the new-file.js, so I deleted the old-file.js (as though I've renamed the old file). But now, when working on my app.js, the intellisense has gone missing, which means VSCode does not automatically make use of the definitions in the new-file.js, which has the same and also additional object declarations.
I tried looking for my Typescript and JavaScript Language Features built-in extension but can't find it in my VSCode. I also restarted my VSCode many times but still not working. My jsconfig.json looks fine in the project root folder as shown below:
{
"compilerOptions": {
"module": "commonjs",
"target": "es2016",
"jsx": "preserve"
},
"exclude": [
"node_modules",
"**/node_modules/*"
],
"typeAcquisition": {
"include": [
"jquery",
"angular"
]
}
}
Note that I was talking about the "implicit intellisense" of VSCode across external files, no import statements, nothing. Also note that my app.js and new-file.js will always be merged as app.min.js by terser at the later stage. Does anyone know what happen to my situation and how can I restore the intellisense of my new-file.js and put it back to work like the old one? Many thanks!

How to import typescript file from outside of the project folder [duplicate]

Let's say I have two projects with following file structure
/my-projects/
/project-a/
lib.ts
app.ts
tsconfig.json
/project-b/
app.ts // import '../project-a/lib.ts'
tsconfig.json
I want to consume lib.ts located in project-a also from project-b. How to do that?
Release it as NPM module - absolutely don't want that, it's an overkill for such a simple use case. I just
want to share one file between two projects.
Use import '../project-a/lib.ts' - doesn't work, TypeScript complains
'lib.ts' is not under 'rootDir'. 'rootDir' is expected to contain all source files.
Put tsconfig.json one level up so it would cover both project-a and project-b - can't do that, the TypeScript config is slightly different for those projects. Also it's not very convenient, don't want to do that.
Any other ways?
Since Typescript 3.0 this can be done with Project References.
Typescript docs: https://www.typescriptlang.org/docs/handbook/project-references.html
I believe you would have to move lib.ts into a small ts project called something like 'lib'
The lib project should have a tsconfig containing:
// lib/tsconfig.json
{
"compilerOptions": {
/* Truncated compiler options to list only relevant options */
"declaration": true,
"declarationMap": true,
"rootDir": ".",
"composite": true,
},
"references": [] // * Any project that is referenced must itself have a `references` array (which may be empty).
}
Then in both project-a and project-b add the reference to this lib project into your tsconfig
// project-a/ts-config.json
// project-b/ts-config.json
{
"compilerOptions": {
"target": "es5",
"module": "es2015",
"moduleResolution": "node"
// ...
},
"references": [
{
"path": "../lib",
// add 'prepend' if you want to include the referenced project in your output file
"prepend": true,
}
]
}
In the lib project. Create a file index.ts which should export all your code you want to share with other projects.
// lib/index.ts
export * from 'lib.ts';
Now, let's say lib/lib.ts looks like this:
// lib/lib.ts
export const log = (message: string) => console.log(message);
You can now import the log function from lib/lib.ts in both project-a and project-b
// project-a/app.ts
// project-b/app.ts
import { log } from '../lib';
log("This is a message");
Before your intelissense will work, you now need to build both your project-a and project-b using:
tsc -b
Which will first build your project references (lib in this case) and then build the current project (project-a or project-b).
The typescript compiler will not look at the actual typescript files from lib. Instead it will only use the typescript declaration files (*.d.ts) generated when building the lib project.
That's why your lib/tsconfig.json file must contain:
"declaration": true,
However, if you navigate to the definition of the log function in project-a/app.ts using F12 key in Visual Studio code, you'll be shown the correct typescript file.
At least, if you have correctly setup your lib/tsconfig.json with:
"declarationMap": true,
I've create a small github repo demonstrating this example of project references with typescript:
https://github.com/thdk/TS3-projects-references-example
This can be achieved with use of 'paths' property of 'CompilerOptions' in tsconfig.json
{
"compilerOptions": {
"paths": {
"#otherProject/*": [
"../otherProject/src/*"
]
}
},
}
Below is a screenshot of folder structure.
Below is content of tsconfig.json which references other ts-project
{
"compilerOptions": {
"baseUrl": "./",
"outDir": "./tsc-out",
"sourceMap": false,
"declaration": false,
"moduleResolution": "node",
"module": "es6",
"target": "es5",
"typeRoots": [
"node_modules/#types"
],
"lib": [
"es2017",
"dom"
],
"paths": {
"#src/*": [ "src/*" ],
"#qc/*": [
"../Pti.Web/ClientApp/src/app/*"
]
}
},
"exclude": [
"node_modules",
"dist",
"tsc-out"
]
}
Below is import statement to reference exports from other project.
import { IntegrationMessageState } from '#qc/shared/states/integration-message.state';
I think that #qqilihq is on the right track with their response - Although there are the noted potential problems with manually maintaining the contents of a node_modules directory.
I've had some luck managing this by using lerna (although there are a number of other similar tools out there, for example yarn workspaces seem to be somewhat similar, although I've not used them myself).
I'll just say upfront that this might be a little heavyweight for what you're talking about, but it does give your project a lot of flexibility to grow in the future.
With this pattern, your code would end up looking something like:
/my-projects/
/common-code/
lib.ts
tsconfig.json
package.json
/project-a/
app.ts (Can import common-code)
tsconfig.json
package.json (with a dependency on common-code)
/project-b/
app.ts (Can import common-code)
tsconfig.json
package.json (with a dependency on common-code)
The general theory here is that the tool creates symlinks between your internal libraries and the node_modules directories of their dependant packages.
The main pitfalls I've encountered doing this are
common-code has to have both a main and types property set in its package.json file
common-code has to be compiled before any of its dependencies can rely on it
common-code has to have declaration set to true in its tsconfig.json
My general experience with this has been pretty positive, as once you've got the basic idea understood, there's very little 'magic' in it, its simply a set of standard node packages that happen to share a directory.
Since I'm the only dev working on 2 projects which require some shared code folder I've setup a 2-way real time sync between the common code shared folders.
project A
- shared/ -> 2-way sync with project B
- abc/
project B
- shared/ -> 2-way sync with project A
- xyz/
It's a one-time quick setup but gives benefits like:
no hassle of configuring and managing mono-repo/multiple tsconfig
no build step to get latest code, works instantly
works with cloud build tools as shared code is inside repo instead of symlink
easier to debug locally as all files are within the project
I can further put checks on shared folder with commit hooks/husky and throw warnings etc.
And in-case if I want to collaborate with other team members, I can mention to use this sync tool as part of project setup.
It seems we've got a few options here:
(1) Put both projects in a mono repo and use answer given by #ThdK using TS project references
NOT GOOD if you don't want a mono repo
(2) Use Lerna - see answer by #metric_caution
NOT GOOD if you can't be bothered to learn Lerna / don't want to publish your shared files to npm
(3) Create a shared npm package
NOT GOOD if you don't want to publish your shared files to npm
(4) Put shared folders in a "shared" directory in project A and write a script to copy files in the shared folder from project A to project B's shared folder that is executed on a git push OR a script to sync the two folders.
Here the script can be executed manually when copying / syncing is required. The copying / syncing could also be done prior to a git push using husky and the shared files added to git automatically in the script.
Since I don't want a mono repo and I can't be bothered to publish an npm package for such a pathetic purpose I'm gonna go with option 4 myself.
In a similar scenario, where I also wanted to avoid the overhead of having to perform an NPM release, I went for the following structure (after lots of trial and error and failed attempts):
/my-projects/
/node_modules/
/my-lib/
lib.ts
tsconfig.json
package.json
/project-a/
app.ts
tsconfig.json
/project-b/
app.ts
tsconfig.json
The central idea is to move the shared stuff to a node_modules directory above the individual projects (this exploits NPMs loading mechanism, which would start looking for dependencies in the current directory and then move upwards).
So, project-a and project-b can now access the lib simply via import { Whatever } from 'my-lib'.
Notes:
In my case, my-lib is actually only for shared typings (i.e. .d.ts files within a lib subdirectory). This means, I do not explicitly need to build my-lib and my my-lib/package.json looks as follows:
{
"name": "my-types",
"version": "0.0.0",
"private": true,
"types": "lib/index"
}
In case my-lib contains runnable code, you’ll obviously need to build my-lib, so that .js files are generated, and add a "main" property to the package.json which exposes the main .js file.
Most important: Despite its name, /my-projects/node_modules only contains custom code, no installed dependencies (they are actually in the individual projects project-a/node_modules and project-b/node_modules). This means, there’s an explicit git ignore setting, which un-ignores the /node_modules directory from being committed.
Is this a clean solution? Probably not not. Did it solve my issue? Yes. Am I happy to hear about improvement suggestions? Absolutely!
I switched to deno. Code sharing in TypeScript projects is easy, at long last.

TypeScript use noImplicitAny with Javascript sources

I want to enable the noImplicitAny flag in my compiler.
My problem is that I use lodash/fp and there is no typings so far.
So the compiler complains about the lack of definition file for lodash/fp.
Is there a way to allow implicit any only for external js files ? Or to whitelist a subdirectory like node_modules ?
The way I get around this is by creating a file where I declare the modules I want to use that have no typings. For example I would create a file called modules.ts, and there simple decalre the module I want to use like so: declare module 'name-of-module'. Now on any file I want to use my non typed module I can simply import my modules.ts and then the module I want to use using the import * as syntax. What this does is change it from implicit any to explicit any, but this of course will not give you typings for these modules, it simply allows to you to use them.
In your tsconfig.json you should have the following:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"noResolve": true,
"sourceMap": true,
"noImplicitAny": true,
"removeComments": true,
"experimentalDecorators": true
},
"exclude": [
"node_modules"
]
}
This should prevent the node_modules folder from being compiled to JavaScript as they're most likely already JavaScript.
If the "files" and "include" are both left unspecified, the compiler defaults to including all TypeScript (.ts, .d.ts and .tsx) files in the containing directory and subdirectories except those excluded using the "exclude" property.
See the main TypeScript site here
You can create a declaration file with ".d.ts" extension like ambient-modules.d.ts
Add the following line in this file
declare module '*';
And you're done!
Now, you still get the benefits of noImplicitAny flag without worrying about the other js files which don't have any types available.
For more info, you can refer here

vscode rich editing support - does not always follow require()

I am using VS Code 1.2.1 and learning how the rich editing support works for javascript. (intellisense, peek, go to definition, etc)
There are two situations where vscode does successfully load the require()-ed module, but one situation that it does not provide any rich editing support. Here is an example w/ comments:
// vscode knows about var _ because I already did
// $ typings install lodash
var _ = require('lodash');
// vscode knows about var fu, because the test.js is in project context.
var fu = require('./test.js');
// vscode is unaware of var tree, even though I copied the src into the
// project context.
// $ cp -r node_modules/tnt.tree/src lib/tnt.tree
var tree = require('tnt.tree');
console.log(tree); // ok
The last one, tnt.tree is giving me trouble. The code above does successfully build with webpack, and run OK. But vscode says the variable tree is 'any', with no additional info.
Finally, here is my jsconfig.json:
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"diagnostics": true,
"allowSyntheticDefaultImports": true
},
"exclude": [
"node_modules",
"dist"
]
}
Summary: there are no typings for tnt.tree. So I copied the module of interest (tnt.tree) out of node_modules and into a lib/ directory, to try to make vscode aware of it in the project context. But that doesn't seem to work. Any pointers would be greatly appreciated, as I am sure this is a problem I will revisit over and over when trying to learn new Js modules.
I filed a bug with the vscode team, and they reassigned it to the typescript team. So this sounds like a bug with the editor itself:
IntelliSense based on type inference not working in node_modules?
https://github.com/Microsoft/TypeScript/issues/9323

Categories