Adding Javascript

How do you add Javascript libraries from npm to your project? As an example, we will add Popper.js. Run the following in your terminal in the root of the project:

npm install @popperjs/core --save

Popper will be added to your node dependencies in package.json. In index.js (content/js/index.js), paste the following code

import { createPopper } from '@popperjs/core';
console.log(createPopper);

If you see Popper’s output in your console, things worked. For further instructions, I refer you to the excellent Popper documentation. Of course this is just an example. You can import any npm module.

No transpile

Note that any files contained in the root except index.js get transported to your build without any transpiling. This way you can, for example, add a vanilla JS file called map.js and load it as is, if for example you wrote a simple vanilla JS script intended to work in every browser.

Transpile using Babel

You can import files into the index.js file as follows – for example, a file called calculator.js in the a folder called modules:

import './modules/calculator';

The whole index.js will be bundled as bundle-client.js in the final build. A typical index.js contains a few modules to make a website work:

import './slideshow';
import './form-validation';

You will also see a file called bundle-protoype.js, this is explained in from prototype to production.