Learn
Libraries

📚 Adding Libraries

Web applications often depend on external code for solutions to common problems. While the React ecosystem offers a vast array of components available through npm, adding npm packages can be cumbersome in a pure VanillaJS environment of Pre-ReactJS.

For projects built with pre-reactjs, You cannot use these npm packages unless you tweak your /scripts folder (highly discouraged)

Libraries can be imported in a similar way how traditional vanilla and jQuery applications import them Using CDNs.

Adding Three.js to your app!

We'll be using three.js as an example to demonstrate how to import third party libraries, but you can do this any other library.

Step 1 : import the library :

In the root of the project you'll find index.html you don't edit this file for any other purposes apart from importing libraries. Add the following to the head of your index.html ::

<script type="importmap">
        {
          "imports": {
            "three": "https://cdn.jsdelivr.net/npm/three@0.167.1            /build/three.module.js",
            "three/addons/": "https://cdn.jsdelivr.net/npm/three@<version>/examples/jsm/"
          }
        }
</script>

Step 2 : create your page :

Modify your existing Pages/new_page.js as :

 
import Navbar from "../components/Navbar/Navbar.js"
 
let NewPage = /*html*/`
<div class="Text">
    <div id="headAndNav">
        <h1 class="title">Hi There :) </h1>
        <div class="bg">${Navbar()}</div>
    </div>
    <p class="paragraph">This a page shows you how to add external libraries to your project.</p>
    <div id="scene"></div>
 
</div>
`
 
export default NewPage

Step 3 : Use the library :

Create Logic/new_page.js note the filename should be same as Pages/new_page.js. Add the following code to it ::

import * as THREE from 'three';
 
const scene = new THREE.Scene();
const frame = document.getElementById("scene")
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth/1.5, window.innerHeight );
renderer.setAnimationLoop( animate );
frame.appendChild( renderer.domElement );
 
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );
 
camera.position.z = 5;
 
function animate() {
 
	cube.rotation.x += 0.01;
	cube.rotation.y += 0.01;
 
	renderer.render( scene, camera );
 
}

And you are done!

Observation :

In this chapter you learned how to use 3rd party libraries in your application. With this you are all set to building your awesome pre-reactjs applications.