Skip to content

Why You Should Use a Bundler Like Browserify or Webpack

Manabu Tokunaga edited this page Mar 26, 2017 · 9 revisions

Issue

Many of Mithril examples as well as other JavaScript libraries use require(). I am a frontend developer and have no interest in require() or nodejs.

Solution

The time has come to all of us that the require() is now a norm; whether or not you are dealing with node.js or in <script> style JavaScript, you will sooner or later have to deal with the require() style.

There has been require.js, but there are many other solutions like Browserify, System.js, Webpack and many others. I am starting to use Browsrify as it appears to be the simplest way to work this in a few command lines. TypeScript compiler itself now has it's own System.js based bundling feature (I have not tried.)

Working with Require in TypeScript 2.x or later

Instead of require() you would use "import" statement in Typescript.

For Mithril, you will first need to install the Types definitions using npm first.

Then,

In your source, whenever you need to use Mithril, you will need to import the Mithril and Mithril Stream definitions like this;

import * as m from "mithril";
import * as s from "mithril/stream"

Once that's done, you can do things like;

import sm = Stream.Stream;  // aliasing Stream.stream as sm

class TestCompo implements m.Component<{},{}> {
   s: Stream.Stream<string>; // Stream.Stream fully qualifed
   t: s<string>; // Use the alias as defined above.
   view(vnode: m.Vnode<{}, {}>) {
       this.s = Stream<string>();
       this.t = Stream("Hello");
    }
}

After you have created several ts files in this manner, you can now use browserify to bundle all the files your ts code requires. Browserify then scans all the required files (including mithril and lodash), and bundle it in a single .js file. This is only the file you need to "script src" in your index.html page.