Use typings in vscode without reference path for each d.ts - angularjs

I have TypeScript and Typings working in vs2015 with the Web Analyzer plugin. I've resolved all vs2015 errors. Now I am trying to set it up in vscode. I've setup a gulp task and vscode reports:
error TS2304: Cannot find name 'angular'
I can resolve it with the following line, but is there a simpler way than listing out each file individually? I.e., vs2015 compiles the TypeScript without issue and knows how to use the Typings files.
/// <reference path="../typings/browser/ambient/angular/index.d.ts" />
I started with gulp-tsc and also tried gulp-typescript, but both require this.
var tsc = require("gulp-tsc");
var typescript = require("gulp-typescript");
var $ = require("gulp-load-plugins")({ lazy: true });
gulp.task("ts-watcher", function() {
gulp.watch("./app/**/*.ts", ["ts-compile"]);
});
gulp.task("ts-compile", function() {
var tsProject = typescript.createProject('tsconfig.json');
return gulp.src(config.allts) //["./app/**/*.ts"]
.pipe(typescript(tsProject))
.pipe(gulp.dest("dest/"));
});
gulp.task("default", ["ts-watcher"]);
{
"compilerOptions": {
"module": "amd",
"rootDir": "src",
"sourceMap": true,
"target": "es5",
"removeComments": true,
"outFile": "./build/build.js"
},
"compileOnSave": true,
"exclude": [
"node_modules",
"typings/main",
"typings/main.d.ts",
"packages"
]
}
My typings folder is in the same folder as tsconfig.json.
Restarting VSCode did not help.
This is similar to Including d.ts type definition files in VSCode, but I am 1) including more information, 2) using VSCode 1.1.0, and 3) I have a TSconfig, not a JSconfig. Would a jsconfig help?

Add a main.d.ts file in your app folder. (Or the src folder where all your ts file resides) with below content, (check the relative path based upon your project structure)
/// <reference path="../typings/main.d.ts" />
you might have to restart VS code.

Maybe you shouldn't exclude typings/main.d.ts as you seem to do. This file is the entry point that includes all registered type defs and hence also angular.

A tsconfig (or jsconfig) in your workspace root is required for vscode to automatically pick up type definitions from typings directory in your workspace root.
In the following example only browser .d.ts-files are used.
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"sourceMap": true
},
"exclude": [
"typings/main.d.ts",
"typings/main",
"node_modules"
]
}
To install additional typings you can use the following typings command
typings install --ambient jquery --save
or use one of the following vscode extensions:
typings-installer
typings-autoinstaller

Related

StencilJS error with React output target - You may need an additional loader to handle the result of these loaders

I'm creating some basic elements in Stencil for a custom design system. I created some basic components, which work fine on their own as custom elements, but throw errors when used as React components.
I generated the React components via Stencil by includng the #stencil/react-output-target in stencil.config.ts.
reactOutputTarget({
componentCorePackage: '#sr-design-system/simple-stencil-demo',
proxiesFile: './react/src/components/index.ts',
includeImportCustomElements: true
}),
I then uploaded all of the components (custom elements & React) to a private npm package and installed them in a seperate project. The custom elements seem to work fine, but with the React elements I get the following error.
ERROR in ./node_modules/#sr-design-system/simple-stencil-demo/react/src/index.ts 6:12
Module parse failed: Unexpected token (6:12)
File was processed with these loaders:
* ./node_modules/source-map-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
| import { createReactComponent } from './react-component-lib';
|
> import type { JSX } from '#sr-design-system/simple-stencil-demo/';
|
| import { defineCustomElement as defineSrText } from '#sr-design-system/simple-stencil-demo/dist/components/sr-text';
# ./src/App.jsx 7:0-73
# ./src/index.jsx 7:0-24 12:33-36
webpack 5.65.0 compiled with 1 error and 1 warning in 63 ms
I've been stuck on this issue for days now. Any idea what the solution could be?
===tsconfig.json===
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"allowUnreachableCode": false,
"declaration": true,
"experimentalDecorators": true,
"forceConsistentCasingInFileNames": true,
"lib": ["dom", "es2017"],
"module": "es2015",
"moduleResolution": "node",
"pretty": true,
"removeComments": false,
"strictPropertyInitialization": false,
"target": "es2017",
"baseUrl": ".",
"paths": {
"#srds/react": ["./react"]
},
"jsx": "react",
"jsxFactory": "h"
},
"include": ["src"]
}
===stencil.config.ts===
import { Config } from '#stencil/core';
import { reactOutputTarget } from '#stencil/react-output-target';
export const config: Config = {
namespace: 'simple-stencil-demo',
bundles: [{ components: ['sr-text'] }, { components: ['text-demo'] }],
outputTargets: [
reactOutputTarget({
componentCorePackage: '#sr-design-system/simple-stencil-demo',
proxiesFile: './react/src/components/index.ts',
includeImportCustomElements: true,
}),
{
type: 'dist',
esmLoaderPath: './loader',
},
{
type: 'dist-custom-elements',
},
{
type: 'docs-readme',
},
{
type: 'www',
serviceWorker: null, // disable service workers
},
],
buildEs5: 'prod',
};
I figured out what the issue. For some reason, the dist folder was not being generated for me every time I ran npm run build.
Sometimes it was generated, other times it wasn't. I believe it was due to some errors in my component code, which failed silently. So now I check for the dist folder every time I build the library.
In my final, working attempt I went with the monorepo approach as advised by the Stencil team in their documentation.
Here are all I took the steps for a basic Stencil library with a React output:
Create a monorepo
Create a Stencil Library
Generate components using npx stencil generate
Update name in package.json to MY_LIBRARY
npm i #stencil/react-output-target
Add the React Wrapper function to stencil.config.ts
react({
componentCorePackage: 'MY_LIBRARY',
proxiesFile: '../MY_REACT_LIBRARY/src/components/stencil-generated/index.ts',
includeDefineCustomElements: true,
}),
Move back to root level of monorepo
Create a React library
git clone https://github.com/ionic-team/stencil-ds-react-template react-components
Update name in package.json to MY_REACT_LIBRARY
Change private to false in package.json
In the Stencil Library
Run npm run build
Check if dist folder contains all subfolders (cjs, collection, components, esm, types, web-components, index.cjs.js, index.js)
Run npm link to generate a global symlink
In the React Library
Run npm link MY_LIBRARY
Run npm i
Run npm run build (Not sure if this step is required as it is not documented, but I did it anyway)
Run npm link
Move back to root level of monorepo
Create a React demo
npx create-react-app MY_REACT_DEMO --template typescript
npm link MY_REACT_LIBRARY
Import a component from the library and use it in App.tsx
npm run start
When I confirmed everything worked fine, I added a basic lerna.jsonconfig for npm package management. Using this config, Lerna will automatically handle symver for our packages.
{
"version": "independent",
"npmClient": "npm",
"command": {
"publish": {
"allowBranch": ["master", "react-generation"],
"ignoreChanges": ["*.md", "build.js", "config.json"],
"message": "(auto) Lerna publish",
"registry": "URL_TO_MY_PACKAGE_REGISTRY"
},
"bootstrap": {
"ignore": "component-*",
"npmClientArgs": ["--no-package-lock"]
}
},
"packages": ["MY_LIBRARY", "MY_REACT_LIBRARY"]
}
After configuring Lerna, I published using the command npx lerna publish, following their publishing wizard.
When it's published the package can be installed in any React project using npm i MY_REACT_LIBRARY and it should work.

Setting up ESLint for a Typescript Project using React, React Testing Library, and Cypress

It seems that every time I start using a new library of some sort I run into problems with ESLint, and I can never truly figure out why. I stumble through until the errors and warnings go away, and then deal with it all again later. I'm hoping that I can get some answers on how it's supposed to work here.
I have a React project that is using Typescript. We use react-testing-library for tests (with Jest types) as well as Cypress for testing (with Cypress types). Jest and Cypress will conflict as they use a lot of the same keywords but from different libraries (ie. describe, expect, context, etc.).
Furthermore, with cypress is is possible to define your own functions which will extend the global cy object that is used in all cypress tests, however this must also be typed and requires you to write your own definition files.
Everything was going well until I tried to add my own type definitions, at which point it started complaining again. (I would like to note that my project does compile and run as expected with everything I'm doing at the moment. It is simply ESLint that isn't happy).
The main issue I'm trying to solve is why the type definition doesn't seem to be included in a project. I'm receiving the following error:
Parsing error: "parserOptions.project" has been set for #typescript-eslint/parser.
The file does not match your project config: cypress\support\index.d.ts.
The file must be included in at least one of the projects provided.
As well as whether there is a better way to lay this out.
Thanks to anyone who actually takes the time to read this and make an attempt.
The folder structure looks like this:
cypress
- fixtures
- integrations
- - file.spec.ts <- Uses the custom functions in a test
- plugins
- support
- - commands.ts <- Contains my custom functions
- - index.d.ts <- Types for custom functions
- - index.ts
- .eslintrc.js (A)
- tsconfig.json (B)
src (contains all the jest tests)
.eslintrc.js (C)
tsconfig.json (D)
tsconfig.eslint.json
.eslintrc.js (A)
module.exports = {
extends: ['../.eslintrc.js'],
parserOptions: {
project: 'cypress/tsconfig.json',
},
}
tsconfig.json (B)
{
"extends": "../tsconfig.json",
"compilerOptions": {
"noEmit": true,
// be explicit about types included
// to avoid clashing with Jest types
"types": ["cypress", "cypress-axe"],
"allowJs": true
},
"include": [".eslintrc.js", "../node_modules/cypress", "./**/*"]
}
.eslintrc.js (C)
module.exports = {
parser: '#typescript-eslint/parser',
root: true,
env: {
es6: true,
node: true,
browser: true,
},
parserOptions: {
ecmaVersion: 6,
sourceType: 'module',
tsconfigRootDir: __dirname,
project: './tsconfig.eslint.json',
ecmaFeatures: {
jsx: true,
},
},
plugins: ['react', 'react-hooks', '#typescript-eslint', 'cypress'],
rules: {
'react-hooks/rules-of-hooks': 'error', // Checks rules of Hooks
...
},
}
tsconfig.json (D)
{
"compilerOptions": {
"target": "es5",
"lib": ["es6", "dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"strict": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react",
"baseUrl": "src",
"types": ["jest"]
},
"include": [
"build-system",
"src",
".eslintrc.js",
"pretty.js",
"gulpfile.js"
],
"exclude": ["node_modules", "src/*.test.ts", "src/*.test.tsx"]
}
tsconfig.eslint.json
{
// extend your base config so you don't have to redefine your compilerOptions
"extends": "./tsconfig.json",
"compilerOptions": {
"noEmit": true
},
"exclude": []
}
For what it's worth, I've solved this problem. Hopefully this can be useful to someone at some point.
Essentially the solution was to get rid of the index.d.ts file, and put the types directly in the commands.ts file.
With a little help from this thread, which states:
Hi folks, this issue comment helped me work around the issue:
cypress-io/add-ypress-custom-command-in-typescript#2 (comment)
Fix seems to be declaring Cypress in the global namespace, and your
custom command definitions in there (copied from ☝️ ):
declare global {
namespace Cypress {
interface Chainable {
customCommand: typeof customCommand;
}
}
}
function customCommand(input: MyCustomClass) {
// ...
}
Cypress.Commands.add('customCommand', customCommand);
But agree that the solution suggested in the docs doesn't work
So, by adding the the following code to my commands.ts file:
declare global {
namespace Cypress {
interface Chainable<Subject> {
/**
* Custom command to wait for a specific set of network requests to finish
* #example cy.waitForData()
*/
waitForData(): Chainable<Subject>
}
}
}
as well as adding the following rule to my .eslintrc.js (C) file:
rules: {
...
'#typescript-eslint/no-namespace': ['off']
}
I was able to fix the issue.
Furthermore, if it's relevant, the isolatedModules flag will require that you add an export {} to the commands.ts file as well.

jsconfig.json path alias not working properly

I have a react project created using create-react-app, and I'm trying to add material kit react to the project. I have placed the assets and components of material kit react under src/template and I would like to change the path of assets from src/assets to src/template/assets.
The problem is when I configured jsconfig.json to define the path for assets alias I get the error "Module not found" when using assets, but if I use the template alias it works just fine.
Here is my jsconfig.json file:
{
"compilerOptions": {
"baseUrl": "src",
"target": "es6",
"paths": {
"template/*": ["src/template/*"],
"assets/*": ["src/template/assets/*"]
}
},
"exclude": ["node_modules"]
}
If someone can help me to understand why the template alias is working and not the assets alias.
please try the code below.
I think your 'baseUrl' is wrong.
{
"compilerOptions": {
"baseUrl": ".",
"target": "es6",
"paths": {
"template/*": ["./src/template/*"],
"assets/*": ["./src/template/assets/*"]
}
},
"exclude": ["node_modules"]
}
So, This will make VS Code IntelliSense work.
But there may be other issues. (..Because I went through it.)
Other issue is that resolve does not work.
error is the same
This dependency was not found:
* template/somtething in ./blahblah..
To install it, you can run: npm install --save template/somtething`
If there is an error above,
try to set an alias to the 'template' folder using the following Webpack configuration.
https://webpack.js.org/configuration/resolve/

Typescript (at-loader) compiler errors in WebPack

I am using Visual Studio 2017 to write an Angular SPA, but I use WebPack to run it. Currently I let VS build the Typescript into JS and WebPack uses that JS to create the build artefact.
I want to move to WebPack building the Typescript so its easier for our CI server to build the project. For some reason VS can compile the Typescript fine but awesome-typescript-loader cannot.
My Typescript is written using ES6 modules i.e.
import * as angular from "angular";
import * as moment from "moment";
import "angular-material";
import { ExpensesService } from "../../main/components/reports/expenses/expenses.service";
import { IJourney } from "../../Interface/IJourney";
I get these errors from WebPack / Awesome-Typescript-Loader when I compile run it. Note that all of these are in the node_modules folder and not my code (that I can tell?)
ERROR in [at-loader] ./node_modules/#types/node/index.d.ts:32:11
TS2451: Cannot redeclare block-scoped variable 'Error'.
ERROR in [at-loader]
./node_modules/#uirouter/angularjs/lib-esm/services.d.ts:9:9
TS2717: Subsequent property declarations must have the same type. Property 'stateProvider' must be of type 'StateProvider', but here has
type 'StateProvider'.
ERROR in [at-loader]
./node_modules/awesome-typescript-loader/lib/runtime.d.ts:20:13
TS2403: Subsequent variable declarations must have the same type. Variable 'require' must be of type 'NodeRequire', but here has type
'WebpackRequire'.
ERROR in [at-loader] ./node_modules/tsutils/src/typeguard.d.ts:140:70
TS2694: Namespace 'ts' has no exported member 'EnumLiteralType'.
ERROR in [at-loader] ./node_modules/uri-js/src/punycode.d.ts:9:17
TS2714: The expression of an export assignment must be an identifier or qualified name in an ambient context.
My tsconfig.json (which I force VS to use) is
{
"compileOnSave": true,
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"baseUrl": "./",
"lib": [ "es2015" ],
"module": "commonjs",
"moduleResolution": "node",
"noImplicitAny": false,
"preserveConstEnums": true,
"removeComments": true,
"sourceMap": true,
"target": "es5"
},
"exclude": [
"typings"
],
"include": [
"./src/**/*.ts",
"node_modules/**/*.d.ts",
"scripts/typings/d.ts"
],
"files": [
"./src/app/bootstrap.ts"
]
}
I won't copy packages.json here for brevity, but I include all appropriate npm packages i.e. #types/angular, #types/angular-material etc.
In my WebPack.config here is the relevant setup
module.rules = {
{
test: /\.ts$/,
exclude: /node_modules/,
use: ["awesome-typescript-loader"],
},
}
resolve: {
extensions: [".ts"],
modules: [node_modules"]
},
In my case, excluding in the tsconfig.json didn't work as it works for not implicit compiling, but still goes to the files if explicitly required, and exclude anyway work just to reduce include set.
Adding skipLibCheck to tsconfig.json solved the problem:
{
"compilerOptions": {
// ...
"skipLibCheck": true,
},
// ...
}
NOTE: This was using awesome-typescript-loader in webpack. With ts-loader i didn't have problem.
The cause of the error is you're compiling the definition files
To fix it
removing "node_modules/**/*.d.ts" and "scripts/typings/d.ts"
in tsconfig.json will resolve your problem.

error TS2339: Property 'endsWith' does not exist on type 'string'

I get this error on the code block below.
error TS2339: Property 'endsWith' does not exist on type 'string'
let myList = angular.element(elem).attr("href").split("/");
let last = _.last<string>(myList);
if (last.endsWith("something")) {
return last;
}
I have also discovered this link that shows that there is a function endsWith(...).
http://definitelytyped.org/docs/typescript-services--typescriptServices/classes/typescript.stringutilities.html
Do I miss some .d.ts file or what?
While compiling your typescript code, please point the target to ES6.
tsc --target ES6 "filename"
endsWith is an ES6 function so you need to target ES6 in your TypeScript compiler settings or you can add an interface for it:
interface String {
endsWith(searchString: string, endPosition?: number): boolean;
};
[Playground]
Here : I used VS code as an IDE
Issue was :
let fName:String = "Yokey";
console.log(fName.anchor("url"));
will result in :
PS C:\MYahya\OS_DEV\typescript_lrn\1> tsc main.ts
main.ts(2,19): error TS2339: Property 'anchor' does not exist on type 'String'.
Solution :
I should include the following tsconfig.json file in the project:
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"baseUrl": "../types",
"typeRoots": [
"../types"
],
"types": [],
"forceConsistentCasingInFileNames": true,
}
}
Then I used tsc (without file name) so the transpiler would use the tsconfig.json to transcompile all type script files hosted in the directories to js files.
if youre using intelliJ IDE like WebStorm, click on the area where your project files are on the left then search for tsconfig.json. In that file you will see your es set to an older version just change the "target": "es3" to the latest like "target": "es2018"
Target ES6(Java Script version) in your TypeScript compiler settings using below command :
Command: tsc --target ES6 main.ts
If you want to transpile and run the file at the same time then use
below command :
Command : tsc --target ES6 main.ts | node main.js

Resources