Write JavaSript Module With Webpack

How to write a utlity library of common functions in your webpack project.

The following is the code of our utility library util.js.

const util = {}util.test = () => {  console.log('test')}util.name = 'My Utility Library'export default util

To use util.js.

import util from '@/util'util.test()console.log(util.name)

If you use util.js very frequently and you want to avoid the import statement, add the following code to your entry point main.js.

import util from './util'global.util = util

If you are using ESLint with Webpack, ESLint will complaint of http://eslint.org/docs/rules/no-undef 'util' is not defined. Edit .eslintrc.js to add the following:

module.exports = {
  ...
  globals: {
    util: true,
  },
  ...
}  

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.