This project demonstrates the creation of a Haxe-JavaScript modular project leveraging Webpack for bundling (code and assets) and lazy loading.
It's really easy and absolutely transparent in the code!
Note: this is a "vanilla DOM" example - no 3rd party library involved!
You will need to get familiar with how Webpack works - thankfully the documentation is excellent nowadays: https://webpack.js.org/
A project aims at creating a Webpack loader for Haxe: https://github.com/jasononeil/webpack-haxe-loader
Every asset dependency should be explictely required, so Webpack knows what to include in the output folder. With the right configuration, small assets can even be inlined in the bundle to reduce the number of requests.
Webpack.require('./index.css');
var img = new Image();
img.src = Webpack.require('./logo.png');
Even the HTML page is generated by a plugin, so everything has to go through Webpack.
Haxe JS isn't normally capable of code splitting, but the core functionality was developped within the (Webpack-free) Haxe Modular project: https://github.com/elsassph/haxe-modular
The Haxe Webpack loader will leverage the code splitting feature when you request modules asynchronously:
import com.Foo;
...
// Extract Foo (and dependencies) into a separate bundle
Webpack.load(Foo).then(function(_) {
// Foo is now loaded
var foo = new Foo();
});
Webpack's "magic" is configured in the webpack.config.js
. It is a very powerful and
flexible system which is documented here: https://webpack.js.org/
The basics is that the haxe-loader
allow to "require" an
HXML file,
which in turn will provide the (splitted) JS output to Webpack.
This feature is added as a "rule" in the config:
{
test: /\.hxml$/,
loader: 'haxe-loader',
options: {
extra: `-D some_extra=arguments`,
debug: debugMode
}
},
HXMLs can be require directly from JS code, or as an entry point, which allows to make a pure Haxe Webpack project:
entry: {
app: './build.hxml'
},
Using yarn for node modules is recommended:
npm install yarn -g
Using hmm for haxelibs is recommended:
haxelib --global install hmm
haxelib --global run hmm setup
Install npm and haxe dependencies:
yarn install
hmm install
Then start Webpack webserver, open http://localhost:9000
, and enjoy live reload:
yarn start
Hot-Module Replacement is the technique allowing, while your browser is showing your live application, to hot-reload CSS and the Haxe modules!
React views in asynchronous modules will automatically refresh themselves if you edit
and save: Webpack will recompile the project, reload the module, and re-render the
views without losing state. un and try editing Foo.hx
!
For that you only need to:
- add
-D react_hot
in yourhxml
, - call
ReactHMR.autoRefresh
after the main render (seeApp.hx
), - run in live debug mode (
yarn start
).
To build the project statically, run:
yarn build
For a production release:
export NODE_ENV=production
yarn build -p