1. 程式人生 > >ES6 development environment made easy with babel, gulp and webpack!

ES6 development environment made easy with babel, gulp and webpack!

ES6 development environment made easy with babel, gulp and webpack!

Hello, everyone!

Yes, I know, this is yet another tutorial, aiming to incorporate the buzzwords in modern day web development. However, there is no glimpse of React, no Vue, no Angular. Just plain old JavaScript, albeit ES6.

I’ve been a developer for some time now and like everyone else, I sometimes find technology stacks overwhelming and hard to grasp at the first couple looks. I’ve spent numerous hours searching the web for detailed introduction into a particular new framework, library etc.

Maybe the problem lies within me, but (almost) every tutorial, that I stumbled upon in my journey was missing some part. Quite often, I would have to read through several different articles on the same subject, to get to the awaited ‘Ahaaaa’ moment.

So, with this article, I am to provide as detailed information as I can, about starting a project, any kind of project, using the aforementioned technologies.

Starting point

With the only requirement being having node.js installed, simply run npm init -y, in your teminal. This will initiate a new project, skipping npm’s interactive program, and will print something very similar in the console:

{  "name": "es6-starter-pack",  "version": "1.0.0",  "description": "",  "main": "index.js",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1"  },  "keywords": [],  "author": "",  "license": "ISC"}

After that, let’s create an app folder inside and start with the following structure:

app - src // where I like to keep all the .js files - template // where all the html & css goes - assets // where all static files go(sound and images, if any)

Then, create a gulpfile.js in the project’s root directory. Let’s start with its configuration. Gulp is a task runner, and in its essentiality, it’s running tasks, that we create ourselves:

// require gulp modulelet gulp = require("gulp");let OUT_DIR = './build';
// create a task to copy static html to the build foldergulp.task('copy:html', () => gulp.src('./app/template/index.html').pipe(gulp.dest(OUT_DIR)));
// copy css to build foldergulp.task('copy:css', () => gulp.src('./app/template/style.css').pipe(gulp.dest(OUT_DIR)));
// if any assets are present, copy them to the build folder as wellgulp.task('copy:assets', () => gulp.src('./app/assets/*').pipe(gulp.dest(OUT_DIR + '/assets/')));

By default, we can run each of these tasks one by one, with gulp copy:html for example, or, we can combine them all into a single task, like the following:

gulp.task('default', ['copy:html', 'copy:css', 'copy:assets']);

This is the task that will be executed if you just run gulp inside the folder, where the gulpfile.js is located. In our case, it runs the three copy tasks listed above.

Finally, for it to work run:

npm install gulp --save-dev

The save-dev part will tell the project, that gulp is a dependency, needed for development purposes only, needed for compile time. It will not be installed when the project is built for a production environment, thus, not taking unneeded space on our hosting.

Webpack

Install webpack with npm install webpack, and create a webpack.config.js, again inside the project root folder. Open the config file and place the following lines inside:

const path = require('path');
const outputDir = path.resolve(__dirname, 'build');
module.exports = {
    entry: path.resolve(__dirname, 'app/src'),
    output: {
        path: outputDir,
        filename: 'bundle.js'
    }
};

The entrypart is telling webpack where is the code we want bundled, and the output is the directory we want it exported to. We are using the path node module, that will automatically resolve the system path to the project folder, independent of the platform used.

Connecting the dots

Now, webpack and gulp can run separately, but our goal, ideally, is to make them work together, making our development time more productive as well.

For this, we will need the webpack-stream module. Install it through npm, again adding as a dev depencency. Then open the gulpfile and add the following modifications:

On the top, load the module:

let webpack = require('webpack-stream');

Then create the following task, and add it to the default one:

gulp.task('webpack', () => {
return gulp.src('build/')
.pipe(webpack(require('./webpack.config.js')))
.pipe(gulp.dest('build/'));
});
gulp.task('default', ['copy:html', 'copy:css', 'copy:assets', 'webpack']);

With this task, we are running webpack, passing it the configuration created in the webpack.config.js file.

After this is done, running only a gulp command will:

  1. Copy all static assets
  2. Copy html & css into build folder
  3. Bundle all scripts in the src folder to a bundle.js file in the build one.

The future, today

The final part is to include babel, so we can take the advantages of ES6 and have it brought down to today’s support for all browsers.

We need 3 packages for that:

npm install @babel/core babel-loader @babel/preset-env

After installation, we need an adjustment to the webpack config file:

module.exports = {
    entry: path.resolve(__dirname, 'app/src'),
    output: {
        path: outputDir,
        filename: 'bundle.js'
    },
    module: {
        rules: [{
            test: /\.js$/,
            exclude: /node_modules/,
            use: ['babel-loader']
        }]
   }
};

The module addition is using the babel loader, and looking for all .js files in our project, excluding the node_modules folder. Everything else, that matches the regular expression condition(having the extension .js), will be transpiled.

One last step — again, in the root folder, create a .babelrc file, and paste the following:

{
    "presets": ["@babel/preset-env"]
}

This is telling babel, that it is supposed to use it’s own env preset, which is smart enough, to save us from a lot of polyfills between browsers.

Conclusion

With all this, you are ready to go. The full code from this tutorial, can be found as a small starter pack, with minor adjustments here:

If you have reached this far, you have my full appreciation. Also, I have a confession to make — I primarily use this for starters for games. I find this approach very useful when starting out a project, where there are size limitations present. This way, I have the freedom to include whatever I need, if I need it.

I would love to hear any feedback on the tutorial, the stack, or my writing in general. Let me know if you would like me to keep it up(I have a couple projects for game starters created and may convert them to tutorials as well).