Issue adding third-party (external ) js lib in angular5 - javascript

I am working on to add jsplumb community js library version with the angular 5 application (Angular CLI: 1.6.1).
With the first build without any configuration to tsconfig.json I get the following error.
ERROR in src/app/jsplumb/jsplumb.component.ts(4,25): error TS6143: Module '../../../node_modules/jsplumb/dist/js/jsplumb.js' was resolved to 'D:/myproj/angular5/myapp/node_modules/jsplumb/dist/js/jsplumb.js', but '--allowJs' is not set.
With "allowJs":true in the tsconfig.json get the following error
ERROR in error TS5055: Cannot write file 'D:/myproj/angular5/myapp/node_modules/jsplumb/dist/js/jsplumb.js' because it would overwrite input file.
Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig.
As per tsconfig FAQ
Why am I getting the error TS5055: Cannot write file 'xxx.js' because it would overwrite input file.
with an outDir ("outDir": "./dist/out-tsc") this issue should be resolved. This is already set in my tsconfig.
If we add noEmit to true it simply builds the application, not including any js we get a blank white screen.
Let me know if anyone has tried to include external js with new angular cli and face the same kind of error and what is the solution for the same.
Without any additional option added to tsconfig.json if I try to modify any ts file the application will compile with success and I am able to work. But this does not help while running ng build, to create a deployable binary.
Update Workaround: until the fix in CLI is available. For development (ng serve) remove allowJs from tsconfig.json, when ever you get an error with adding allowJs simply modify a ts file to recompile the applicaiton, this time will compile with success. For production or distribution add back the allowJs to tsconfig.json run the application run with ng build --prod --watch=auto you should see the error about overriding the JS file in node_module, simple modify a ts file it should rebuild as --watch=auto is there in command but this time with sucess.

If you're trying to import a library to Angular 2+, you should do it inside angular-cli.json.
There you have a scripts key where you should configure the desired imports. They are generally like:
{
...
"scripts": [
"../node_modules/MODULE/file.js"
],
...
}
Also you can import the library (not recommended) inside your main index.html, using <script src="/path_relative_to_root/file.js">
https://github.com/angular/angular-cli/wiki/angular-cli
https://github.com/angular/angular-cli/wiki/stories-global-scripts
Angular Cli Webpack, How to add or bundle external js files?

have you tried upgrading it to angular 6? maybe they fixed this in the new version.
ng update #angular/cli

Related

Jest config ignored since upgrading to 27

I'm trying to migrate an NX monorepo from Angular 12 to Angular 13. As part of this migration, Jest is also updated to version 27.2.3. the project is also using a custom editor build of CKEditor5.
When CKEditor was first integrated (back when the project was using Angular 9 I believe) we had a lot of issues getting it to work with Jest and whenever the unit tests were ran, any component that included CKEditor was giving the error message:
SyntaxError: Cannot use import statement outside a module
We managed to fix the issue by adding the following configuration to the global jest.preset.js file in the root of the project:
transform: {
'node_modules[\\\\/]#ckeditor.+.(js)$': 'babel-jest',
'^.+.(ts|html)$': 'ts-jest',
},
transformIgnorePatterns: ['/node_modules/(?!#ckeditor|lodash).+.(js|jsx|ts|tsx|svg)$'],
However, now that we are migrating from Angular 12 to 13, the above error message has returned and it seems the above config is now ignored.
As part of the migration, NX has automatically created new project.json files in all of the libs in the monorepo. This file contains some Jest configuration so I have tried moving the config above from the jest.preset.js file to the individual project.json files in any lib using CKEditor, but this has not fixed the issue. The new project.json files also read some Jest config from a project-specific jest.config.js so I have tried adding the config there as well, and that has also not fixed the issue.
I have also tried updating the testEnviroment config in package.json from "node" to "jsdom" and this has not helped either. I also tried moving the whole transform/transformIgnorePatterns config to Jest section of package.json and that also did not help.
I assume my previously working config just need to move to a different file, it is just not clear which file it needs to move to.
My environment is as follows:
Windows 10
Node 16.13.2
NPM 8.1.2
NX 13.4.5
Jest 27.2.3
Angular 13.1.2
This was fixed by adding the following config to the Jest preset file, and removing same config from individual apps/libs configs:
transform: {
'node_modules[\\\\/]#ckeditor.+\\.(js)$': 'babel-jest',
'^.+\\.(ts|js|mjs|html|svg)$': 'jest-preset-angular',
},
transformIgnorePatterns: ['node_modules/(?!.*.mjs$|#ckeditor)'],
Problem was related to having multiple strinfs inside transformIgnorePatterns - it supports only one item despite being an array

working 'types' definition files, anyone?

We're using Tabulator-tables in a large Angular project and I cannot seem to find a usable definition files.
I've tried https://www.npmjs.com/package/#types/tabulator-tables which seems updated etc but it results in lots of errors in my IDE and the project will not compile as a result. There are many errors even though the compilation worked before I added the types package. Its pointless and impractical to add many #ts-ignore comments.
Be advised - I took notice to use the same version of the type definition package as installed in my project (v4.2.2). I assume the problem is with the automatic generation of the above package - the resulting .d.ts file is not usable as a result.
Please correct me if I'm wrong and any help in integrating definition files will be appreciated. TIA!
I had a similar issue with adding TypeScript typings on Angular project and here's what i did:
encapsulated Tabulator inside Angular component (data-grid.component.ts in my case);
npm install #types/tabulator-tables
created file data-grid.component.d.ts with:
declare module 'tabulator-tables' {
export = Tabulator;
}
the key thing: removed import Tabulator from 'tabulator-tables' from file data-grid.component.ts
And it's worked.
A full set of TypeScript Typings can be found in the #types/tabulator-tables npm package
npm install #types/tabulator-tables
An example of how to use the typings in a project can be found here
The Language Documentation includes more information on the available typings
I already wrote an answer for this issue, not good enough in my opinion, but some people upvoted it as right, so I decided to leave it as it is and write a new one.
There is some issues with adding types for tabulator, this is because type annotations not being exported, but there is a way to use them.
After installation of types for tabulator (npm install --save #types/tabulator-tables), you should open (or create it, if it's not exists) file index.d.ts inside directory src, and copy following code into it:
declare module 'tabulator-tables' {
export = Tabulator;
}
You need to ensure that you have "allowSyntheticDefaultImports": true inside compilerOptions of file tsconfig.json or tsconfig.app.json (depends on your project), and tsconfig.spec.ts (it needs for unit testing).
Very important to unload and start over ng serve after editing of tsconfig.
After that all typings should work. Just in case I created simple Angular example, hope this helps.

Unable to compile and publish my Typescript library using webpack or TSC

Ive created a library that helps to trace an object state using rx streams and
Im trying to publish it to npm community.
you can check this out In my github repo
I want to compile my library to a single Javascript file and also create a declaration file ".d.ts" for Typescript users.
As i understand, when running $ npm publish i release my entire repository. what i want is to release the dist folder with the library source and declaration file and so the end users will be able to debug my library if necessary through their code so i need also source map.
So first i need to compile my src directory to a single javascript file and i have 2 ways to do so, using tsc or with webpack.
What ive tried so far and you should know:
I used module alias, configured in tsconfig.json.
I separated the library's bussiness logic to multiple files.
I wanted to import internal library's modules using "#lib" prefix.
so in my tsconfig.json i added:
"paths": {
"#lib/*": [
"src/*"
]
},
That alone cause some problems.
first of all running the command:
$ tsc src/index.ts
doesn't work at all and it shows me an error:
src/index.ts(3,15): error TS2307: Cannot find module '#lib/state-traceable'.
src/index.ts(4,15): error TS2307: Cannot find module '#lib/traceable-decorator'. src/index.ts(5,15): error TS2307: Cannot find module '#lib/effect-decorator'.
src/index.ts(6,15): error TS2307: Cannot find module '#lib/meta'.
yet running the command:
$ tsc
does actually works but it compiles each source file and create declaration file for each one of them.
Additionally, it preserves the path alias "#lib/*" instead of compiling it to something javscript compatible with relative paths "../", "./" etc...
Using webpack:
I succeed to bundle all my library sources to a single file and get rid of the "#lib" prefix however im not able to create a single declaration file.
im using "awesome-typescript-loader" plugin for webpack.
I created an issue, thought its a bug but i yet received any response from them:
https://github.com/s-panferov/awesome-typescript-loader/issues/559
Also tried to get some help from Gitter chats, Typescript community, "awesome-typescript-loader" library has no dedicated chat but couldn't find any useful information. Most of the examples ive seen, Typescript library publishers used to create a single file in their source directory: "index.ts" and it makes life easier because you can use tsc and compile that single file to a javascript file.
I hope i will find salvation here.
Some general info about the environment itself:
OS: Windows 10 Pro
Node Version: 9.5.0
npm version: 5.6.0
webpack version: 4.2.0
Please use the path configuration like below
"paths": {
"#lib/state-traceable": ["src/state-traceable.ts"],
"#lib/meta": ["src/meta.ts"],
"#lib/effect-decorator": ["src/effect-decorator.ts"],
"#lib/traceable-decorator": ["src/traceable-decorator.ts"],
"#lib/contracts/*": ["src/contracts/*"],
"#lib/utils/*": ["src/utils/*"],
"#lib/rx-operators/*": ["src/rx-operators/*"]
},

How to prevent visual studio 2017 from build javascript?

I upgraded today to VS2017, and I saw that every time I change something in my my web app project - the build build all my javascript again (I'm using webpack for client).
It is cool, but it take a lot of time, so I'll be happy to configure it to stop building the javascript (and I'll build it myself just when it changed).
Simple Answer
In your csproj file, add the following line to the existing PropertyGroup block:
<PropertyGroup>
<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
</PropertyGroup>
If adding .ts or .tsx files to your project causes your project file to be modified, you may need to apply the following fix. See the bug report for more details.
<ItemGroup>
<None Remove="**/*.ts;**/*.tsx" />
<Content Remove="**/*.ts;**/*.tsx" />
<TypeScriptCompile Include="**/*.ts;**/*.tsx" />
</ItemGroup>
Add a tsconfig.json file to your project root and make sure the following setting is set:
"compileOnSave": false,
Finally, Restart Visual Studio
Details
Nuget creates a generated targets file called [ProjectName].csproj.nuget.g.targets in the obj directory of your project. This targets file is importing Microsoft.NET.Sdk.Web.ProjectSystem.targets which in turn imports Microsoft.TypeScript.targets.
In the Microsoft.TypeScript.targets file, the following line has a comment that lets us know that if this property is set to true, then the TypeScript compilation task will do nothing:
<!-- Makes the TypeScript compilation task a no-op -->
<TypeScriptCompileBlocked Condition="'$(TypeScriptCompileBlocked)' == ''">false</TypeScriptCompileBlocked>
I'm using webpack's ts-loader to compile and bundle my TypeScript files. So I no longer needed the automatic compilation that Visual Studio performed on each build. In Visual Studio 2017, I just commented out the following line from tsconfig.json to stop the automatic compilation:
"outDir": "./wwwroot/build/",
I had the same problem - Webpack was rebuilding my Typescript files every time Visual Studio rebuilt the project, despite having
<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
in my proj file, and
"compileOnSave": false,
"buildOnSave": false
in my tsconfig.json file.
Turns out it was because I had the NPM Task Runner VS extension installed (https://marketplace.visualstudio.com/items?itemName=MadsKristensen.NPMTaskRunner), and in Task Runner Explorer this had a build task bound to the 'Before Build' event. I didn't need this extension so I just uninstalled it.
Note: I didn't need Webpack to rebuild on VS build because I had it watching my files and rebuilding anyway as I made changes, via this extension: https://marketplace.visualstudio.com/items?itemName=MadsKristensen.WebPackTaskRunner
Setting TypeScriptCompileBlocked to true was not enough for me. What worked was going to the project properties - there is a TypeScript Build tab where you can configure TS compilation, including the Compile On Save option:
It results in the following getting added to the csproj file:
<TypeScriptTarget>ES5</TypeScriptTarget>
<TypeScriptJSXEmit>None</TypeScriptJSXEmit>
<TypeScriptModuleKind>ES6</TypeScriptModuleKind>
<TypeScriptCompileOnSaveEnabled>False</TypeScriptCompileOnSaveEnabled>
<TypeScriptNoImplicitAny>False</TypeScriptNoImplicitAny>
<TypeScriptRemoveComments>False</TypeScriptRemoveComments>
<TypeScriptOutFile />
<TypeScriptOutDir />
<TypeScriptGeneratesDeclarations>False</TypeScriptGeneratesDeclarations>
<TypeScriptNoEmitOnError>True</TypeScriptNoEmitOnError>
<TypeScriptSourceMap>True</TypeScriptSourceMap>
<TypeScriptMapRoot />
<TypeScriptSourceRoot />
Errors complaining about .ts files:
I got build error when I tried to rebuild a VS2017 Web project that includes some typescript files. Error looked like these
Error TS1005 (TS) '?' expected. C:\...\...project1 (tsconfig or jsconfig project) C:\\...\...project1 \node_modules\#storybook\addon-knobs\dist\type-defs.d.ts
No answers that really helped..so far:
After spending hours searching up and down the Stack or else, I realized it could be as simple as to compare the errored project file to another one that also has typescript but no compile error.
It is simple..but it worked:
Here are the steps:
Unload the projects and edited Project file
Search "TypeScript" (exact case and exact word option) and found two Imports that matched:
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.Default.props" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.Default.props')" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets')" />
Then I went to the Project that did not have a problem compiling .ts files and look, it's different in the Condition:
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets" Condition="false" />
So I just replaced the Import with the one in 3) and reloaded the project and as expected, compiled successfully.
In the perfect world,Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets')" might just be exactly same as Condition="false" but there were not, even in my machine there is no such folder existing (C:\Program Files (x86)\MSBuild\15.0).
Sometimes, common sense helps more than deep knowledge, and this was that time.
In my case (Visual Studio 2017 15.9.25), I have to add the following property to .csproj
<PropertyGroup>
<TypeScriptCompileOnSaveEnabled>false</TypeScriptCompileOnSaveEnabled>
</PropertyGroup>
More details:
I read this article https://www.typescriptlang.org/docs/handbook/compiler-options-in-msbuild.html and realize that VS will build TS based on the file Microsoft.TypeScript.targets.
And in this file, I see that it also bases on this property to control the Compile-on-Save TypeScriptCompileOnSaveEnabled. So setting this property to false in .csproj will stop the compile typescript when saving. (Please note that before doing this I already tried setting "compileOnSave": false in tsconfig.json file but it did not help)
Done the following setting along with TypeScriptCompileBlocked to true.
Set the below condition to false in .csproj file of the application.

How to create aurelia typescript project with vs2017rc

I am new to aurelia, and I need create a prototype project of the framework. At the beginning, I planed to use skeleton-typescript-aspnetcore skeleton, but when I tried the vs2017rc, I found it uses .csproj as the default format(while vs2015 is project.json/.xproj), I think we should follow the vs2017 because we will upgrade our IDE after it's been launched.
The vs2017 have a wizard to upgrade .xproj project, but after the upgrading(skeleton-typescript-aspnetcore), there still lots of error ahead me...
I also tried aurelia-cli, but seems it has not support vs2017 yet, does anyone could give a guide to create the prototype project? I will integrate some plugins like the skeleton mentioned above, such as gulp,karma,breeze...
thank you in advance.
Since Visual Studio 2017 just launched I thought I'd answer how I solved this, as there are still many errors when using "skeleton-typescript-aspnetcore".
Using https://github.com/aurelia/skeleton-navigation/releases/tag/1.1.2 as a starting point, these are the steps to get it running:
When you first run the project you will get errors complaining that some files located in /test/ is not under 'rootDir'. In your tsconfig.json the rootDir is defined as "src/", this can be solved simply by moving your test folder inside your src folder. This will cause new errors because the paths defined in those files has now changed. You will need to edit app, child-router and users imports like this:
import {Users} from '../../users'; IntelliSense should help you out here.
The command gulp test will also not run before changing to the new path, you can change the path in karma.conf.js:
files: [
'src/test/unit/setup.ts',
'src/test/unit/*.ts'
],
Next the file users.ts will throw errors like Type 'Response' is not assignable to type 'any[]'. You will need to tell TypeScript what you're declaring like this: public users : Object = []; or simply: public users = {};
The final problem is that you're going to have a lot of duplicate identifier errors, at the time of writing this the cause of this seems to be from the changes brought on by TypeScript version 2.2.1. I don't know what specifically breaks, but I know that previous version 2.1.5 still works. So what you need to do is to run npm install typescript#2.1.5 --save in your src/skeleton directory, the --save is just to update your package.json file, you can do this on your own later as well if you wish.
After you've done that your gulp errors (20~ of them) should be resolved. But there are still some errors remaining caused by duplicate signatures. Again, things have changed in TypeScript 2.0+, there is now a simplified way of getting and using declaration files. Here is an answer on SO on how to use the #types feature: How should I use #types with TypeScript 2 , but to keep this short and sweet you will have to go to your tsconfig.json file and explicitly tell where to find the #types/node folder. It would look something like this:
"compilerOptions": {
...
"typeRoots": [
"node_modules/#types"
],
"types": [ "node" ]
...
},
Hope this helps, with these changes the project should now build and launch correctly.
EDIT:
I recently ran into some problems again with building my project. I got a lot of duplicate identifiers again... I however ran across this answer on SO: TypeScript throws multiple duplicate identifiers
Apparently TypeScript latest ships with fetch definitions out of the box, so I was able to run the command from the answer in the link:
npm uninstall #types/whatwg-fetch
And upgrading from typescript 2.1.5 to latest:
npm install typescript --save
You might even want to install typescript globally by appending -g.
Also this will continue to be an issue unless you comment out/delete url and whatwg-fetch from typings.json globalDependencies in order to prevent it from recreating itself:
"globalDependencies": {
//"url": "github:aurelia/fetch-client/doc/url.d.ts#bbe0777ef710d889a05759a65fa2c9c3865fc618",
//"whatwg-fetch": "registry:dt/whatwg-fetch#0.0.0+20160524142046"
}
Then you can either delete the typings folder, running typings install again or edit index.d.ts in the typings folder and delete the reference paths to whatwg-fetch and url.
Hope this helps someone who might've encountered the same problems even after "fixing" it.

Categories

Resources