Defining a TypeScript debug variable - javascript

I'm running into a brick wall with what I guess should be a simple task - I want a single variable that determines if the application is in debug state - i.e. debug = false so that I can use this variable, as you may expect, in any class and log messages accordingly. Annoyingly however, no matter what I try, I simply cannot get access to this variable.
I have an app.ts file that imports every class and instantiates them. Defining a global variable at the top of this file did not work, and likewise defining them in a global.d.ts file did not work either - the compiler simply cannot see them. For the record my tsconfig.json file looks like this:
{
"files": [
"./resources/assets/js/declarations/**/*.d.ts"
],
"compilerOptions": {
"noImplicitAny": true,
"target": "es2015"
}
}
The global.d.ts file itself is incredibly simple...
declare let appDebug: boolean;
And its value is set in the app.ts file as mentioned previously. What gives? How can I essentially pass this value into every class?

The files setting doesn't support globs/patterns - only an explicit list of files, so you should see an error when you try to compile in typescript via tsc -p . complaining about the "./resources/assets/js/declarations/**/*.d.ts" bit.
Documentation here: http://www.typescriptlang.org/docs/handbook/tsconfig-json.html

Related

“Module not found” Flow error for autogenerated file

I have three ES2015 modules: store.js, middleware-config.js and autogenerated middleware-config-settings.js with some logic and imports.
Module middleware-config-settings.js is generated from webpack.config.js when the app starts with npm start.
store.js:
// #flow
...
import middlewareConfigs from './middleware/middleware-config';
...
middleware-config.js:
// #flow
...
import defaultSettings from './middleware-config-settings';
...
Module middleware-config-settings.js is just simple JSON:
// #flow
export default {
profilingMiddlewareConfig: {
isActive: true,
},
reduxDiffStateMiddlewareConfig: {
isActive: true,
params: {
ignoredActionTypes: [],
approvedActionTypes: []
}
}
};
When I checked the project with flow I got error:
./middleware-config-settings. Required module not found
First, I tried ignore Flow check for the line:
// #flow
...
// #FlowFixMe: ignore
import defaultSettings from './middleware-config-settings';
...
That apporach works fine if middleware-config-settings.js not exists. Otherwise I got another problem: after npm start middleware-config-settings.js file created and next flow execution fails with another error:
Error suppressing comment. Unused suppression
Second, I tried add middleware-config.js into [ignore] section in .flowconfig. But then I got new error message from store.js:
./middleware/middleware-config. Required module not found
After that I add store.js into [ignore] section too and flow executes well but I think that it's not right way.
Third approach is similar to second - I just removed // #flow from middleware-config.js and flow executes fine. And that approach also not too good (all my modules should be flowed).
So I have two questions:
How can I get errorless flow execution without excluding any of that files from flow checks?
Why I got error about store.js when I add middleware-config.js into [ignore] section? If my understanding of the documentation is right so it's not correct behavior:
The [ignore] heading in a .flowconfig file tells flow to ignore files matching the specified regular expressions when type checking your code.
A few options:
Avoid autogenerating files (I assume you have already considered this and decided against it).
Create a permanent middleware-config-settings.js.flow that contains a prototypical config, and check it in to version control. Then, Flow will look at that file instead of looking for the .js file and it will typecheck, but the actual values will be generated on each run. The main downside of this approach is to make sure that the structure of your .js.flow file matches the structure of the generated .js file when you make changes.
Introduce an explicit build step that generates the required files, rather than including that step implicitly in your npm start script. Then, just make sure that you run that build step before using Flow.
Regarding your second question, I believe that if you add something to the [ignore] section, Flow just pretends it doesn't exist at all. So, if you import an ignored file from a checked file, Flow will give you an error.
I solve that problem with some hack with importing middleware-config-settings.js with require and storing module's name in the variable (for avoiding Required module not found error) and with adding #FlowFixMe (for avoiding The parameter passed to require() must be a literal string. error):
let moduleName = './middleware-config-settings';
// #FlowFixMe: import autogenerated file.
let defaultSettings = (require(moduleName): any);

How to invoke a javascript function (generated from typescript) trapped within “System.register()” module while using Google protobuf?

Update: It seems that, the problem is coming due to protobuf. I am fine with other solution as well, which help me to fix the Google protobuf issues. This problem boils down to:
How to integrate Google protobuf with Typescript/Javascript for the browser?
I am retaining below question for the future purpose.
We have moved our application from Javascript to Typescript for obvious advantages of OOP etc..
Earlier invoking a direct javascript function from Html was as straight forward as:
<script>window.MyFunction()</script>
Now with Typescript, all the files are combined into a single autogenerated .js file.
In this single file, individual code of every file are isolated within System.register(). It typically looks something like:
System.register("<filename>", ["<import_1>", ..., "<import_N>"],
function (exports_13, context_13) {
"use strict";
...
function MyFunction () { ... } // somewhere inside the external function
}
In short, everything written within the .ts file is wrapped in an unnamed function after running the tsc compiler.
Now, I don't know how to invoke a function, which is trapped inside another function, which is in turn listed under System.register(...)
Question: What is the correct syntax to invoke such function externally from an Html file?
<script> ??? </script>
Update:
The HTML tries to invoke in following way in the body tag:
<script>
System.import("Main").then( // Main.ts is one of the file
function (module)
{
throw 0; // Temporary, to see if we reach till here
module.main(); // "main()" is the function, which is the entry point
});
</script>
In my code, I am using "browserify" to be able to use the Google protobuf for JS. The error comes for the protobuf related files only. Those definition and source files are present in .d.ts and .js formats.
The error is something like below:
js: Uncaught (in promise) Error: Fetch error: 404 NOT FOUND
Instantiating http://localhost:50000/folder/external/Server_pb
Loading http://localhost:50000/folder/external/_External
Loading Main
Note that, 50000 is a temporary port and the "folder" is just any folder where the .js are kept. The "Server_pb" is a custom protobuf file generated.
My problem can be aptly described quite similar as this link.
Related:
What is mean by System.register in JS file?
How to call a named module from a bundle (<-- can be helpful, but don't know the syntax as a newbie)
How to start a Typescript app with SystemJS modules? (nearly duplicate, but unable to solve the problem with this approach yet)
How do I get TypeScript to bundle a 3rd party lib from node_modules? (seems like another close match; trying to dig into this right now to fix the protobuf problem)
With "google-protobuf" there are issues when used in the fashion of systemjs. It seems that Google has created it only for the nodejs. :-)
To be able to use the protobuf in Javascript for the browser, there are few things which we have to do manually. Such manual boilerplate work can be done using some scripts as well.
I am giving an iterative way, on how to achieve this:
The first step is to generate the protobuf for both JS and TS. Use following command for the same:
protoc <file1.proto> <file2.proto> ... <fileN.proto>
--proto_path=<proto_folder> \
--cpp_out=<cpp_folder> \
--js_out=import_style=commonjs,binary:<js_folder> \
--ts_out=import_style=commonjs,binary:<ts_folder>
Note that, we are using the commonjs (and not systemjs). Legends:
<proto_folder> = folder path where all these file1/2/N.proto files are stored
<cpp_folder> = folder path where you want the c++ file1/2/N.pb.cc/h files to be stored
<js_folder> = folder where you want the file1/2/N_pb.js files to be stored
<ts_folder> = folder where you want the file1/2/N_pb.d.ts files to be stored
Now in all the .d.ts (Typescript definition) files, there are certain code lines, which will give compiler errors. We need to comment these lines. Doing manually, is very cumbersome. Hence you may use sed (or ssed in Windows, gsed in Mac). For example, the lines starting with,
sed -i "s/^ static extensions/\/\/ static extensions/g" *_pb.d.ts;
same as above for static serializeBinaryToWriter
same as above for static deserializeBinaryFromReader
sed -i "s/google-protobuf/\.\/google-protobuf/g" *_pb.d.ts; // "./google-protobuf" is correct way to import
Now, while generating the *_pb.d.ts, the protoc compiler doesn't follow the packaging for Typescript. For example, if in your fileN.proto, you have mentioned package ABC.XYZ, then the fileN.pb.h will be wrapped in namespace ABC { namespace XYZ { ... } }. The same doesn't happen in the case of Typescript. So we have to manually add these in the file. However, here it won't be a simple find/replace as above. Rather, we have to find only the first occurance of any export class (which is of generated proto) and wrap the namespaces. So below is the command:
sed -i "0,/export class/{s/export class/export namespace ABC { export namespace XYZ {\\n &/}" fileN_pb.d.ts;
sed -i -e "\$a} }" fileN_pb.d.ts;
Initial importing of the google-protobuf package has to be prefixed with ./ in the case of generated _pb.js file as well
sed -i "s/google-protobuf/\.\/google-protobuf/g" *_pb.js;
Now compile the the custom Typescript files with tsc -p "<path to the tsconfig.json>", where the tsconfig.json may look like (see arrow):
{
"compileOnSave": true,
"compilerOptions": {
"removeComments": true,
"preserveConstEnums": true,
"module": "CommonJS", <=======
"outDir": "<path to generated js folder>",
},
"include": ["../*"],
"files": ["<path to file1.ts>", ..., "<path to file2.ts>"
}
Now a very important step. All the references to the the generated *_pb.d.ts files, should be referred in 1 of your custom file. That custom file may contain the wrappers around the generated classes if it's required. This will help in limiting string replacement only in that file, which is explained in the upcoming step. For example, create a custom file name as MyProtobuf.ts and import your proto as following:
import * as proto from './fileN; // from fileN.d.ts
In above step, it's important to note that the name "proto" is crucial. With that name, the .js files are auto generated. If there are several proto files in your project, then you may have to create yet 1 more file which exports all of them and then import that 1 file:
// in 'MyProtobufExports.ts' file
export * from './file1'
export * from './file2'
export * from './fileN'
import * as proto from './MyprotobufExports // in MyProtobuf.ts file
With above 2 steps, the usage of the protobuf as, var myClass = new proto.ABC.XYZ.MyClass;
Now the continuation of the important step we discussed above. When we generate the equivalent _pb.js and our custom .js files, still the special name-symbol proto will not be found somehow. Even though everything is wrapped. This is because the autogenerated JS files (from TS files), will declare a var proto. If we comment that then, that issue is gone.
sed -i "s/var proto = require/\/\/ &/g" Protobuf.js;
The final step is to put the browserify on all the .js files into a single file, as below. Due to this, there will be only single .js file, we have to deal with [good or bad]. In this command, the ordering is very important. file1_pb.js should come before file2_pb.js, if file1.proto is imported by file2.proto or vice a versa. If there is no import then the order doesn't matter. In any case the _pb.js should come before the custom .js files.
browserify --standalone file1_pb.js fileN_pb.js MyProtobuf.js myfile1.js myfileN.js -o=autogen.js
Since the code is browserified, the calling of function can be done in following way:
window.main = function (...) { ... } // entry point somewhere in the fileN.ts file
<script>main(...)</script> // in the index.html
With the above steps only, I am able to make the "google-protobuf" work within my project for the browser.

Writing .d.ts file so I can share constants with JavaScript and TypeScript?

I'm working on a node.js project that for historical reasons involves both TypeScript and JavaScript. I'd like to set up some project-wide constants that can be used in both languages. Obvious: write a .js file with the constants, and a .d.ts file that includes the types for TypeScript's use. But no: several hours of beating on the problem (and RTFMing) have gotten me nowhere.
Here's my first try at the constants file:
// constants.js
const MY_CONST_1 = 1;
exports.MY_CONST_1 = MY_CONST_1;
... and the JavaScript which uses it:
// consumer.js
let constants = require('./constants');
let one = constants.MY_CONST_1;
That works well, but when I try the obvious in TypeScript:
// consumer.ts
import * as constants from './constants';
let one: number = constants.MY_CONST_1;
Nope: error TS2307: Cannot find module './constants'. So, gotta write a constants.d.ts file, in the same directory as the constants.js file, right? Sounds easy, but a half dozen different attempts have yielded exactly zilch. No matter what I do, Typescript complains error TS2306: File '/Users/griscom/Documents/Work/test/constants.d.ts' is not a module.
So, what would a successful constants.d.ts file look like? Or, if I'd have to make changes in constants.js for it all to work, what would they be?
P.S. Here's my tsconfig.json file:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": true,
"noImplicitReturns": true
}
}
(This seems like such a simple and obvious need; it's frustrating how opaque the process is.)
Option 1: allowJs
Try using the compiler option allowJs: true. This will allow your original import from ./constants to work even though it's a .js file, without the need to create a separate .d.ts file. TypeScript will understand inferrable types from the .js file, for example you will get type checking against MY_CONST_1 as a number.
As you said in your comment this requires separating your source files from your output files, because it can't output a JS file at the same location as a JS source file.
Option 2: constants.d.ts declaration file
Given your source file that looks like this:
// constants.js
export const MY_CONST_1 = 1;
You can write a constants.d.ts file that looks like this:
// constants.d.ts
export const MY_CONST_1: number;
Where you were off in your previous attempts is using the declaration module, which is used to declare types for external modules (like from node_modules). In this case simply putting the constants.d.ts file in the same directory as constants.js and using export will tell TS that it's a JS module that exports that value:
import { MY_CONST_1 } from "./constants";
import * as constants from "./constants";
Something important to keep in mind is that the .d.ts file is not checked against the .js file to ensure it's actually correct, that's on you. So if you make a change to the .js file you have to make sure to update the .d.ts file accordingly and correctly. A compile error or lack of compile error does not mean it's correct or not. This is one reason allowJs exists because it avoids such leaks.
export const MyConst =1;
Or
export class MyGroup {
static MyConst: number
}
Generally stay clear of modules since that isnt compatible with the meaning of modules in inports. Instead use "namespace" which is very similar to a class with static members. Meaning you could probably do (on phone and cant try it out):
export namespace MyNamespace {
export const MyConst = 1;
}
But lastly try avoid wrapping things in extra namespaces and classes etc since the import syntax is the module. Also it makes your code treeshakeable.
Another option: using an import for side effects only. Indeed, your constants are global, i.e. not defined in a module due to the missing export keyword:
import './constants';
To be used in combination with the allowJs compiler option mentionned in an another response.

Using CodeLens for JavaScript in VSCode

I'm trying to get CodeLens working for a JavaScript project in VSCode. I've seen multiple sources indicate that this should work, but nothing with clear instructions on how to enable it besides the basic settings.
I have the following files in my workspace:
test.js
function test ( a, b ) {
return a + b;
}
test( 1, 2 );
jsconfig.json
{
"compilerOptions": {
"target": "ES5",
"checkJs": true
},
"include": [
"*"
]
}
And in my user settings I have the following:
"javascript.referencesCodeLens.enabled": true
(editor.codeLens is enabled by default.)
I've toggled and saved my preferences several times. I've restarted VSCode a few times as well. Still, I don't see any CodeLens information within my JavaScript.
Did I miss something? Am I doing something wrong? Do I even need the jsconfig.json file to enable this?
VSCode 1.17.0.
As of VS Code 1.17, we only show JS/TS references code lenses on classes, methods, and exports.
This issue tracks showing them in more locations, including on functions as in your example.

Using browsers navigator results in JShint error

I'm using the globally available navigator object that the browser exposes in an Ember-CLI project (aka, with ES6 syntax) and I'd like to avoid getting errors when referencing this valid global object.
I saw this suggestion: Ember CLI - Error when using moment.js in route and tried added ['navigator'] to the predef definition in the .jshintrc file. Didn't seem to have any impact. I also then put the following into the JS file itself:
/* global navigator: false */
That worked but I still feel the .jshintrc alternative would be nice. Is there a way to achieve this? Why didn't my attempt have the desired results in the same way that the momentjs example did?
BTW, here is the default setting that Ember-CLI puts in:
"predef": [
"document",
"window",
"-Promise"
]
The existing answer isn't wrong, exactly, but it does have the wrong format, and doesn't make clear that there is a seperate .jshintrc file for tests. In my case, this was the one that needed to be updated.
In tests/.jshintrc (which is different from the main .jshintrc) add "navigator" to the "predef" array, like so:
{
"predef": [
"document",
"window",
"navigator",
"location",
...
]
}
In .jshintrc file, you should do it that way:
{
"predef": {
"navigator": true
}
}
Hope this helps! :)

Resources