Angular - cant find name 'Map' - javascript

I started to study Angular, but i can't get trough the problem with convert typescript file to javascript. I've created AngularCLI project and simple typescript file:
class Example {
msg = 'Some message';
}
and i tried to convert it to js with tsc command: tsc example.tsc. This is javascript file which was generated:
var Example = /** #class */ (function () {
function Example() {
this.msg = 'Some message';
}
return Example;
}());
And i've got some errors
node_modules/#types/selenium-webdriver/remote.d.ts:139:29 - error TS2583: Cannot find name 'Map'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
I think (or even sure) the problem is in javascript version (even error says that). This is tsconfig.json file:
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"module": "es2015",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"target": "es5",
"typeRoots": [
"node_modules/#types"
],
"lib": [
"es2018",
"dom"
]
}
}
So i did what was suggested. I changed module, target, lib to atleast es2015 (
everything together and each separately) - it didnt help. I tried a lot of solutions from SO, jetbrain forum etc but nothing worked for me.
I use webstorm 2018.3 version. Node version is 10.14.1. Tsc version is 3.1.6.

Your updated tsconfig.json looks good now that it targets es2018. The problem now is how you are compiling. When I asked how you compile you wrote:
... with command line in webstorm using: "tsc filename.tsc" comand.
When we pass files to the compiler, the compiler ignores our tsconfig.json. The official tsconfig.json documentation says this:
When input files are specified on the command line, tsconfig.json files are ignored.
If you want to pass specific files on the command line and to compile with specific options, pass those options (e.g. the lib option) on the command line.
tsc filename.ts --lib es2018

Related

Module '"domhandler"' has no exported member 'DomElement'. Did you mean to use 'import DomElement from "domhandler"' instead?

I trying to build a react-typescript project. ii didn't install dom utils and HTML parser libraries. but when I tried to run yarn build, the following error is coming
~~~~~~~~~~
../node_modules/#types/htmlparser2/index.d.ts:17:10 - error TS2614: Module '"domhandler"' has no exported member 'DomElement'. Did you mean to use 'import DomElement from "domhandler"' instead?
17 export { DomElement, DomHandlerOptions, DomHandler, Element, Node } from 'domhandler';
~~~~~~~~~~
../node_modules/#types/react-html-parser/index.d.ts:9:10 - error TS2305: Module '"htmlparser2"' has no exported member 'DomElement'.
9 import { DomElement } from "htmlparser2";
I tried some of follwoing steps,
added "skipLibCheck": true in tsconfig.json file
https://github.com/apostrophecms/sanitize-html/issues/333 i tried some steps whatever they said, still no use.
tsconfig.json file
{
/* https://www.typescriptlang.org/docs/handbook/react-&-webpack.html */
/* https://www.typescriptlang.org/docs/handbook/compiler-options.html */
"compilerOptions": {
"target": "es5",
"module": "commonjs" /* webpack supports imports syntax */,
"jsx": "react",
"lib": ["es5", "dom", "es2015"],
"strict": true,
"moduleResolution": "node" /* load modules like node */,
"esModuleInterop": true /* to treat commonJS 'module.exports' as 'default export' */,
"importHelpers": true,
"skipLibCheck": true,
}
}
This might be a duplicate question. But I don't know how to solve this issue, can someone help me for solving this??
If you have these errors just check your package.json.
Possibly you installed unwanted type definitions because htmlparser2 package has all necessary type definitions from the box.
If so then delete it and use #Kasunaz's answer.
I fixed this issue by configuring Typescript (editing tsconfig.json) to "Skip type checking of declaration files." (docs):
{
"compilerOptions": {
"skipLibCheck": true,
...
}
}

Import from index.ts returns undefined

I have this very simple file structure consisting of
src
index.ts
services
my-service.ts
In index.ts I have the following
export const a = 3
and in my-service.ts I do,
import { a } from '../index'
console.log(a);
this logs undefined.
When I do
setTimeout(() => console.log(a), 100);
it logs 3.
I am running the solution using
ts-node -r tsconfig-paths/register ./src/index.ts
my tsconfig looks like
{
"extends": "../../tsconfig.json",
// "include": ["src/**/*.ts"],
"compilerOptions": {
"outDir": "dist",
"allowJs": false,
"baseUrl": ".",
"rootDir": "src",
"composite": true
},
"references": [
{
"path": "../shared-tools"
}
],
"exclude": ["dist"],
"include": ["src/**/*.ts"]
}
Which extends the following root tsconfig
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
// "baseUrl": ".",
"allowJs": false,
"sourceMap": true,
"declaration": true,
"declarationMap": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"types": [],
"typeRoots": [
"./node_modules/#types"
],
"paths": {
"#project/shared-tools": [
"../shared-tools/src"
]
}
}
}
That symptom suggests you have a cycle of dependencies between index.ts and my-services.ts — in addition to the dependency you've described on a in index.ts, index.ts relies on something supplied (directly or indirectly) by my-services.ts. This is called a cyclic dependency. A depends on B which depends on A.
With JavaScript's now-standard ESM static module syntax, cycles are possible but normally they can be resolved without your having to worry about them. In cases where they can't, instead of getting undefined, you get an error (if you use const as you have).
But you're telling TypeScript to rewrite your module syntax into Node's original CommonJS-inspired syntax (module.exports and require() calls). With CJS, cycles can result in your seeing undefined for things that later have a value assigned when all the module code has been run.
Ideally, the solution is to remove the cyclic dependency. If index.ts has to depend on my-services.ts, perhaps move whatever my-services.ts imports from index.ts to something else they both import from. That way, A and B both depend on C rather than on each other.
If for some reason you can't do that, you might try telling TypeScript to output JavaScript module syntax instead ("module": "ES2015" or "module": "ESNext"). Since that does static resolution (if you don't use dynamic import()), it may be able to handle the cycles for you. Node now has robust support for ESM.
Or you may not need to handle it. Even in CJS, cyclic dependencies are really only a problem if you use the dependencies in the initial module code rather than in code that runs later in response to an event (as you saw by wrapping your code using a in a setTimeout). So if the resources involved in the cycles are only needed to (for instance) respond to a network request, you may not need to worry about it at all. There's a bit more about cycles in CJS modules in Node here.

TypeScript -> JavaScript for browser: exports/require statements

I want to switch from JavaScript to TypeScript for our web app's scripts. However, when generating the JavaScript it always puts the following lines on top of the script:
"use strict";
exports.__esModule = true;
var $ = require("jquery");
I receive browser errors for this. How to prevent TypeScript from doing so?
I read TypeScript: Avoid require statements in compiled JavaScript but it can't be the answer to switch to "any", this forfeits the whole TypeScript idea.
I also read Typescript importing exported class emits require(...) which produces browser errors but this still generates the <reference... stuff into the JS file, which is also not what I want.
How to create "clean" JS files?
My tsconfig.json looks like this:
{
"compilerOptions": {
"noImplicitAny": true,
"noEmitOnError": true,
"sourceMap": true,
"target": "es5"
},
"compileOnSave": true
}
My gulp call is:
var ts = require('gulp-typescript');
...
var tsProject = ts.createProject("tsconfig.json");
...
gulp.task("ts", function () {
return gulp.src(tsInputFiles)
.pipe(tsProject())
.js
.pipe(gulp.dest("wwwroot/js"));
});
Just drop the module loading in the beginning of your typescript file, if you do not want to load any modules?
file1.ts:
$(function () {
});
If you try to compile this, you'll get an error:
file1.ts(2,1): error TS2581: Cannot find name '$'. Do you need to
install type definitions for jQuery? Try `npm i #types/jquery` and
then add `jquery` to the types field in your tsconfig.
Run npm as told above (npm init first, if npm has not been initialized in the directory).
Then add typeRoots and types to tsconfig:
{
"compilerOptions": {
"noImplicitAny": true,
"noEmitOnError": true,
"sourceMap": true,
"target": "es5",
"typeRoots": [ "node_modules/types" ],
"types": [ "jquery" ]
},
"compileOnSave": true
}
After that, the compiling works, and you still have the strong typing in place (jquery types applied in compilation).
Browsers don't support JavaScript modules, so you'll need to tell the TypeScript compiler that you're trying to compile code that will be run on a browser. I don't know what the rest of your project looks like, but in your configuration, try adding "module": "es2015" or "module": "system" to your configuration, while also adding an outFile defining where you want to file to be generated :
in your tsconfig file :
{
"compilerOptions": {
"noImplicitAny": true,
"noEmitOnError": true,
"sourceMap": true,
"target": "es5",
"module": "es2015",
"outFile": "script.js",
},
"compileOnSave": true
}
I wanted to use TypeScript files injected directly into a HTML file via gulp task (compiled into es5).
At first adding type="module" to <script> helped. But then more problems appeared, so finally I've end up using this notation instead of import:
/// <reference types="#types/jquery" />
/// <reference path="my_custom_file.ts" />
/// <reference path="my_externalTypes.d.ts" />
and namespace in each of the file to separate them from each other.
That should work for a simple, small projects.

What would cause a unexpected token in typescript outputed map file?

I have a typescript project with a tsconfig.json
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"sourceMap": true,
"inlineSources": true,
"lib": [
"es6",
"dom"
],
"types": [
"node"
],
"moduleResolution": "node",
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
I am running a script "test:integration": "./node_modules/typescript/bin/tsc && mocha test/integration/** --recursive"
I then see:
/Users/mm81509/projects/coverpath-producer-management/test/integration /Example.js.map:1
(function (exports, require, module, __filename, __dirname) { {"version":3,"file":"Example.js","sourceRoot":"","sources":["Example.ts"],"names":[],"mappings":"","sourcesContent":[""]}
^
SyntaxError: Unexpected token :
...
What would cause the typescript compiler make a syntax error in the map.js? I am only seeing this error in that one file in the project.
You're getting the error on a .map file. These files are for mapping source lines to compiled lines. Adjust the glob pattern you pass to Mocha so that it does not try to load the .map files as test files. Something like:
mocha 'test/integration/**/*.js' --recursive
It will only load the .js files and not the .map files. And I suggest putting the single quotes to protect the pattern from being expanded by your shell. You want the pattern to be passed to Mocha as is instead of being interpreted by the shell.

Typescript outfile with System.JS - Module instantiation error

I'm using TypeScript to generate a single outFile that compiles my modules, loaded with SystemJS. When I follow the documentation on loading bundles, as suggested by this SO answer, I get an error:
Uncaught (in promise) Error: Module instantiation did not call an anonymous or correctly named System.register.
Instantiating http://localhost:50001/Content/js/app.js
Loading app.js
at vendor.js?v=c419d08…:4
Here is the setup script in my index.html file:
SystemJS.import("/Content/js/app.js").then(function (mod) {
return SystemJS.import("admin/js/startup");
});
app.js looks like this:
System.register("shared/js/utilities", [], function (exports_1, context_1) {
...
});
System.register("admin/js/startup", ["shared/js/utilities"], function (exports_2, context_2) {
...
});
My tsconfig.json, if it helps:
{
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es5",
"module": "system",
"outFile": "app.js"
},
"compileOnSave": true,
"exclude": [
"node_modules",
"wwwroot"
]
}
UPDATE: I had been using systemjs/dist/system-production.js, because the documentation states that modules already transpiled into the System.register format, which is done by TypeScript, can be loaded by the production loader. If I switch to using systemjs/dist/system.js, I do not get the errors. I still don't see how I am getting this error from the production loader if I'm already working with System.register formatted modules.

Categories

Resources