Ishita Ishita - 1 month ago 21
Node.js Question

Use Webpack library and libraryTarget configuration to set our custom library via global var

Disclaimer: i am very new to webpack. So, please bear with me.

I have a library "xyz" which is currently being imported as a node module through npm registry.

Now, I want to add it as a library and expose it via global name "abc".

I want to use webpack configuration to achieve that.

So, I understand that this is the config i need to add to my webpack config?:

"output": {
"path": SHELL_PATH + filePath.dist,
"libraryTarget": "var",
"library": "abc"
}


But, then how do i link abc to my xyz library so that the methods inside my abc library are exposed through global name "abc"?

What else do i need to do?

Answer

An option could be just wrapping xyz inside abc library and expose abc library as a global variable.

webpack.config.js

module.exports = {
  entry: './index.js',
  output: {
    libraryTarget: 'var',
    library: 'abc',
    path: './dist',
    filename: 'abc.js'
  }
};

index.js

module.exports = {
  xyz: require('xyz')
};

if you want to access xyz fields through abc.xyz, or

module.exports = require('xyz');

if you want to export xyz fields through abc directly.

Comments