Sometimes it is convenient to try to develop with just npm
rather than splitting into client and server versions using bower
or whatever else.
npm init
npm install -D browserify
npm install -D browserify-shim
npm install -D watchify
Also, I would suggest getting some sort of development server with LiveReload or similar, like devd
.
In the client side app, we can now use require
as if we're working with Node.
In app.js
var _ = require('lodash');
// ...the rest of the code...
And then in, say, index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Hello, world!
</body>
<script type="text/javascript" src="./bundle.js"></script>
</html>
and then build everything via
browserify app.js -o bundle.js
# or with watchify
watchify app.js -o bundle.js
If you want to make some objects available inside the HTML document, or in a more general scope, use the --standalone
flag.
browserify standalone-app.js --standalone MyApp -o standalone-app.js
Thereafter, you can use everything exported in standalone-app.js
, which might look like
(function() {
var _Matrix = require('./matrix.js');
var _Vector = require('./vector.js');
exports.Vector = require('./vector.js');
exports.Matrix = require('./matrix.js');
});
Sometimes modules really will have differences between the client and server side versions that are impossible to automatically bridge.
If you have a version of the module that works client side, you can use browserify-shim
to use that version instead of what browserify
would generate.
For example, vectorious
uses nBLAS
to accelerate computations on the server, but that is not available for the client side.
However, there is a version of vectorious that works in the browser, say vectorious-4.1.4.js
In package.json
, we add
[...]
"browserify": {
"transform": [ "browserify-shim" ]
},
"browser" : {
"vectorious": "./vectorious-4.1.4.js"
},
"browserify-shim": {
"vectorious": "vectorious"
}
[...]
Babel allows us to use the features of ES6, which substantially reduces the risk of self-harm.
It comes with its own risk of self-harm, however, during the installation phase. Here is what worked for me:
- Install
babel-cli
(notbabel
, for that would be too easy). - Then install
babel-preset-es2015
, which ensures that everything is compiled from ES5-->ES6.
npm install -D babel
npm install babel-preset-es2015
Now it is fairly convenient to build with it,
# watch a directory and build on change
babel --presets es2015 --watch ./src -o ./build