How to load a library in JS/TS in the browser? - javascript

I have a project consisting of a TypeScript file and an HTML page. Currently, I am loading several libraries that the TypeScript file requires in the HTML Page by including them in tags, i.e. <script src="https://unpkg.com/tabulator-tables#4.9.3/dist/js/tabulator.min.js"></script>.
Since I would like to use the TypeScript code in other web pages without having to copy a bunch of script tags, is there a way I could load the libraries in the TypeScript file instead of in the HTML file? I tried searching it up and saw some options (for example, import and export) but just using import {Tabulator} from 'tabulator-tables'; obviously didn't work, and I'm somewhat lost.

Because you stated that you're not using any bundler, and that you don't want to use a UMD module in a <script> element, you'll need a version of tabulator-tables that is in the ES module format. It looks like the package provides one at https://unpkg.com/tabulator-tables#4.9.3/dist/js/tabulator.es2015.min.js. You can download that file locally to your project and import from it in your script like this:
import Tabulator from './relative/path/to/where/you/saved/tabulator.es2015.min.js';
You'll need to publish that downloaded module alongside your HTML file, JS file, etc. wherever you're serving the web page, and make sure that you set your own script's type attribute to module in the HTML.

Related

Parceljs import javascript file as string

I have a very particular use case. I want to import a javascript file as a string and inject it into html responses at will in a service worker. I can't see how to do this using parceljs beyond hosting the javascript file somewhere and doing fetch at runtime to load the js file into memory. However, I want to do this at build time. How best to do this?
Note: Ideally the dependencies of javascript file I am importing should be bundled into the string.
Seems to be possible in parcel 2 with
import js from "bundle-text:./b.ts";
console.log(js);
https://v2.parceljs.org/configuration/plugin-configuration/#predefined-(offical)-named-pipelines

Injecting multiple external javascript files with Webpack

Let's say I have a few external javascript files (libraries, if you prefer to call them that way). Those files haven't been adapted to any of the "modern" JS functionalities, meaning that I can't import them like I'd do with some of the most common libraries nowadays (lodash, axios, etc...). The files in question have been always used as old-style import-and-use libraries (<script src="foo.js"></script>).
How can I make Webpack pack (concatenate) all those files and inject them in the head of my index.html, right before my actual bundle?
You can download 'foo.js' manually and add it to project repo. Imagine like you have a folder called 'external-libs' and you can simply import foo.js as something like following
import '../../external-libs/foo.js';
This will be enough for Webpack to append the content of foo.js to your final bundle.

StencilJS using component in HTML file

I want to use a component created using StencilJS in a regular basic HTML file. I followed these steps:
I have created a stencil component to create the basic my-component example:
npm init stencil
I want to use this component in an HTML file, so I ran
npm run build
I then created an html project with the following structure:
And then I moved the files from the dist folder into the script folder. And I added script tag in the head of my html file that references the component.js file like this:
<script src="script/{component_name}/{component_name}.js"></script>
And I used the component in the html like this:
<my-component first="Stencil" last="'Don't call me a framework' JS"></my-component>
But my component isn't being rendered. I get an error involving a esm.js file. Can someone help me with this process of compiling my stencil component to be using in a basic HTML project?
Stencil bundles your dist into modules and lazy-loads only the required code based on the components you are actually using in your HTML. So you should serve the whole dist folder along with your website.
The recommended way is to have the following two script tags in your html file:
<script type="module" src="/dist/[namespace]/[namespace].esm.js"></script>
<script nomodule src="/dist/[namespace]/[namespace].js"></script>
(where [namespace] is whatever is set in your stencil.config.ts)
This will instruct browsers who support ES Modules to use the esm bundle, and other browsers will use the ES5 (cjs) bundle.
If my-component is the only component that you're using from your library, then only that code will be lazy-loaded by your page. Stencil knows about component interdependencies and how to lazy-load them accordingly.
There is a new experimental output target (called custom-elements-bundle) that allows you to bundle everything into one js file, which will simplify distribution in some cases. It's only available with the new refactored compiler (which is available using the --next flag, after installing #stencil/core#next) (Stencil 2 has been out for a while now).

Including external (hosted) javascript files in Angular2

I'm trying to add an external js file into my Angular2 project by adding the record to my angular-cli.json file.
I've added a file to the [scripts] array as below:
"scripts": ["https://as-identitydemo--c.na50.visual.force.com/resource/1495420277000/salesforce_login_widget_js"],
all the other posts that i've read refer to using this format for something that's either hosted locally, or installed in the node_modules etc..
How can I include an external js library and utilize that in my project?
You should import the library in your index.html in the head tag.
Second you have to make the library visible to your Angular project. That means you need the typings. You can either search https://github.com/DefinitelyTyped
for already existing types or add the types to the typings.d.ts file.
Example:
In your page (outside of the Angular app) you might have a javascript global variable:
var testVar = 'testvalue';
Then in the typings.d.ts you can make this variable globally accessible by adding
declare var testVar:string;
Then you can access this variable in the whole Angular project like that:
console.log(testVar);
The same you can do with functions in external libraries.
Here is a Plunk that shows that (without having a typings file). Hope this helps.

how to use webpack to load CDN or external vendor javascript lib in js file, not in html file

I am using react starter kit for client side programming. It uses react and webpack. No index.html or any html to edit, all js files. My question is if I want to load a vendor js lib from cloud, how to do I do that?
It would be easy to do that in a html file. <script src="https://forio.com/tools/js-libs/1.5.0/epicenter.min.js"></script>
However, in js file, it only uses npm installed packages. How can I import the above lib with no html file? I tried import and require, they only work for local files.
update 10/21/15
So far I tried two directions, neither is ideal.
#minheq yes there is a html file sort of for react start kit. It is html.js under src/components/Html. I can put cloud lib and all its dependencies there like this:
<div id="app" dangerouslySetInnerHTML={{__html: this.props.body}} />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://forio.com/tools/js-libs/1.5.0/epicenter.min.js"></script>
<script src="/app.js"></script>
<script dangerouslySetInnerHTML={this.trackingCode()} />
</body>
Good news is it works, I don't need do anything else in js file, no import or require. However, now I have two jquery libs loaded in different ways. One in here, the other through npm and webpack. I wonder it will give me trouble later. The react-routing I use give me 'undefined variable' error if I type a none home path in browser window due to the server side loading I guess. So this solution is not very good.
Use webpack externals feature. This is documented as: link. "You can use the externals options for applications too, when you want to import an existing API into the bundle. I.e. you want to use jquery from CDN (separate tag) and still want to require("jquery") in your bundle. Just specify it as external: { externals: { jquery: "jQuery" } }."
However, the documentation I found a few places are all fussy about how to do this exactly. So far I have no idea how to use it to replace <script src="https://forio.com/tools/js-libs/1.5.0/epicenter.min.js"></script> in html.
externals is not intended to let you do this. It means "don't compile this resource into the final bundle because I will include it myself"
What you need is a script loader implementation such as script.js. I also wrote a simple app to compare different script loader implementations: link.
var $script = require("scriptjs");
$script("//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js", function() {
$('body').html('It works!')
});
You can create a script tag in your JS as
$("body").append($("<script src="https://forio.com/tools/js-libs/1.5.0/epicenter.min.js"></script>"))
There is one html file that is definitely being used to serve to users with your js bundle attached. Probably you could attach the script tag into that html file
Use webpack's externals:
externals allows you to specify dependencies for your library that are
not resolved by webpack, but become dependencies of the output. This
means they are imported from the environment during runtime.
I have looked around for a solution and most of all proposals were based on externals, which is not valid in my case.
In this other post, I have posted my solution: https://stackoverflow.com/a/62603539/8650621
In other words, I finished using a separate JS file which is responsible for downloading the desired file into a local directory. Then WebPack scans this directory and bundles the downloaded files together with the application.

Categories

Resources