I need to import a library in my vue component, in the documentation I explain how to install it using npm (already do this step) but not how to import it into a vue component, this is the way in which it explains how to use the files:
<link href="node_modules/webdatarocks/webdatarocks.min.css" rel="stylesheet"/>
<script src="node_modules/webdatarocks/webdatarocks.toolbar.min.js"></script>
<script src="node_modules/webdatarocks/webdatarocks.js"></script>
and this is the way to instantiate the library:
<script>
var pivot = new WebDataRocks({
container: "#wdr-component",
toolbar: true,
report: {
dataSource: {
filename: "https://cdn.webdatarocks.com/data/data.csv"
}
}
});
</script>
So what is the best way to call this in my component?
This is a bit heavy.
The library is is not develop in module-like system, so the solution is make the js file imported as global.
A good library would be like const WebDataRocks = require("WebDataRocks"); or with imports, but the library is made only for end-client.
First Part - Add the JS file to the global web client
To use WebDataRocks you have to get the global variable, to get the global variable you have to inyect, as common javascript on html but with webpack.
Here are a solution for this
Webpack - How to load non module scripts into global scope | window
You have to do this for webdatarocks.toolbar.min.js and webdatarocks.js
Second Part - Add the CSS
You have some options, the easy way i found to do this is use require in your <script> zone:
require('../node_modules/webdatarocks/webdatarocks.js')
Good luck! ð
If something fails check the paths and let us know more information about it
Alternative solution (But worse)
If you are going to use this script in a internet system, you could insert the script and CSS in the HTML. For this do:
Open index.html
Add this code on the head section:
<link href="https://cdn.webdatarocks.com/latest/webdatarocks.min.css" rel="stylesheet"/>
<script src="https://cdn.webdatarocks.com/latest/webdatarocks.toolbar.min.js"></script>
<script src="https://cdn.webdatarocks.com/latest/webdatarocks.js"></script>
Rebuild
Extracted from WebDataRocks React Example
Important! this is unsafe ⣠â
Make this only if you are sure about what this mean
If the webdatarocks CDN's fails, your app will also fails.
Hope it helps :)
I did this and it works:
import WebDataRocks from 'webdatarocks'
import '#/../node_modules/webdatarocks/webdatarocks.min.css' // # is resolved to src/ folder
I didn't import the toolbar as I don't need it:
WebDataRocks({
container: '#pivot',
toolbar: false,
...
})
Related
I am trying to create a simple JS/ESM based Angular example. It has been a while since I have been in the angular space and I see there are really 2 options
Using the UMD lib (I would like to avoid this)
Use the ESM2015 folder and load using ESM (this is what I would like to do)
I try doing this like...
<html>
<head></head>
<body ng-app="jrg-module">
<jrg-element></jrg-element>
<jrg-app></jrg-app>
<script type="module">
import { Component } from "//unpkg.com/#angular/core/esm2015/index.js";
import { platformBrowserDynamic } from "//unpkg.com/#angular/platform-browser-dynamic/esm2015/index.js"
import {ShadowElement, CREATE_ELEMENT} from "//unpkg.com/#jrg/ui/target/jrg-ui.esm.mjs";
class JrgElement extends ShadowElement {
constructor() {
super("<h1>CustomElement</h1>");
this.render();
}
}
CREATE_ELEMENT("jrg-element", JrgElement, {});
const MyComponent = Component({
selector:"jrg-app",
template:"<h1>Angular</h1>"
}).Class({
constructor: function() {}
});
const app = platformBrowserDynamic().bootstrapModule(MyComponent)
</script>
</body>
</html>
But (after taking forever to download 500+ files) I get
Uncaught TypeError: Error resolving module specifier ârxjsâ. Relative module specifiers must start with â./â, â../â or â/â.
Can I use the ESM version in the browser or do I have to use UMD? If I can use ESM from the browser is there a link to an example?
I swear Angular used to have a dropdown for their examples where you could switch between TS and JS but I don't see it now.
Have you tried out the website stackblitz it has plenty of angular examples of setting up a new project.
You can also do ng new my-app from the cli to generate a new project locally.
Angular has moved away from javascript in favor of typescript, so you will have to use ESM
I have 2 separated Angular projects.
For each of them, I run the following CLI command:
ng build --prod --output-hashing=none
It creates the following files for each project:
runtime.js
polyfills.js
main.js
Now I want to import the projects into another project, which is a simple javascript project (not Angular project).
I know that the order is important and that runtime.js and polyfills.js appear twice.
So I made sure that these files are the same (because I use the same Angular version in both projects).
The imports in the simple javascript project look something like this:
<script src="runtime.js"></script>
<script src="polyfills.js"></script>
<script src="main1.js"></script>
<script src="main2.js"></script>
Unfortunately, only one of the projects seems to work this way (and there are no exceptions).
If I'll import only main1.js or only main2.js they will work properly.
I guess the problem is the dependency libraries I use in each project, that maybe override each other, but I don't know what I can do about it.
UPDATE:
Not sure if it's relevant, but in each Angular project, I use #angular/elements in order to publish the components I need. something like this:
export class AppModule {
constructor(private injector: Injector) {
const elem = createCustomElement(MyFirstComponent, { injector });
customElements.define('my-first-element', elem);
}
ngDoBootstrap() {}
}
Then in the javascript project, I use it like this:
var elem1 = document.createElement('my-first-element');
container.append(elem1);
var elem2 = document.createElement('my-second-element');
container.append(elem2);
Check the <app-root></app-root> tag in your index.html.
You may need 2 different selector for your AppComponent:
// app.component.ts for the first project
selector: 'app-root-one',
// app.component.ts for the second project
selector: 'app-root-two',
I have put my js files eva.min.js/feather.min.js and so on in vendor dir, then I imported them in ember-cli-build.js app.import('vendor/eva.min.js'). But how to use it?
I tried something like import eva from 'eva'/'eva.min'/'eva.min.js' or import Eva from 'eva'; and so on, but it doesn't work.
app.import('vendor/eva.min.js');
app.import('vendor/bootstrap.min.js');
app.import('vendor/feather.min.js');
app.import('vendor/popper.min.js');
app.import('vendor/jquery-slim.min.js');
app.import('vendor/swipe.js');
import Swipe from 'swipe';
Console usually gives me the could not find the module error.
And I don't have a deep background in programming, so I would highly appreciate if you explained the problem as simple as possible.
UPD: I found all js code as npm package (it happens that the js files weren't third-party)
https://www.npmjs.com/package/feather
https://www.npmjs.com/package/popper.js
https://www.npmjs.com/package/jquery-slim
https://www.npmjs.com/package/swipe
https://www.npmjs.com/package/bootstrap
https://www.npmjs.com/package/eva-icons
But all your responses were helpful. Anyway in the near future I expect to use third-party libraries.
A quick way is to use scriptjs and it allows you to load any javascript into your component in the following way: (I am using Yammer as an example)
import $scriptjs from 'scriptjs';
componentDidUpdate() {
//script loader
setTimeout(function(){
$scriptjs('https://c64.assets-yammer.com/assets/platform_embed.js',
() => {
window.yam.connect.embedFeed(YammerHelper.loadComments());
});
}, 1000);
}
You should get the idea how to consume it. Check their docs with lots of examples.
This is not the best solution. But one way of using the third party js is,
1) say you have a function in your js file vendor/third-party.js
someFunction = function (element) {
...
console.log("works")
};
2) Then import it in your ember-cli-build.js
...
app.import('vendor/third-party.js');
...
3) After importing restart your server.
Use the function directly in your controller/component as
window["someFunction"]
Unless the JavaScript library being used explicitly supports the import X from 'y' syntax then when you import in the build using the app.import syntax you just use it in your app just as the plugin documentation describes.
So for Swipe you would do the following.
Based on this documentation: https://github.com/thebird/Swipe
// ember-cli-build.js
app.import('myswipe.js`);
// component.js
/* global Swipe */ // This silences the linter from throwing errors...
classNames: ['swipe'],
didInsertElement() {
this._swipe = Swipe(this.element, {
option1: option1
});
}
// component.hbs
<div class='swipe-wrap'>
{{yield}}
</div>
This codes creates a component to control your swipe plugin.
This code would create a swipe object and isolate it to the component.
Again when you use the app.import you are just loading the library on boot. The library does whatever it says it will do in the docs. Sometimes they register a global object, sometimes they dont.
Is it not possible to access already 'built' components within the html file that the build is linked to?
I am trying the following -
In bundle.js
var React = require('react');
var ReactDOM = require('react-dom');
var Titles = React.createClass({
render() {
return (
<div>
<h1>{this.props.headerProp}</h1>
<h2>{this.props.contentProp}</h2>
</div>
);
}
});
In my html page -
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>
<div id="con"></div>
<script type="text/javascript" src="/public/bundle.js'"></script>
<script type="text/jsx">
ReactDOM.render(<Titles headerProp = "Header from props..." contentProp = "Content
from props..."/>, document.getElementById('con'));
</script>
But console outputs React is not defined.
I have even tried to set react globally within the bundle -
window.React = React;
And calling it with window. prefixed but yields the same result.
Because you're mentiong a bundle.js file with a snippet containing commonjs style imports, I'm assuming you're using Webpack.
I have some considerations about your code.
bundle.js file will not expose any module as global. That includes React and any other module you might require inside the bundle. There isn't goint to be window.ModuleName. However, these module are accessible in the Browser via require.js because Webpack will export modules as UMD, that is, they will be accessible through either commonjs or AMD (Require.js).
I'm pretty sure that, if in the entry point of your webpack configuration file, you do something like var React = require("react"); window.React = React, that's actually going to work.
There's a Webpack module meant to expose modules globally (like in window.x) in a more ellegant way than (2) called expose-loader. You should take a look at it.
You should really try to avoid doing what you're trying to do. In your entry.js file (the entry point of your webpack configuration) should be responsible for doing something like ReactDOM.render(..., document.getElementById("#app")). So that, just by including your bundle, the app will render automatically. This is what everybody does.
JSXTransformer.js as well as the <script type="text/jsx"> have been deprecated a long time ago. Now you're supposed to use Babel to compile React.
I'm having trouble understanding exactly how to use older javascript libraries within newer ES6 projects. I'm looking at a React project that's been compiled with webpack, written with ES6 and transpiled with Babel. Each component follows the import * from "" notation.
There's an external javascript library I want to use within the project: https://github.com/pchen66/panolens.js. The compiled library doesn't follow ES6 export format, and only has one global object PANOLENS.
What should I do if I want to include this into my project?
This is not the best.
Include it in your html :
<script src="js/three.min.js"></script>
<script src="js/panolens.min.js"></script>
<script src="bundle.js"></script>
<script>window.PANOLENS = PANOLENS</script>
Where bundle.js is your own builded javascript code.
Then, you will be able to use PANOLENS object anywhere.
Example component :
import react, {Component} from 'react'
export default class Test extends Component {
componentDidMount(){
var panorama, viewer;
panorama = new window.PANOLENS.ImagePanorama('asset/equirectangular.jpg' );
viewer = new window.PANOLENS.Viewer(
container: document.getelementbyid('viewer-container'), // A DOM Element container
controlBar: true, // Vsibility of bottom control bar
controlButtons: [], // Buttons array in the control bar. Default to ['fullscreen', 'setting', 'video']
autoHideControlBar: false, // Auto hide control bar
autoHideInfospot: true, // Auto hide infospots
horizontalView: false, // Allow only horizontal camera control
cameraFov: 60, // Camera field of view in degree
reverseDragging: false, // Reverse orbit control direction
enableReticle: false, // Enable reticle for mouseless interaction
dwellTime: 1500, // Dwell time for reticle selection in millisecond
autoReticleSelect: true, // Auto select a clickable target after dwellTime
passiveRendering: false, // Render only when control triggered by user input
);
viewer.add( panorama );
}
render(){
return(
<div id='viewer-container'></div>
)
}
}
It doesn't really matter if the module itself follows ES6 syntax. It will either follow commonJS or AMD, both of which webpack can handle, and at worst, you can just require/import the whole file into your bundle: https://www.npmjs.com/package/panolens.js.
EDIT: This npm module/repo does use module.exports if you look at the dist.
EDIT:
Yeah, it looks like someone has forked the library and made an NPM package out of it. Have you taken a look at https://github.com/sbolel/pano. There is an ES6 example.
Install the package:
npm install --save pano
Then import:
import Pano from 'pano'
import { Page } from 'pano'
// Pano.Page === Page
const panoPage = new Page('pano')
panoPage.init()
ORIGINAL:
You could load the script asynchronously using the method below, or if you are using a bundler, it would have a way to import external scripts. For example, Webpack has Externals for this.
After doing this, you can access the the global object PANOLENS, as per the documentation. You'll want to make sure the PANOLENS object is available before using it in your application.
Add the following to your static HTML:
<script src="https://github.com/pchen66/panolens.js" async></script>
If you are planning to only use the script in a certain React component (presuming you use React), you could use a library such as react-async-script-loader. This will allow you to lazy load a script on a particular component. It has a bunch of properties that can be used to determine when the script is ready to be used.
Again, after the script has successfully loaded, you may use the library by accessing it through the global PANOLENS variable.
So you would want some kind of module shimmer. If you are using webpack you should try this:
https://github.com/webpack/docs/wiki/shimming-modules
There are similar shims for browserify too:
https://github.com/thlorenz/browserify-shim
You could also fork the repo and shim it manually something like this, the implementations may vary though.
/**
* Panolens.js
* #author pchen66
* #namespace PANOLENS
*/
var PANOLENS = { REVISION: '3' };
module.exports = PANOLENS;