Import a non-ES6 module with Webpack
Assume we have a module left-pad.js that exposes itself on theWhen 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.
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
The leftPad module still pollutes the // eslint-disable-line
statement at the end (or there's a plugin for that)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
Finally, extract this import statement to the config so we don't need to use this, each time we import this modulewindow
object to add itself to.webpack.config.js/module/loaders:
{test: require.resolve('./src/js/non_node_modules/left-pad', loaders: ['imports?window=>{}','experts?leftPad']}