Using TypeScript Declaration For External JavaScript Library - node.js

I'm not sure if this extreme edge case or something but I cannot seem to find straight forward documentation on how to do this (or I'm just really not understanding what is available):
I am developing an ionic application and as part of that I need to use the ALKMaps JavaScript library (which is similar to Google Maps API). To do so, I created a local npm module and within that I created a alkmaps.d.ts file as recommended by https://www.typescriptlang.org/docs/handbook/declaration-files/by-example.html#objects-with-properties). However, I cannot seem to figure out how to properly import it into my angular code. The same document suggests that using <reference path=''> tags is not good but that is the only thing that seems to satisfy the tsc compiler.
My declaration file, alkmaps.d.ts, looks like (inside excluded for brevity):
declare namespace ALKMaps {
export class Map { ... }
...
}
And I was trying to import it into a file like:
import { ALKMaps } from 'alkmaps'; // Error: File '.../alkmaps.d.ts' is not a module
I also tried the following but got the same error.
import ALKMaps = require('alkmaps');
Using the reference tag seems to work within this module but then the project that utilizes this module still throws the "is not a module" error (that might warrant a separate question)
From https://github.com/Microsoft/TypeScript/issues/11420 I found the idea of using export = ALKMaps or export as namespace ALKMaps but adding those to my declaration file resulted in different errors instead.
Can anyone please explain in a straightforward way how to use declaration files representing external JS libraries in a typescript node module?

This is how I was able to get alkMaps into my Angular 2 app
Insert the script into the index.html file.
Declare an ALKMaps variable in the component that you are adding the map
imports .....
declare let ALKMaps : any;
#Component({
selector: 'show-map',
templateUrl: 'show-map.component.html'
})
export class ShowMapComponent implements Oninit{
map : any;
constructor() {
}
ngOnInit() {
ALKMaps.APIKey = "apiKey";
this.map = new ALKMaps.Map("map", {displayProjection: new ALKMaps.Projection("EPSG:4326")});
}
}
This will get the map to display and you can put different layers on the map, however the map does not display correctly. #Mike, if you were able to get further than this, will you please comment?
EDIT: The tiles on the image were elongated and not connected. After inspecting the css the main.css, after building, set a global property on the img element to:
img {
max-width:100%
}
The tiles for the map are originally set to 256% for the width. To correct the element, I changed the property for img in the style sheet.
show-map {
img {
max-width: 256%
}
}

Related

How to add types for third-party components in vue SFC template?

I am using volar+vue2+ts+composiiton api. In SFC templates, for custom components, volar is able to perform type checks and give the following message when some errors encountered. It benefits me a lot.
I wonder if the type check is also applicable on components from third-party packages such as element-ui. When hovering over tags like el-*(components from element-ui), volar says it has the type of any and type check is not available. For jsx components, one can add types to the IntrinsicElements in shims-tsx.d.ts. But IntrinsicElements doesn't work for SFC templates. Is it possible to add types for third-party components?
import Vue, { VNode } from 'vue';
declare global {
namespace JSX {
interface Element extends VNode {}
interface ElementClass extends Vue {}
interface IntrinsicElements {
// JSX can add types here
'el-button': any;
[elem: string]: any;
}
}
}
As #Finn said, element-ui has added types. Unfortunately, even though El* classes are imported and registered via vue's components option, volar seems to be unable to do type checks. Here ElHeader is expected to have a prop named height of type string. But it is assigned a number without any error message
The following code snippet comes from the source of element-ui
export declare class ElHeader extends ElementUIComponent {
/** Height of the header */
height: string
}
Element-ui for vue2 has added components type declare in package,
so volar's type checks follows the package's types declaration.

How to do lazy export in Typescript

Module: shared-module
export * from "./common-types";
export * from "./lots-of-large-classes"
Let's say I have 200 large classes and import the above module like
Module: Main
import { CommonTypeClass } from "shared-module"
Now all 200 classes "also" will load as they are resolved in static scope and referred in my import.
To avoid this I tried
Object.defineProperty(module.exports, 'lots-of-large-classes', {
// The lots-of-large-classes folder is very large. To avoid pulling it in from static
// scope, we lazy-load the module.
get: () => require('./lots-of-large-classes'),
});
But VS Code isn't showing the lots-of-large-classes import.
import { LargeClassOne } from 'shared-module/lots-of-large-classes'; // ISN'T WORKING
However, above solution also still loads all classes as there is an index file which loads all classes.
How can I selective load LargeClassOne from lots-of-large-classes folder without loading other classes through shared-module?
Something like with overhead of loading one large class alone which is being imported.
import { LargeClassOne } from 'shared-module/lots-of-large-classes';
It's not possible to statically import dynamically-loaded data. Using subpath exports in the package.json for "shared-module" will help you accomplish your goal.
You can combine this with TypeScript's path mapping feature for very flexible import specifiers.

Put data on ServersideProps

Is it possible to get data from server side's config file on client by getServersideProps() in Next.js? How to put data in props? Or how to get it on client in other way?
I have tried publicRuntimeConfig in next.config.js, but it is undefined and I don't know why...
It's hard to tell exactly what's going on but I have one idea from experience: You need to make sure you're calling nextJSApp.prepare() before any modules using next/config are included.
As an example,
// SomeComponent.tsx
import { getConfig } from 'next/config'
const config = getConfig()
export interface X { ... }
// server.ts
import { X } from './SomeComponent'
app.prepare().then(...)
This fails because module are loaded first and the config hasn't been initialized until app.prepare has been completed.
The solution for this is to either use TypeScript's import(...) syntax if you just need a type or use node's require for dynamic resolution during runtime.

Is it possible to import a function in a modules subfolder

I'm trying to access the decode() method in the jsQR module.
I found an example that called decode() directly but that was from an HTML file, not nodejs.
In visual code I see this...
I know that the default export is defined in index.d.ts but is there anyway of importing the other classes/functions on the rest of the dist folder?
I've tried to import using require("jsqr/decoder") and require("jsqr/decoder/decode") to no avail.
EDIT
To be clear, I don't want jsQR, the default export. That deals with images. I'm trying to explicitly call the decode() method in the pic which accepts a BitMatrix
There are no limitations in what you can require from node_modules. So, with your case it should look like:
TypeScript\ESM Modules:
import { decode } from 'jsqr/dist/decoder/decoder';
CommonJS:
const { decode } = require('jsqr/dist/decoder/decoder');
UPD: If you take a look into dist folder for jsqr package, you can find that there are only d.ts files. Which means that you can not import it from there.
But, you can find an actual export of the module here:
Which means that you should able to import it from jsqr:
const { decode } = require('jsqr');

Invoke the text plugin from requirejs mapping

I'm writing a web app using TypeScript, Backbone, and Mustache. I want to use Requirejs for dependency loading.
I'm also using the Web Essentials visual studio plugin for TypeScript with the AMD compilation option turned on. For those that are not familiar with this, it will wrap your type script file in an AMD module if you import external modules.
For example:
In type script I import the following modules in type definition files.
export import Backbone = module("Backbone");
import mainTemplate = module("MainTemplate");
The output is something like:
define(["require", "exports", "Backbone", "MainTemplate"], function(require, exports, __Backbone__, __mainTemplate__) {
//...code goes here ...
});
For the template, I've declared the following in a type definition file:
declare module "MainTemplate" { }
In order to support requirejs plugins, you need to declare your module as:
declare module "text!MainTemplate.html" { }
I'd like to keep the module name free of plugins and file extensions. This would leave me with some flexibility in the future.
I have the following mapping in require.
require.config({
map: {
"MyModule": {
"MainTemplate": "text!MainTemplate.html"
}
}
}
This successfully invokes the text plugin however, the plugin loads the wrong url. Sifting through the source code for the text plugin, I found that the following code is the culprit.
load: function (name, req, onLoad, config) {
...
url = req.toUrl(nonStripName),
//returns "scripts/**text!**MainTemplate.html**.html**"
...
}
If I name the module, 'MainTemplate.html' it works fine but I'd like to keep the extension out of the module name.
I've modified the text plugin with a simple regex replacement to strip out the plugin reference and the duplicate extension.
Is there a better way to handle this?
Ran into similar issue. Solved finally. See TypeScript: compiling removes unreferenced imports
/// <amd-dependency path="text!templates/application.htm" />
var applicationTemplate = require('text!templates/application.htm');
For Typescript 1.0 this works for me.
First I created a .d.ts file which stores all module declarations for each text template.
//workaround for typescript's lack of support for requirejs text template notation
//remember that a reference to the import variable has to be found in the class, otherwise typescript ignores the import
declare module "text!views/details/details.html" {
var text: string;
export = text;
}
declare module "text!views/layout/layout.html" {
var text: string;
export = text;
}
declare module "text!views/home/home.html" {
var text: string;
export = text;
}
then to refer to the text template I add these lines on top of the class/module.
/// <reference path="../texttemplate.d.ts"/>
import detailsTemplate = require('text!views/details/details.html');
The reference line is not actually needed, since the .d.ts file is picked up globally. But I added it as a reminder of the workaround. It also makes it easy to ctrl+click to go the d.ts. file.
There is a slightly nicer way to do this (I'm using typescript 2.0)
Referenced here: https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html
This code expects that your requirejs configuration and plugins are set up correctly:
/// <amd-dependency path="text!./about.html" name="template"/>
declare let template: string;
This helped me a lot to migrate lagacy code to typescript.
Since TypeScript 0.9.0 I think you need to do the following:
/// <amd-dependency path="text!templates/application.htm" />
declare var require:(moduleId:string) => any;
var applicationTemplate:string = require("text!templates/application.htm");
Check out more at http://www.codebelt.com/typescript/typescript-amd-with-requirejs-tutorial/
We are using Backbone and require.js for our TypeScript applications.
We don't use the
import backbone = module("Backbone")
syntax, but rather use a
/// <reference path="../../modules/Backbone.d.ts" />
reference, and then a BootStrapper.
This way, the 'text!htmlfile.html' syntax works perfectly with require.js.
I've put together a blog on using require.js with TypeScript and AMD:
http://blorkfish.wordpress.com/2012/10/23/typescript-organizing-your-code-with-amd-modules-and-require-js/

Resources