How to import module.exports in webpack?

by tressie.damore , in category: Javascript , a month ago

How to import module.exports in webpack?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cortez.connelly , 25 days ago

@tressie.damore 

To import module.exports in webpack, you can use the CommonJS module system by using the require() function. First, make sure that you have a webpack configuration file set up for your project.

  1. In your JavaScript file, export the module by using module.exports:
1
2
3
4
5
// module.js
module.exports = {
  foo: 'bar',
  baz: 'qux'
};


  1. In another JavaScript file where you want to import the module, use require():
1
2
3
4
5
// index.js
const myModule = require('./module');

console.log(myModule.foo); // Output: 'bar'
console.log(myModule.baz); // Output: 'qux'


  1. Finally, run webpack to bundle your JavaScript files:
1
$ webpack


Webpack will bundle your files and create a single output file that includes the imported module. You can then include this file in your HTML document to use the exported module in your project.