Using Nodejs with Typescript - javascript

I would like to use Nodejs in my typescript project and downloaded node.d.ts from https://github.com/borisyankov/DefinitelyTyped/tree/master/node
But VisualStudio finds a lot of errors in the .d.ts file. They're all basically the same:
Error 2 exported interface 'Server' extends interface from private
module 'events' C:\Users\lhk\Desktop\typescript-game\strategy
go\node\node-0.8.d.ts 236 37 node-0.8.d.ts
All the error messages complain that a private interface is extended.
I searched SO and found this question:
nodejs require inside TypeScript file
One of the comments gives the advice to download node.d.ts from the Microsoft samples. I browsed the internet, found this article http://stackful.io/blog/typescript-nodejs-vim-and-linux-oh-my/ and downloaded the second version of node.d.ts , with the exact same result.
Where do I find a proper definitions file for nodejs and Typescript ?

For the 0.8.1-1 version of TypeScript, use the latest node.d.ts file from this github project:
https://github.com/soywiz/typescript-node-definitions
I was getting the same exported interface errors until I pulled the latest definition files from there.

I'm not entirely sure what the heck is going on here.
I suspect that the current version of the (0.8.1~1) node.js package for Typescript broke some stuff. I've been running into this too. I tweaked the node.d.ts file and marked a couple things "export" instead of "declare" and that got me past my compilation issues, but I'm finding that the functions are not showing up in the current scope.
FWIW, I have been playing around with a personal fork of typescript-require and typescript-wrapper (both of which required some tweaking to work with 0.8.1~1) and I'm wasn't too certain that everything is working as well as it should be, so I wasn't sure that the issue is my issue or something endemic to the current node/typescript.

Related

How do I import Pixi.js into a TypeScript project?

I'm new to Pixi.js but I have some past experience with TypeScript. I'm really struggling to import Pixi.js into my project.
I got a small Pixi.js project running using a CDN import of Pixi and vanilla JavaScript, and now I'm trying to get that same project running on TypeScript. I think one of my options would be to use the CDN import of Pixi and then import the type definitions for Pixi, but I read in several places that the later versions of Pixi are already written in TypeScript, so I don't think it's a good option for me to use a JavaScript version of the library and then import my own TypeScript definitions.
I tried using npm install pixi.js and then import * as PIXI from "pixi.js"; but that gives me this TypeScript error:
This module is declared with using 'export =', and can only be used with a default import when using the 'allowSyntheticDefaultImports' flag.
and it also gives me this browser error when I force it to compile anyway:
Uncaught TypeError: Failed to resolve module specifier "pixi.js". Relative references must start with either "/", "./", or "../".
This error makes sense to me, because clearly telling the browser to find pixi.js will result in no file being found, since it's a Node.js module.
I tried changing import * as PIXI from "pixi.js"; to import PIXI from "pixi.js"; to get rid of the "only use default import" error, but that just gives me a "pixi.js has no default export" error, which seems to be in direct contrast with the error I was getting before, saying that it only has a default export...
And even if I manage to get rid of the TypeScript errors, I still can't wrap my head around how this would function properly anyway since the browser has no idea what "pixi.js" is when it's referring to a Node module that doesn't even exist inside the browser...
So all of this leads me to my question of how do I get a Pixi.js program running with TypeScript? I've looked up tutorials many times but every single one includes something like Webpack, Browserify, etc. I would not like to use any bundlers/other dependencies at all, I simply want to write TypeScript code, compile it, and have it give me some .js files that I can pop directly into a .html file and run in my browser. Is this possible?
My findings thus far have been that what I'm looking for is (somehow) not possible. I've found that my options are either to import the vanilla JavaScript version of Pixi and just go without type information (and do some hacky workarounds to get TypeScript to not think PIXI is undefined), or use a bundler like Webpack. Neither of those are ideal, and I have to think there's another option...
It would depend on your setup, but you could try something like this:
import { Sprite } from '#pixi/sprite';
new Sprite()
or you could try importing all as PIXI like this
import * as PIXI from 'pixi.js';
new PIXI.Sprite()
You must have figured this out but still I want this answer to be here for other to see.
This is my demo project on github that you can clone and use. It has typescript and pixi.js installed. THIS PROJECT USES VITE instead of webpack which is very complicated.
pxts :pixi.js setup library
Some of things you must keep in mind
Pixi.js version 6 has typescript types bundled along.
Most of the examples on line are old and out of date
Latest pixi version is v 7.x for which there is no community support yet.
link for version 6.5.8 docs
While working with version 6.x you have to install Assets separately where as in Version 7.x its bundled in.
OLD AND OUT OF DATE TUTORIALS ONLINE is the main reason for confusion. Do check which version you have got installed.

How to find dead code in a large react project?

In order to refactor a client-side project, i'm looking for a safe way to find (and delete) unused code.
What tools do you use to find unused/dead code in large react projects? Our product has been in development for some years, and it is getting very hard to manually detect code that is no longer in use. We do however try to delete as much unused code as possible.
Suggestions for general strategies/techniques (other than specific tools) are also appreciated.
Thank you
Solution:
For node projects, run the following command in your project root:
npx unimported
If you're using flow type annotations, you need to add the --flow flag:
npx unimported --flow
Source & docs: https://github.com/smeijer/unimported
Outcome:
Background
Just like the other answers, I've tried a lot of different libraries but never had real success.
I needed to find entire files that aren't being used. Not just functions or variables. For that, I already have my linter.
I've tried deadfile, unrequired, trucker, but all without success.
After searching for over a year, there was one thing left to do. Write something myself.
unimported starts at your entry point, and follows all your import/require statements. All code files that exist in your source folder, that aren't imported, are being reported.
Note, at this moment it only scans for source files. Not for images or other assets. As those are often "imported" in other ways (through tags or via css).
Also, it will have false positives. For example; sometimes we write scripts that are meant to simplify our development process, such as build steps. Those aren't directly imported.
Also, sometimes we install peer dependencies and our code doesn't directly import those. Those will be reported.
But for me, unimported is already very useful. I've removed a dozen of files from my projects. So it's definitely worth a shot.
If you have any troubles with it, please let me know. Trough github issues, or contact me on twitter: https://twitter.com/meijer_s
Solution for Webpack: UnusedWebpackPlugin
I work on a big front-end React project (1100+ js files) and stumbled upon the same problem: how to find out which files are unused anymore?
I've tested the next tools so far:
findead
deadfile
unrequired
None of them really worked. One of the reason is that we use "not standard" imports. In additional to the regular relative paths in our imports we also use paths resolved by the webpack resolve feature which basically allows us to use neat import 'pages/something' rather than cumbersome import '../../../pages/something'.
UnusedWebpackPlugin
So here is the solution I've finally come across thanks to Liam O'Boyle (elyobo) #GitHub:
https://github.com/MatthieuLemoine/unused-webpack-plugin
It's a webpack plugin so it's gonna work only if your bundler is webpack.
I personaly find it good that you don't need to run it separately but instead it's built into your building process throwing warnings when something is not ok.
Our research topic: https://github.com/spencermountain/unrequired/issues/6
Libraries such as unrequired and deadcode only support legacy code.
In order to find the unused assets, to remove manually, you can use deadfile
library:https://m-izadmehr.github.io/deadfile/
Out of box support for ES5, ES6, React, Vue, ESM, CommonJs.
It supports import/require and even dynamic import.
It can simply find unused files, in any JS project.
Without any config, it supports ES6, React, JSX, and Vue files:
First of all, very good question, in large project coders usually try many lines of code test and at the end of result, hard to find the unused code.
There is two possible that must be work for you - i usually do whenever i need to remove and reduce the unused code into my project.
1st way WebStorm IDE:
If you're using the web-storm IDE for JS development or React JS / React Native or Vue js etc it's tell us and indicate us alote of mention with different color or red warning as unused code inside the editor
but it's not works in your particular scenario there is another way to remove the unused code .
2nd Way unrequired Library: (JSX is not supported)
The second way to remove the unused code inside the project is unrequired library you can visit here : unrequired github
another library called depcheck under NPM & github here
Just follow their appropriate method - how to use them you will fix this unused issue easily
Hopefully that helps you
I think the easiest solution for a create-react-app bootstrapped application is to use ESLint. Tried using various webpack plugins, but ran into out of memory issues with each plugin.
Use the no-unused-modules which is now a part of eslint-plugin-import.
After setting up eslint, installing eslint-plugin-import, add the following to the rules:
"rules: {
...otherRules,
"import/no-unused-modules": [1, {"unusedExports": true}]
}
My approach is an intensive use of ESlint and make it run both on IDE ad before every push.
It points out unused variables, methods, imports and so on.
Webpack (which has too nice plugins for dead code detection) take care about avoiding to bundle unimported code.
findead
With findead you can find all unused components in your project. Just install and run:
Install
npm i -g findead
Usage
findead /path/to/search
This question recalls me that react by default removes the deadcode from the src when you run the build command.
Notes:
you need to run build command only when you want to ship your app to production.

A lot of incorrect JavaScript errors in the ASP.NET Core Template Pack for Angular 2

I found the ASPNETCoreTemplatePack by MadsKristensen a very good starting point for developing ASP.NET Core applications using Angular 2 as frontend. But as I started editing, I got 448 errors in the error-list dialog. Some of them are from the example Angular components, others actually generated by node.js modules. All came from TypeScript files. The project column says virtual TypeScript project and I opened some at random.
Example
Nr. 1: ClientApp/app/components/app/counter/counter.component.ts
#Component({
selector: 'counter',
template: require('./counter.component.html')
})
Here VS says The name "require" was not found.
Nr 2: node_modules/rxjs/add/operator/map.d.ts
import { MapSignature } from '../../operator/map';
declare module '../../Observable' {
interface Observable<T> {
map: MapSignature<T>;
}
}
Error: Invalid module name in augmentation, module '../../Observable' cannot be found.
And so on, as I said there are nearly 500 of them. Seems that Visual Studio misunderstand something here, as the app is compiling and all function work like expected. Also the counter-component, which couldn't work when the error was true, cause the require-function load its view. So I want to disable those errors - they make me missing real errors in my code, which had to be fixed.
Things I already tried:
Setting TypeScriptCompileBlocked to true in the project file like described here: http://rostacik.net/2015/08/14/how-to-disable-building-of-typescript-files-in-visual-studio-2015/
Added a tsconfig.json in the project-root with "exclude": [ "bin", "node_modules" ]
By doing some research I found out that the used functions like module or require and also some syntax-constructs are introcuted in the TypeScript 2.0 Version. First this was confusing me, since my package.jsonfile already refers to TypeScript in the 2.0.0 Version. Also an upgrade to 2.1.5 (latest version in time of writing) doesn't change anything.
After trying some other things I searched for the needle in the haystack as we said in Germany. And I learned that Visual Studio has a TypeScript for Visual Studio 2015 package. This seems to contain some sort of rules to validate TypeScript in the errorlist-window. Its version is the same as TypeScript: TypeScript 2.1.5 > TypeScript for Visual Studio (2015) 2.1.5.
So its very important to have the same version of TypeScript for Visual Studio installed as the TypeScript version you're using as compiler. In my case, I had TypeScript for Visual Studio in Version 1.8.36 since I'm new to it and never used it before. Seems like the default one installed by VS. But the ASPNETCoreTemplatePack refers to 2.0.0 which caused this problem.
Install a specific version
My solution above will cause a new problem. The download page from Microsoft lists multiple older versions like 2.1.4 or 2.0.6 with links for downloading. But all refers to TypeScript_Dev14Full.exe, which is the latest (so currently 2.1.5). You could get a wider range of versions in the Visual Studio Marketplace.
Please note: Some versions of the market contains warnings that installing the addon would break their VS or TypeScript. I don't had tried this, since the latest version 2.1.5 is fine for me. But its may a good hint for people who had problems with the latest version. Please take care, backup your data and better create some sort of restore point, so that you can easily get a working development-area in case of anything breaks.

WebStorm 2016.3 + Electron: Unresolved function or method

I am playing around with Electron and WebStorm as part of a project preparation and I am struggling with different problems. Therefore I want to start simple by creating very basic stuff and working my way up.
So I have a very simple project setup in WebStorm and my first Electron app is running. But WebStorm keeps saying that it cannot resolve function names.
Electron and electron-prebuilt are added to the package.json and Node.js coding assistance is enabled. Therefore require('electron') is recognised correctly.
I saw the blog entry by JetBrains on how to start with Electron in WebStorm and found also another similar answer here on StackOverflow.
JetBrains' blog entry
StackOverflow answer
It is said, that one should add github-electron to the JavaScript library from the communitie-stubs repositories. But these seems outdated, as there is no github-electron anymore and all other electron entries are ambiguous.
So my question is: How to setup WebStorm for plain JS ES6 correctly, beginning by eliminating the "unresolved" messages?
So, after digging into the topic more and more and climbing the steep learning curve, I finally found the answer by myself.
Here we go:
Go to WebStorm's Preferences / Languages & Frameworks / TypeScript
Make sure Use TypeScript Service is enabled
Open up WebStorm's Terminal panel (as it will automatically point to your project's working directory) and install the type definitions for TypeScript via NPM:
npm install #types/electron
You don't need to use the --save / --save-dev tags, as the types are needed solely for WebStorm's code assistance and have no impact on your project.
You'll get a new entry inside your node_modules folder containing the type definitions.
And that's it. WebStorm does not show any unresolved function or method messages for this particular module anymore.
This works for theoretically every other module, as long as there are type definitions available. But chances are good, as there are a lot of them. Way more than what WebStorm's JavaScript library download functionality offers.
Have a nice day, everyone!
Martin
install the electron library. Since the github-electron has renamed to electron.

How to get angular2 to work in eclipse with typescript

So I was starting researching about angular2 and since I saw so many references to typescript being prefered I am trying to switch to it from javascript. Problem is, I saw a nice little guide I could follow to install it all in eclipse (angular, javascript, everything needed to launch the 5 minute guide code on the main page of angular), so I did it and managed to get it to work.
Now I would like to do the same with typescript, but I find myself lost since it doesn't seem to be working, I can't launch code, it's like node.js isn't working anymore, but since I do not know what the expected result is, I am not sure what is missing.
For example, I re did the 5 minute guide and notice as a difference that I do not have the installation of the modules, nor any run-as configuration ready, in fact, I can't manage to run as any typescript code I try to do.
What I did was:
1- Install Eclipse Mars, other guys uses older versions
2- Install Node.js
3- Install WildFly Server
4- Install TypeScript plugin https://marketplace.eclipse.org/content/typescript
5- Import my project in eclipse, you may have to create a new static web project and add your files in there. The 5 minute quick start is not an eclipse web project so you may not be able to import this. Do not forget to copy and past the same structure with the node modules that you have
6- Right click on the project > Configure > Enable Typescript Builder
7- Right Click the project > Properties > TypeScript > Compiler and configure as follows:
I hope this will do it for you.
Remember, this plugin does not respect json configuration file, so you have to do this manually as in the screenshot. Also, if you are going to provide arguments to your component constructor, You will have errors. Let me know if you got those. Another thing to mention is that using some annotations like #Input will not work, you will have to use inputs:[] inside your #Component annotation.
You can try to add those plugins on top of Mars:
https://github.com/angelozerr/angular2-eclipse
https://github.com/angelozerr/typescript.java
Those 2 are incubating but already provide good features. There is another one, that I didn't try but which has some popularity:
https://github.com/palantir/eclipse-typescript
Eclipse >= Neon
sudo npm install -g angular-cli (ng help must work)
See: https://github.com/angelozerr/angular2-eclipse
Install it and restart Eclipse
Open a .ts file
Eclipse Oxygen
Default javascript installation, then added the default free plugin for angular 2 / typescript from here:
angular2.ide - http://oss.opensagres.fr/angular2-eclipse/1.3.0/
After installing I opened an existing Angular 4 / TS project, worked fine. I then installed support for .scss from http://www.liclipse.com/text/updates. All setup and configured with Typescript 2.4.1 / nodejs v6.9.4.
But within days it now fails to open .ts files at all. Re-installation of the ng plugin did not fix it, I uninstalled liclipse plugin and no change either. It basically leaves eclipse unusable for ng4 projects as is.
The logs show the following errors.
org.eclipse.core.runtime.CoreException: Plug-in "ts.eclipse.ide.jsdt.ui" was unable to instantiate class "ts.eclipse.ide.jsdt.internal.ui.editor.TypeScriptEditor".
at org.eclipse.core.internal.registry.osgi.RegistryStrategyOSGI.throwException(RegistryStrategyOSGI.java:194)
at org.eclipse.core.internal.registry.osgi.RegistryStrategyOSGI.createExecutableExtension(RegistryStrategyOSGI.java:188)
at org.eclipse.core.internal.registry.ExtensionRegistry.createExecutableExtension(ExtensionRegistry.java:905)
...
Caused by: java.lang.NoClassDefFoundError: org/eclipse/wst/jsdt/ui/text/JavaScriptSourceViewerConfiguration
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
...
Caused by: java.lang.ClassNotFoundException: An error occurred while automatically activating bundle org.eclipse.wst.jsdt.ui (441).
at org.eclipse.osgi.internal.hooks.EclipseLazyStarter.postFindLocalClass(EclipseLazyStarter.java:112)
at org.eclipse.osgi.internal.loader.classpath.ClasspathManager.findLocalClass(ClasspathManager.java:529)
...
Caused by: java.lang.ClassFormatError: Name index 1 in LocalVariableTable has bad constant type in class file org/eclipse/wst/jsdt/internal/core/JavaModelManager
I found
TypeEcs plugin for Typescript
it provide below.
•Syntax highlighting
•Code Completion
•Code Outline
•Find References
•Rename / Refactor
•Open Type
•Code Compilation
•Format Code
•Comment Code
•Open Declaration
•Mark Occurences
•Type Script Debug

Categories