Expose module in global scope using Browserify or Webpack

Tags: October 25, 2019 6:05 AM

Goal

You want to expose a module as in global scope so it can be called in HTML file. For example we will create a small function for reversing a string. We will expose it as StrReverse.

// File main.js
module.exports = function(str) {
  return str.split('').reverse().join('');
}

Browserify

$ browserify --standalone StrReverse main.js --outfile bundle.js

The key is --standalone parameter.

Webpack

$ webpack-cli --mode=none --output-library StrReverse main.js --output bundle.js

The key is --output-library parameter.

Test in HTML

Create a HTML file and include bundle.js via <script> tag.

<!DOCTYPE html>
<html>
<body>
<script src="bundle.js"></script>
var reversed = StrReverse("Hello World");
document.write(reversed);
</body>
</html>

Share on Facebook Twitter

0 comments:

Post a Comment