Angular2 RC5 Importing 3rd Party JS Library: Showdown - javascript

I'm having trouble importing Showdown as a vendor. When I compile, I get showdown is not defined in the browser console. Since it is a vendor package, I don't think I can import it inside of app.module.ts. Do I need to declare a custom typing for it? The package is all in js. I am running on Angular2 RC5. Thanks!
home.service.ts
import 'showdown/dist/showdown';
declare var showdown: any;
private extractData(res: Response) {
let body = res.json();
var converter = new showdown.Converter(),
originalBody = window.atob(body.content),
body.title = converter.makeHtml(title);
}
vendor.browser.ts
import 'showdown/dist/showdown';

I'm not familiar with the Showdown, but if you want to import it in the code you need to have type definition files. If you use TypeScript 2.0, you can simply install it from npmjs.org. I just checked - they have the type definitions for Showdown in the #types organization: https://www.npmjs.com/search?q=%40types%2Fshowdown
Just run npm i #types/showdown --save-dev.
If you use older TypeScript, install the declarations with Typings.
Don't forget to add a script tag for Showdown in your index.html.
In this sample app I use JQuery implicitely, but don't need to import it though:
https://github.com/Farata/angular2typescript/tree/master/chapter2/auction

Solution was to employ typings mentioned by Yakov Fain
import {Converter} from "showdown/dist/showdown";
const converter = new Converter();
var body.title = converter.makeHtml(title);

Related

Import javascript from node_modules in angular

I installed a npm package which contains a javascript file, what I want to use. The js file name is all.js and contains this code:
import { initExtended } from './extended'
import Header from './components/header/header'
function initAll(options) {
// Set the options to an empty object by default if no options are passed.
options = typeof options !== 'undefined' ? options : {}
// Allow the user to initialise GOV.UK Frontend in only certain sections of the page
// Defaults to the entire document if nothing is set.
var scope = typeof options.scope !== 'undefined' ? options.scope : document
// Find first header module to enhance.
var $toggleButton = scope.querySelector('[data-module="govuk-header"]')
new Header($toggleButton).init()
initExtended(options)
}
export {
initAll,
Header
}
File all.js is located in node_modules.
When I tried to import it directly from index.html like:
<script type="module" src="node_modules/#id-sk/frontend/govuk/all.js"></script>
It is not working. Console error, file not found.
I also tried import it via angular.json:
"scripts": [
"./node_modules/#id-sk/frontend/govuk/all.js"
]
Also not working with error "Uncaught SyntaxError: Cannot use import statement outside a module (at scripts.js:15241:1)". The error refers to line:
import { initExtended } from './extended'
I also tried to import it in polyfills but I don't know how to call it.
As you are speaking about angular.json, I assume that you are working in an Angular application bootstrapped using the Angular CLI with default settings.
To be able to use this package #id-sk/frontend in your typescript files, you have to import it directly into your typescript file.
1. Import #id-sk/frontend in your TS files
// Import everything into a local variable
import * as govuk from '#id-sk/frontend';
// Import specific object
import { HeaderExtended } from '#id-sk/frontend';
2. Run ng serve
⚠ Spoil: It will lead to typings errors
3. Let's add or create typings
As #id-sk/frontend is not written in typescript, the compile doesn't know about the typings of this library.
Following this statement, you have two choices:
Find or contribute to DefinitelyTyped in order to create the typings of your package #id-sk/frontend
Create a local file typings.d.ts in your ./src folder to declare an empty module
declare module "#id-sk/frontend"
4. Kill & run ng serve again
Enjoy it!
Go further
You can add typings to your module in order to give you autocompletion on the provided objects of #id-sk/frontend.
``ts
declare module "#id-sk/frontend" {
export interface Options {
scope?: Document
}
export function initAll(options: Options): void;
}

Import nodejs module with version number into typescript

So I have a node module which seems to use a versioning system. Using nodejs I simply used
const Package = require('package-name').V1;
which worked without issues. Typescript however does not like the .V1 so I use
import { Package } from 'package-name';
which complies fine but the typescript output to javascript is
const package_name_1 = require("package-name");
Which means that any function or properties of package_name_1 are undefined since the module doesn't seem to load V1.js file (i assume that is how it works..)
So I tried
import * as Package from 'package-name';
But it outputs the same javascript as before..
The actual folder structure of the package I am using is
-node_modules
--package-name
---client
----v1
----v1.js
with the v1.js file looking like
var PackageV1 = {}
PackageV1.CONSTANTS = require('./v1/constants');
PackageV1.Request = require('./v1/request');
PackageV1.Session = require('./v1/session');
...
module.exports = PackageV1;
Of course things like
const Package = require('package-name.V1');
do not work
Error: Cannot find module 'package-name.V1'
How can I require this V1.js file / directory using the typescript method?
As was hinted at in the comments
import * as Package from 'package-name';
is fine but when using the package I had to use
Package.V1.Request()
rather than
Package.Request()

Import ace code editor into webpack, es6, typescript project

I'm trying to build a web component that will host the ace editor. The trouble is that I don't find enough information on how to import the module and set the types. The code bellow was working just fine using simple <script> tags and global vars.
So far this is what I have:
npm install ace-code-editor --save
npm install #types/ace --save-dev
code-editor.cmp.ts
// Error: [ts] File '.../node_modules/#types/ace/index.d.ts' is not a module.
import * as ace from 'ace';
export class CodeEditorCmp extends HTMLElement {
// DOM
private editor: AceAjax; // How do I import the type. What type to use?
constructor() {
super();
}
connectedCallback() {
this.initCodeEditor();
}
initCodeEditor(){
this.editor = ace.edit("editor-vsc");
// How do I import the editor themes?
this.editor.setTheme("ace/theme/xcode");
// How do I import the editor modes?
var JavaScriptMode = ace.require("ace/mode/html").Mode;
this.editor.session.setMode(new JavaScriptMode());
this.editor.getSession().setTabSize(4);
this.editor.getSession().setUseSoftTabs(true);
this.editor.getSession().setUseWrapMode(true);
this.editor.setAutoScrollEditorIntoView(true);
// Update document
this.editor.getSession().on('change', this.onEditorChange);
}
onEditorChange(){
}
}
require('./code-editor.cmp.scss');
window.customElements.define('editor-vsc', CodeEditorCmp);
For those who don't want to use the brace module, I saw that my issue was that I was importing the wrong version of ace. Once installed, make sure to import from src-noconflict. The noconflict version uses ace.require which seems to play a lot more nicely than the other iterations that use require.
I would suggest that you do the following:
npm install ace-builds --save
npm install #types/ace --save-dev
Afterwards in your file just import the noconflict like below:
import * as ace from 'ace-builds/src-noconflict/ace';
This will result in a variable ace being defined. You will then be able to reference methods and properties of ace as normal, such as ace.edit()
You can get more information about the different versions of ace check out the git page.
After a lot of digging I managed to find brace module. It's a browserify wrapper for ace. Fortunately it works straight away with webpack. No need to use separate types, they come prepackaged.
import * as ace from 'brace';
import 'brace/mode/javascript';
import 'brace/theme/monokai';
export class CodeEditorCmp extends HTMLElement {
private editor: ace.Editor;
initCodeEditor(){
this.editor = ace.edit('javascript-editor');
this.editor.getSession().setMode('ace/mode/javascript');
this.editor.setTheme('ace/theme/monokai');
//...
}
//...
}

How to import sub-modules of a module using define in JavaScript?

I'm new to AMD and trying to use react-context-menu library. The docs for the library imports modules like ,
import { ContextMenu, MenuItem, ContextMenuTrigger } from "react-contextmenu";
Now if I were to include the module using define[], how would I do it ?
e.g for including react I would do,
define(["react"], function(React){
});
What should I do if I also want to include react-context-menu and use it's submodules ContextMenu, MenuItem, ContextMenuTrigger?
define(["react", "react-context-menu"], function(React, ??????){
});
Thanks in advance.
Perhaps you should consider using CommonJS modules var $ = require('jquery') in conjunction with a module bundled instead, either webpack or browserify.
define(["react-contextmenu"], function(ReactContextMenu){
var ContextMenu = ReactContextMenu.ContextMenu;
var ContextMenuTrigger = ReactContextMenu.ContextMenuTrigger;
var MenuItem = ReactContextMenu.MenuItem;
});
The sub-modules can be included using .(dot). <module>.<sub-module> worked for me.

Trying to integrate braintree-web into Angular2

I am trying to use the Braintree SDK (braintree-web) in my Angular2 app. I'd really appreciate any pointers on how to get this working. I think it is because I am not importing the braintree-web module, but I can't figure out how to to that either. I can find any exports in the whole module.
Here is where I am:
I've imported the braintree-web library and a typings file I found.
ng install --save braintree-web
npm install #types/braintree-web#3.0.1
I tried to hack the JS example Braintree provides into a Angular2 TS Component, but I keep getting an error:
EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in
./UpaccountComponent class UpaccountComponent - inline template:5:7
ORIGINAL EXCEPTION: TypeError: this.braintree.setup is not a function
Here is the .ts file.
import { Component, OnInit } from '#angular/core';
declare var braintree:any;
#Component({
selector: 'up-btcheckoutform',
templateUrl: './btcheckoutform.component.html',
styleUrls: ['./btcheckoutform.component.css']
})
export class BtCheckoutFormComponent implements OnInit {
braintree = require('BrainTreeWeb');
// braintree = require('braintree-web');
integration: any
constructor() { }
ngOnInit() {
var c = this;
var clientToken = "CLIENT_TOKEN_GOES_HERE";
braintree.setup(clientToken, "dropin", {
container: "payment-form",
onReady: function(int) {
c.integration = int
}
});
}
ngOnDestroy() {
this.integration.teardown();
}
}
I'm not sure about the usage of braintree-web specifically, but if you're using webpack, remove the lines declare var braintree:any; and braintree = require('BrainTreeWeb');
You'll also need to add the braintree-web/index.js file to the bundle, unless they've got a UMD module.
From a quick glance at braintree-web, it looks like braintree.setup(..) isn't a function. Something like this might be equivalent:
braintree.client.create({
authorization: "long-token-string"},
(err, client) => {
// Do stuff here
client.request({..});
});
With the package installs, you'll need to have added --save-dev to the types install.
I have integrated the brain-tree the same way as you have done and it works.
I've just installed one more command
first install
npm install #types/braintree-web#3.0.1er
then install
npm install --save braintree-web#2.30.0
and use
braintree = require('braintree-web');
Again if it asks for braintree is not defined then remove declare var braintree:any;
and replace bellow code
braintree.setup(clientToken, "dropin", {
container: "payment-form",
onReady: function(int) {
c.integration = int
}
});
with
this.braintree.setup(clientToken, "dropin", {
this.container: "payment-form",
onReady: function(int) {
c.integration = int
}
});
Edit:
just declare the var after import declare var braintree:any; if your working with angular 4 then declare declare var require: any;
You can also import it via:
import * as braintree from 'braintree-web';
Refer this:
Refrring 3rd party JS libraries in angular 2
It's a universal solution. You don't even need to use any npm packages. Just simply refer BrainTree JS libarary in index.html and follow the steps documented in above link. It's applicable for any JS library.

Categories