ES6 in custom plugins

Hey, I think this may be considered ‘general’ advice to be asking, hopefully get a pointer still:

I have created a custom mu-plugin: /mu-plugins/test-plugin.

Inside my plugin directory I am including the GetStream JS via CDN:
wp_enqueue_script('getstream', '//', null, null, true);

However, when attempting to require or import getstream:
const stream = require('getstream');

Uncaught ReferenceError: require is not defined
Uncaught SyntaxError: Cannot use import statement outside a module

A friend mentioned this earlier:

"Your original main.js is going through a babel-like transpiler and converting ES6 to vanilla JS, so import works there, I imagine you haven’t set one up inside your plugins

Right now I am just trying to get a proof of concept up and running, any advice how to be able to run: const stream = require('getstream'); without having to do a whole install of babel-like transpiler inside the plugin too. Even a vanilla JS approach would do just to test with.

Just throw it through Laravel Mix. It takes two seconds.

In your plugin directory, start by installing Laravel Mix:

$ yarn add laravel-mix

Once that is done we can follow up with a simple config (change paths as needed):


const mix = require('laravel-mix');

mix.js('assets/js/app.js', 'public/js');

The above assumes your source file is located at assets/js/app.js which will then be compiled to public/js/app.js (which you would enqueue).

Once that is done, we can wrap it up with adding the following scripts to package.json:

  "scripts": {
    "build": "cross-env NODE_ENV=development webpack --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "build:production": "cross-env NODE_ENV=production webpack --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "start": "cross-env NODE_ENV=development webpack --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js --watch"

After that, you are free to build / watch.

$ yarn build
$ yarn start

If you’d like to see a real world example, take a look at

1 Like

Thanks @Log1x! Worked perfectly and a great suggestion, will use this going forward.

1 Like

This topic was automatically closed after 42 days. New replies are no longer allowed.