How to prevent visual studio 2017 from build javascript? - 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.

Related

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/*"]
},

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

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

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.

Visual Studio 2015 compiles ALL typescript files when SINGLE file is changed

I am using Visual Studio 2015 with Typescript 1.5.4 and Resharper 9
This is the buggy scenario:
I have about 180 typescript files
I change single .ts file
VS shows message "Generation of XXX.ts file complete. Remaining files still compiling"
after that ALL my .ts files are compiled to .js
2 things were changed in those .js files: formatting is slightly different and reference for .js.map was removed
When I build the whole project, then the .js files are generated again but with original formatting and with link to .js.map present
This is annoying because it generates too much noise in Git
and it prevents me from debugging typescript files directly in browser. (because of that missing .js.map file)
The desired behaviour is of course that the only changed .ts file should be compiled on save. How to do it?
It seems that R# has nothing to do with this, because it continues to happen with R# disabled.
My current project settings:
-------------UPDATE-------------
I've tried to update to Typescript version 1.6.
The PATH variable pointed to C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.4\ so I've updated that to point to 1.6
So when I now type tsc -v it says message TS6029: Version 1.6.2
But because of historical reasons (the project I work on is about 2 years old) I have to use version 1.4 inside VisualStudio. So in the .csproj is <TypeScriptToolsVersion>1.4</TypeScriptToolsVersion>
After this change the compile on safe stopped working completely.
Now I have to rebuild the whole solution :(
It seems that Visual Studio does not support watch mode properly (i.e. incremental compilation):
Just to be clear, --watch does work on Windows if you're using
node.js/io.js, but the tsc.exe program distributed with VS does not
support it; you still have Compile on Save for similar functionality
anyhow.
https://github.com/Microsoft/TypeScript/issues/2375#issuecomment-100812347
I'm not sure why this was closed. Supporting --watch for our tsc.exe
host would both be possible and desirable. Right now the limiting
factor is that our tsc.exe host is a bit of ugly C++, that uses some
ancient COM interfaces for Chakra that we haven't spent much effort
on. Our options are: [...]
https://github.com/Microsoft/TypeScript/issues/2375#issuecomment-100949019
As a workaround, could you run
tsc --watch
in the folder where tsconfig.json is located?
Edit: https://github.com/Microsoft/TypeScript/issues/5638 - Visual Studio 2015 compiles ALL typescript files when SINGLE file is changed
Starting with VS 2015 RTM, Compile-on-Save, every time you save a file
we need to generate all files in the project to ensure consistent
output. We have got numerous issues related to inconsistent output
when saving files in different orders. Building all files is the only
way we can guarantee correct and consistent output given all the
language constructs and how they interact across files (e.g.
namespaces/internal modules can be augmented, and that affects the
shape of emitted code, also const enms are in lined as constants,
etc..).
Try "ECMAScript 5" instead of "ECMAScript 3" in "ECMAScript version
I had a similar issue, but since we were handling TS compilation on our own, I wanted to avoid auto-compilation at all...
The fix was to force the TypeScriptCompileOnSaveEnabled flag to false inside the project:
<PropertyGroup>
<TypeScriptCompileOnSaveEnabled>false</TypeScriptCompileOnSaveEnabled>
</PropertyGroup>
in my case this effectively stopped VS2015 from automatically compiling the .ts files on save, without VS getting into the way every time and messing up outputs...
Another work around: You could use Gulp to generate your compiled js files and maps. With Gulp you can also create a watch task to compile at a save of a ts file. You can even create clean tasks to clean up the project.
Example of a build task:
var tsProject = ts.createProject(paths.typescriptRoot + 'tsConfig.json'); // use tsconfig.json
gulp.task("tsbuild", function () {
var tsResult = tsProject.src()
.pipe(sourcemaps.init()) // needed to create sourcemaps
.pipe(ts(tsProject)); // use tsconfig.json
return tsResult.js
.pipe(concat(paths.concatTsFileName)) // concat all output files into a sings js files
.pipe(sourcemaps.write()) // write the sourcemap to be able to debug the ts files
.pipe(gulp.dest(paths.typescriptOut)); // output the result on specific path
});
Example of a cleanup task :
gulp.task("clean:tsout", function (cb) {
rimraf(paths.typescriptOut + paths.concatTsFileName, cb); // rimraf is used to delete a folder
});
gulp.task("clean:scriptjs",
function () {
return gulp.src(paths.typescriptJs, { read: false }) // to clean up multiple files we need to use gulp-rimraf
.pipe(gulpRimraf());
});
Example of a Watch task:
gulp.task("watch:tsbuild", ['tsbuild'], function () {
gulp.watch(paths.typescriptRoot + '**/*.ts', ['tbbuild']);
});

Categories

Resources