JavaScript Imports

Learn to use different methods to import JavaScript libraries with Python.

JavaScript imports

We covered a few different ways of importing JavaScript libraries into the scope of our Python projects early on. Moving forward, we’ll assume that you are using the Parcel web application bundler and npm to locally store copies of the JavaScript libraries that will be used in the project. That said, the primary import of a JavaScript library will use the Node.js require() function like this:

React = require('react')

This ES5 style statement will cause the application bundler to import the JavaScript library into the current namespace and assign it to the Python variable on the left of the statement. Once we do that, we can import the library into another Python module as a native Python object. By comparison, we might come across the same JavaScript import with ES6 syntax, which would look like this:

import React from 'react';

For the React library, we are importing the top-level default object. For other JavaScript libraries, we want to import a named function from the library. This applies especially if the libraries are large and we only need one small function out of it. For example, consider a JavaScript ES6 import that looks like this:

import { FixedSizeList } from 'react-window';

If we were to look at the source code for that library, we’d see that the function is exported in the JavaScript file using a named export as:

exports.FixedSizeList = FixedSizeList;

Based on that, we can import it into our Python file like this:

FixedSizeList = require('react-window')['FixedSizeList']

Note that, in the Python version of the import, we are essentially doing a dictionary lookup of the function that we wish to import. Other times, the library might have a default export function set. Let’s say we have a JavaScript import that looks like this:

import Button from '@material-ui/core/Button';

Suppose the JavaScript library assigns the exported function to the exports.default property as it does for this one. In that case, we will need to structure that import in our Python file in a way similar to how we just handled the named JavaScript export, like this:

Button = require('@material-ui/core/Button')['default']

Get hands-on with 1200+ tech skills courses.