How could I refer typings to be included at runtime? - javascript

my question (in details) might have duplicates here but I couldn't be able to get answeres since I have spent 3 days searching for it.
I am new to typescript and want to run a TS project (and not any angular 2 thing in it) using 'npm start' command. Please have a look at below code:
My directory structure is:
myClass.ts (it is inside module directory)
export namespace Classes {
export class NewClass {
constructor(public msg:string){}
displayMessage ():string{
return this.msg;
}
};
};
greeter.html
<!DOCTYPE html>
<html>
<head><title> TypeScript Greeter </title></head>
<body>
<script src='greeter.js'></script>
</body>
</html>
greeter.ts
import {Classes} from 'module/myClass';
class Greeter extends Classes.NewClass {
constructor(public greeting: string) {
super('');
}
greet() {
return "<h1>" + this.greeting + "</h1>";
}
};
var greeter = new Greeter("Hello, world!");
var newClass = new Classes.NewClass("This is my message.");
document.body.innerHTML = greeter.greet() + newClass.displayMessage();
package.json
{
"name": "greeter",
"version": "1.0.0",
"description": "Sample TS app",
"main": "greeter.ts",
"scripts": {
"start": "tsc && http-server"
},
"keywords": [
"TS"
],
"author": "",
"license": "MIT",
"dependencies": {
}
}
tsconfig.json
{
"compilerOptions": {
"baseUrl": "./",
"sourceMap": true,
"module": "commonjs",
"outDir": "./out"
},
"files": [
"greeter.ts",
"module/myClass.ts"
]
}
typings.json
{
"globalDependencies": {
"node": "registry:dt/node#6.0.0+20160928143418"
}
}
My queries are:
I have included 'dt~node' typings after watching a few tutorials, but is it necessary here in this scenario ?
I am from javascript background, so I am not sure how to include the typings files in my project. Do I need to include reference path in greeter.html for typings files or something else. Please specify this.
I am unable to make it work as browser console displays this error after running 'npm start' in window's command:
Please help if anyone could guide me to resolve my queries. Thank you.

Related

How do I utilize this javascript library in node.js?

I'm relatively new to node.js and am attempting to utilize a javascript library without any success.
The library itself is psn-api.
To set up for usage I have:
Installed node.js locally
Created my project folder
Ran npm init and successfully created package.json
Ran npm install i -s psn-api which has successfully installed psn-api to my project folder in node-modules and updated the dependencies in package.json.
I've copied the sample code from the psn-api github (see below) and saved as index.ts file in my project folder.
I run npx tsc --init which generates my tsconfig.json file
I run npx tsc index.ts which compiles into index.js
I run node index.js
Sample code (index.ts):
import * as fs from "fs";
import type { Trophy } from "psn-api";
import {
exchangeCodeForAccessToken,
exchangeNpssoForCode,
getTitleTrophies,
getUserTitles,
getUserTrophiesEarnedForTitle,
makeUniversalSearch,
TrophyRarity
} from "psn-api";
async function main() {
// 1. Authenticate and become authorized with PSN.
// See the Authenticating Manually docs for how to get your NPSSO.
const npsso = "xxxxxxxx";
const accessCode = await exchangeNpssoForCode(npsso);
const authorization = await exchangeCodeForAccessToken(accessCode);
// 2. Get the user's `accountId` from the username.
const allAccountsSearchResults = await makeUniversalSearch(
authorization,
"xelnia",
"SocialAllAccounts"
);
const targetAccountId =
allAccountsSearchResults.domainResponses[0].results[0].socialMetadata
.accountId;
// 3. Get the user's list of titles (games).
const { trophyTitles } = await getUserTitles(authorization, targetAccountId);
const games: any[] = [];
for (const title of trophyTitles) {
// 4. Get the list of trophies for each of the user's titles.
const { trophies: titleTrophies } = await getTitleTrophies(
authorization,
title.npCommunicationId,
"all",
{
npServiceName:
title.trophyTitlePlatform !== "PS5" ? "trophy" : undefined
}
);
// 5. Get the list of _earned_ trophies for each of the user's titles.
const { trophies: earnedTrophies } = await getUserTrophiesEarnedForTitle(
authorization,
targetAccountId,
title.npCommunicationId,
"all",
{
npServiceName:
title.trophyTitlePlatform !== "PS5" ? "trophy" : undefined
}
);
// 6. Merge the two trophy lists.
const mergedTrophies = mergeTrophyLists(titleTrophies, earnedTrophies);
games.push({
gameName: title.trophyTitleName,
platform: title.trophyTitlePlatform,
trophyTypeCounts: title.definedTrophies,
earnedCounts: title.earnedTrophies,
trophyList: mergedTrophies
});
}
// 7. Write to a JSON file.
fs.writeFileSync("./games.json", JSON.stringify(games));
}
const mergeTrophyLists = (
titleTrophies: Trophy[],
earnedTrophies: Trophy[]
) => {
const mergedTrophies: any[] = [];
for (const earnedTrophy of earnedTrophies) {
const foundTitleTrophy = titleTrophies.find(
(t) => t.trophyId === earnedTrophy.trophyId
);
mergedTrophies.push(
normalizeTrophy({ ...earnedTrophy, ...foundTitleTrophy })
);
}
return mergedTrophies;
};
const normalizeTrophy = (trophy: Trophy) => {
return {
isEarned: trophy.earned ?? false,
earnedOn: trophy.earned ? trophy.earnedDateTime : "unearned",
type: trophy.trophyType,
rarity: rarityMap[trophy.trophyRare ?? 0],
earnedRate: Number(trophy.trophyEarnedRate),
trophyName: trophy.trophyName,
groupId: trophy.trophyGroupId
};
};
const rarityMap: Record<TrophyRarity, string> = {
[TrophyRarity.VeryRare]: "Very Rare",
[TrophyRarity.UltraRare]: "Ultra Rare",
[TrophyRarity.Rare]: "Rare",
[TrophyRarity.Common]: "Common"
};
I've run around in circles with possible fixes such as adding "type":"module" to the package.json, trying to import or otherwise define psn-api in my js file but I keep hitting error after error. I'm sure there's some fundamental misunderstanding I have. I'd really appreciate if someone could outline the direct steps I need to take to get the sample script running in the cmd line.
My package.json as it stands:
{
"name": "psnapitest",
"version": "1.0.0",
"description": "",
"main": "index3.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"#types/node": "^18.6.2",
"psn-api": "^2.7.0"
},
"type": "module",
"devDependencies": {
"#tsconfig/node16": "^1.0.3",
"typescript": "^4.7.4"
}
}
My tsconfig.json as it stands (after advice in comments):
{
"compilerOptions": {
"target": "es2016",
"module": "es6",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true
}
}
Current error when running compiled js:
Now compiles with no issues.
I run node index.js and get the following error
exports.__esModule = true;
^
ReferenceError: exports is not defined in ES module scope
I tried this locally and no error
when using node library you need to set "moduleResolution": "node" on your tsconfig.json
index.ts
import fs from 'fs'
package.json
{
"name": "psn-api-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "tsc index.ts",
"start": "node index.js"
},
"type": "module",
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"psn-api": "^2.7.0"
},
"devDependencies": {
"#types/node": "^18.6.2",
"typescript": "^4.7.4"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "es2016",
"module": "es6",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true
}
}
Try instead of using import, use require:
const fs = require('fs')
const psn = require('psn-api')
type { Trophy } = psn
const { exchangeCodeForAccessToken } = psn
const { exchangeNpssoForCode } = psn
const { getTitleTrophies } = psn
const { getUserTitles } = psn
const { getUserTrophiesEarnedForTitle } = psn
const { makeUniversalSearch } = psn
const { TrophyRarity } = psn
Also, instead of compiling it to node.js, try using this library:
https://www.npmjs.com/package/ts-node
Its basicly node.js but for typescript

VS Code: Lit custom element not rendering properly

I've copied/pasted the code from lit.dev's playground page to troubleshoot and attempt to get Lit running in VS Code before working on my own project. I was able to troubleshoot most of my issues and finally got it to run correctly, but it seems that the custom element 'simple-greeting' is simply not rendering upon launch.
Here's my html:
<!DOCTYPE html>
<head>
<script type="module" src="./app.js"></script>
</head>
<body>
<simple-greeting name="World"></simple-greeting>
</body>
Here's my js:
import {html, css, LitElement} from 'lit';
export class SimpleGreeting extends LitElement {
static styles = css`p { color: blue }`;
static properties = {
name: {type: String},
};
constructor() {
super();
this.name = 'Somebody';
}
render() {
return html`<p>Hello, ${this.name}!</p>`;
}
}
customElements.define('simple-greeting', SimpleGreeting);
Here's my launch.json:
{
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome against localhost",
"file": "${workspaceRoot}/index.html"
}
]
}
Here's my jsconfig:
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"experimentalDecorators": true,
"allowJs": true
},
}
And finally, here's my package.json:
{
"name": "epigraph_tictactoe",
"version": "1.0.0",
"description": "",
"main": "index.html",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Cameron Crane",
"license": "ISC",
"type": "module",
"dependencies": {
"common-js": "^0.3.8",
"lit": "^2.2.0",
"ts-node": "^10.7.0"
}
}
Why won't my custom element render? Chrome itself launches, but the page is blank unless I add another test component like <p>Hello, World!</p>, which seems to work just fine.
Had a similar issue with a different project and it looks like the issue was that I was either running my code through the Live Server extension on VS Code, or I was not running a web server at all.
Starting a web dev server using this seemed to fix the issue.

TypeScript cannot find namespace

I am trying to create a web game using webGL, TypeScript and node.
I have a file structure that currently looks like this
> node_modules
> src
engine.ts
webgl.ts
index.ts
index.html
package.json
engine.ts looks like this:
namespace EngineSpace {
export class Engine {
// ....
}
}
and webgl.js:
namespace EngineSpace {
export class WebGLUtil {
// ....
}
}
and index.js
window.onload = function() {
let engine = new EngineSpace.Engine();
engine.start();
}
However when I run npm start, I get that src/index.ts:5:22 - error TS2304: Cannot find name 'EngineSpace'..
I am not sure why it cannot resolve this namespace. Given that I am trying to create a game, how should I have this set up / what would be best practices?
below is the package.json: file
{
"name": "typescript-engine",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "npm run build:live",
"build": "tsc -p .",
"build:live": "nodemon --watch 'src/**/*.ts' --exec 'ts-node' src/index.ts"
},
"repository": {
"type": "git",
"url": ""
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": ""
},
"homepage": "",
"devDependencies": {
"#types/node": "^12.11.1",
"nodemon": "^1.19.4",
"ts-node": "^8.4.1",
"typescript": "^3.6.4"
}
}
here is the tsconfig:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"lib": ["es6","dom"],
"outDir": "lib",
"rootDir": "src",
"strict": false,
"esModuleInterop": true,
"resolveJsonModule": true
}
}
If you want to use namespace in nodejs side you need to export it also to use it in another module. Becuase namespace will be converted like this
engine.ts
namespace EngineSpace {
export class Engine {
public start() {
console.log('hello');
}
}
}
enigne.js
var EngineSpace;
(function (EngineSpace) {
class Engine {
start() {
console.log('hello');
}
}
EngineSpace.Engine = Engine;
})(EngineSpace || (EngineSpace = {}));
And if you want to use some property of another module in nodejs you need to export it and need to require it in another module.
Refer this for nodejs namespace
For the browser setup with typescript please refer this
Hope it helps you

Exported function is undefined

I'm facing an issue with my Mocha tests in Typescript, I fear it is related to Babel, but I am really not sure what's happening.
Essentially, I have a function that is being exported in a file
// src/my-ts-lib/tests/components/factoryMocks/componentConfigMocks.ts
...
export function getRandomConfig(type?: string): ComponentConfig {
const randomComponentType = type || randomType();
return {
type: randomComponentType,
config: configLibrary[randomComponentType]
}
}
And being imported in another, which is being called by a test:
// src/my-ts-lib/tests/components/RouteComponent/mocks/routeMocks.ts
...
import { getRandomConfig } from '../../factoryMocks/componentConfigMocks';
..
export const getSingleRouteConfigMock = (componentType?: string): RouteProps => {
const defaultComponentType = 'PageLayout';
return {
childComponent: {
type: componentType || defaultComponentType,
config: getRandomConfig(componentType || defaultComponentType)
},
pageName: randomString(),
path: randomString(),
};
};
...
When running the tests, I get the following error:
RouteCompnent/mocks/routeMocks.ts:10
config: getRandomConfig(componentType || defaultComponentType),
^
TypeError: componentConfigMocks_1.getRandomConfig is not a function
at Object.exports.getSingleRouteConfigMock (/Users/.../routeMocks.ts:10:44)
If I comment the call and console.log(getRandomConfig) I can see that it is undefined. I do not know why this is happening. What's even weirder is that, in subsequent tests that call getSingleRouteConfigMock, this same console.log correctly outputs the function, meaning that it has been exported then.
I've fiddled around with Babel, Mocha, and Typescript configs but have had no success.
Here's the Babel config:
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
The Mocha config:
mocha.opts
--require ts-node/register
--watch-extensions ts tsx
--require source-map-support/register
--recursive
--require #babel/register
--require #babel/polyfill
src/**/*.spec.**
And the Typescript config:
tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": false,
"module": "commonjs",
"target": "es6",
"jsx": "react"
},
"include": [
"./src/**/*"
],
"exclude": [
"./src/**/*.spec.ts",
"./src/my-ts-lib/components/**/*.spec.tsx",
"./src/my-ts-lib/test-helpers/*"
],
}
And the relevant sections of the package.json
...
"dependencies": {
...
"#babel/polyfill": "7.2.x",
...
},
"devDependencies": {
"#babel/core": "7.2.x",
"#babel/preset-env": "7.2.x",
"#babel/preset-react": "7.0.x",
"#babel/register": "7.0.x",
"babel-loader": "8.x",
"mocha": "3.2.x",
...
}
I found out I have a circular dependency. That's why this was not working.
Another possible cause for this symptom is that the function is actually missing in the module when you use a bundler like Parcel in production mode and it removes unused items (that particular issue discussed at Empty Javascript File When Building With Parcel JS 2 ). Check the compiled module file and make sure that the name exists.

Debugging a simple Typescript app in a Browser using VSCode

I am building my first typescript project (my background is C#, Java).The apps works as expected, but i can't put a break point in typescript and debug the application.
Also when i use pure typescript compiler (tsconfig with tsc.exe) the mapping works perfectly. I am using gulp since i want to bring all js into one file.
When there is a mistake in the generated js, then visual studio code is hitting the break point in js file (bundle.js) instead of typescript, however custom break points never work
I am using windows 10 for development.
Please find my code below.
The HTML
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World!</title>
<!-- <script data-main="main" src="scripts/require.js"></script> -->
</head>
<body>
<p id="greeting">Loading ...</p>
<script src="bundle.js"></script>
</body>
</html>
Type scripts
main.ts
import { Student } from "./student";
class Startup {
public static main(): string {
return Startup.showHello();
}
public static showHello() : string {
var std = new Student();
return std.GetText();
}
}
document.getElementById("greeting").innerHTML = Startup.main();;
student.ts
export class Student
{
public GetText() : string
{
return "Hi from VB ggggggggggg";
}
}
Gulpfile.js
'use strict';
var gulp = require("gulp");
var ts = require("gulp-typescript");
var tsProject = ts.createProject("tsconfig.json");
var browserify = require("browserify");
var source = require('vinyl-source-stream');
var tsify = require("tsify");
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var buffer = require('vinyl-buffer');
var paths = {
pages: ['src/*.html']
};
gulp.task("copy-html", function () {
return gulp.src(paths.pages)
.pipe(gulp.dest("dist"));
});
gulp.task("default", ["copy-html"], function () {
return browserify({
basedir: '.',
debug: true,
entries: ['src/student.ts','src/main.ts'],
cache: {},
packageCache: {}
})
.plugin(tsify)
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest("dist"));
});
tsconfig.json (i believe this file is not needed since we use gulp to compile, When using pure typescript compile the break points work as expected)
{
"compilerOptions": {
"module": "commonjs",
"outDir": "dist",
"target": "es5",
"sourceRoot": "src",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
// "outFile": "dist/bundle.js",
"sourceMap": true
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
also launch.js
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome",
"url": "http://localhost:8080/index.html",
"sourceMaps": true,
"webRoot": "${workspaceRoot}/dist",
},
{
"name": "Launch localhost with sourcemaps",
"type": "edge",
"request": "launch",
"url": "http://localhost:8080/index.html",
"webRoot": "${workspaceRoot}/dist",
"sourceMaps": true
},
]
}

Categories

Resources