Import a non-ES6 module with Webpack

In notebook:
Egghead Webpack
Created at:
2016-06-20
Updated:
2016-06-20
Tags:
JavaScript Webpack libraries

When you have a dependency that does not export itself properly, you can use the exports-loader to force it to export the pieces of the file that you need.

Assume we have a module left-pad.js that exposes itself on the ​window​. (​window.leftPad = leftPad​)
We want to import this as a regular module (​import leftPad from './non_node_modules/left-pad'​).
Again, the problem comes when we don't have control over this module.

We need the exports-loader plugin. 
​$ npm i -D exports-loader​ 

Then you can import leftPad from 'exports?leftPad!./non_node_modules/left-pad'​ 
The ​?​ above tells Webpack that it's a loader. 
You need add a ​// eslint-disable-line​ statement at the end (or there's a plugin for that)
The leftPad module still pollutes the ​window​ object, we need to remove this

​$ npm i -D imports-loader​ 

and modify the import

import leftPad from 'imports?window=>{}!experts?leftPad!./non_node_modules/left-pad'
Now, this module will use this empty ​window​ object to add itself to.
Finally, extract this import statement to the config so we don't need to use this, each time we import this module

webpack.config.js/module/loaders:

​{test: require.resolve('./src/js/non_node_modules/left-pad', loaders: ['imports?window=>{}','experts?leftPad']}