Adding Javascript

How do you add Javascript libraries from npm to your project?

As an example, we will add jQuery. Run the following in your terminal:

npm install jquery --save

In index.js (content/js/index.js), paste the following code

// jQuery
const $ = require('jquery');
window.$ = $;

$(function() {

  // Your jQuery based code

});

You can load local files as follows – for example, a file called calculator.js in the same folder as index.js:

$(function() {

  // Custom javascript
  require('./calculator')

});

If the author of the npm package you are loading did not specify where their JS is located, you will get an error. You can get around this by requiring the full path:

require('jquery/dist/main.js');

You can also import Javascript modules, for example:

import * as Figma from 'figma-js';