Using Babel in Docker to convert a javascript file
ES6-type Javascript doesn’t work with old browsers such as IE11. One solution might be to convert this Javascript to make it compatible.
Let’s say you have /path/to/my/project/path/to/js/my.js
:
class MyFirstES6Class {
constructor(message) {
this._message = message;
}
get message() {
return this.message;
}
}
var myClass = new MyFirstES6Class('Hello World!!');
console.log(myClass.message);
If you want to convert this using Babel within a Docker container, you need to install Docker and then run:
docker run -v "$PWD":/data ewoutp/babel --presets es2015 path/to/js/my.js --out-file path/to/js/my.converted.js
Now, at /path/to/my/project/path/to/js/my.converted.js
, you’ll have:
var MyFirstES6Class = (function () {
function MyFirstES6Class(message) {
_classCallCheck(this, MyFirstES6Class);
this._message = message;
}
_createClass(MyFirstES6Class, [{
key: 'message',
get: function () {
return this.message;
}
}]);
return MyFirstES6Class;
})();
var myClass = new MyFirstES6Class('Hello World!!');
console.log(myClass.message);
If you want to do this often, you can put a script in /path/to/my/project/scripts/convert-es6.sh
:
#!/bin/bash
# See http://blog.dcycle.com/blog/9f519875/babel/
set -e
docker run -v "$PWD":/data ewoutp/babel --presets es2015 path/to/js/my.js --out-file path/to/js/my.converted.js
Now you can set this to executable:
chmod +x /path/to/my/project/scripts/convert-es6.sh
Next time someone updates the new-style Javascript, you can convert it:
./scripts/convert-es6.sh