user7369787
user7369787

Reputation: 19

How to import library which is not module in webpack

How to import in the webpack third party library which is not module (ES, CJS, AMD, etc.)?

For example external library is just an object:

var libObj = {
  a: "a",
  getAddress: function() {
    return null;
  }
}

But how to import this in root JS file? For example in main.js:

import ...what... from ...where...

Upvotes: 1

Views: 3844

Answers (3)

ixth
ixth

Reputation: 78

You should use exports-loader:

module.exports = {
    module: {
        rules: [
            /* ... */
            {
                test: require.resolve('ye-olde-lib.js'),
                use: 'exports-loader?libObj'
            },
            /* ... */
        ]
    }
};

It's covered in official documentation: https://webpack.js.org/guides/shimming/#global-exports

Upvotes: 1

Matthi
Matthi

Reputation: 1063

In your library write export default libObj (ES6). And in your JS file import <yourFavoriteVarName> from '<pathToLib>';

Upvotes: 0

MayK
MayK

Reputation: 1329

You need to first export your libObj file:

// your libObj.js file

var libObj = {
  a: "a",
  getAddress: function() {
    return null;
  }
}

export default libObj;

// your webpack file

import libObj from './libObj.js'

//.. do things

Upvotes: 0

Related Questions