Category Archives: Tools

Automate AppCache offline support in your Webpack build

webpack-logo

Why would you use AppCache ? An API that is messy, not as advanced as service-workers and moreover, which is being removed from the Web Standards ?…

With the Progressive Web Apps, we hear a lot about service-workers. They are very powerfull for a lot of things (including offline support). Though, they’re not supported on IE nor Safari … 🙁

So, until the rest of the browser vendors catch up, if you want to provide some offline experience to all your users, you’ll have to use AppCache which is still widely supported.

AppCache in a few words

  • You have to provide a manifest.appcache file, served with the content type text/cache-manifest
  • This file will consist of three different parts:
    • CACHE: files that will be explicitly cached after they’re downloaded for the first time (this is the default section)
    • NETWORK: white-listed resources that require a connection to the server
    • FALLBACK: fallback pages the browser should use if a resource is inaccessible
  • You will reference this manifest.appcache as an attribute on the html tag of the page that will use it
  • If the manifest.appcache file is updated, the browser will download the resources listed in this manifest (if not, or offline, it will use the cached resources)

More infos on MDN

AppCache in a SPA

Note: Skip this part if you don’t bother about providing different index.html file whether your users are online or offline.

If you’re developing a SPA, and you want to provide a different index.html entry point whether you are online or offline, you’ll have to use a little trick. You won’t reference your manifest.appcache directly in your index.html but in an other html file that you’ll include in an iframe to your index.html.

That way, the index.html file won’t be cached by default (as the master entry) and you’ll be able to define a fallback in the manifest.appcache

index.html

...
<iframe src="./iframe-inject-appcache-manifest.html" style="display: none"></iframe>
...

iframe-inject-appcache-manifest.html

<html manifest="manifest.appcache"></html>

dummy manifest.appcache file

CACHE MANIFEST
# v1 (some version id)

assets/foo.png
assets/bundle.js
assets/style.css
# more assets ...

NETWORK:
*

# that way, you'll be able to force the fallback of index.html
# to an other file when you're offline
FALLBACK:
. offline.html

Automate AppCache

If your app relies on a large code base, with a build step, you will need to automate this task. You’ll also have to ensure that AppCache doesn’t mess with your development workflow (meaning disabling it when developing).

I will describe the steps I took to automate AppCache support on topheman/rxjs-experiments, a little project using RxJS (no other frameworks involved). The workflow of this project is based on a seed I made and open-sourced: topheman/webpack-babel-starter.

Checkout the App

Step 1 – Define if we should “activate” AppCache

When you’re running webpack in dev-server mode, that means you’re developing, so you want your sources to be kept up to date (you don’t want AppCache to cache them).

webpack.config.js

const MODE_DEV_SERVER = process.argv[1].indexOf('webpack-dev-server') > -1 ? true : false;
// ...
const APPCACHE = process.env.APPCACHE ? JSON.parse(process.env.APPCACHE) : !MODE_DEV_SERVER;// if false, nothing will be cached by AppCache

Continue reading

ES6+ code coverage with Babel plugin

babel-logo

Running unit tests against an ES6+ source code base has now become an almost trivial task, thanks to Babel and all the ecosystem around it. There are a lot of good resources explaining how to do that, with different tools and frameworks.

On the other hand, code coverage on this kind of tests is a rather less covered subject …

If you apply regular code coverage solutions to that case, you end up with reports based on the transpiled code, not your original source code in ES6+, which isn’t really relevant …

Here comes isparta

This problem was solved by isparta, a code coverage tool for ES6+, using Babel, which provides code coverage reports using istanbul (which is also a code coverage tool … 😉 more infos here).

Using isparta, you can generate code coverage from unit tests on ES6+ source code base, directly against your original source code (not the transpiled one). This works great, combined with tools like karma-coverage, you can output coverage reports under any format (html, lcov … that can be processed by various tools/services like Jenkins or coveralls.io …).

isparta not maintained anymore

No Maintenance Intended

About two weeks ago, @duglasduteil added the “No Maintenance Intended” badge to his module. This should remind us that behind every open source project there are developers maintaining them (most of the time on there free time).

So, now may be the time to find a replacement for isparta … I was looking for an alternative for a few days when I eventually ended up on twitter with @kentcdodds who mentionned dtinth/babel-plugin-__coverage__.

ES6+ code coverage using a Babel plugin

Since Babel v6, you can make your very own plugins that can do much more than simply transpile ES6+ to ES5.

Babel is a generic multi-purpose compiler for JavaScript. More than that it is a collection of modules that can be used for many different forms of static analysis.

Babel Plugin Handbook

That’s what @dtinth has done with babel-plugin-__coverage__. He made a babel plugin that instrument your code, injecting metadata that will be processed by istambul (which is used under the hood by karma-coverage and other coverage report tools).

The great thing is that, since you go through Babel anyway to transpile your source code, the only thing you have to do to get those infos to feed tools like karma-coverage (or any istambul-based coverage reporter) is to activate this plugin in your .babelrc file …

Using a babel plugin for coverage is a no-brainer.

@kentcdodds

You won’t have to add complex configuration or tools anymore. @dtinth‘s plugin is 300 LOC, it’s his first babel plugin that he made over two nights. As far as I have tested it, it works very well.

This is clear that using a babel plugin for that kind of purpose is the right way to proceed. Since it’s becoming easier to setup, we might see more projects using ES6+ including code coverage reports in a near futur.

You can see an example of setup on my project topheman/react-es6-redux.

Checkout it out

How to fail webpack build on error

webpack-logo

By default, webpack will tolerate any errors happening while bundling.

It’s useful when you’re running in webpack-dev-server mode, however, when you’re making your final build you might want it to fail if any error happens (the main use case being when you’re testing the build step on your CI).

For that, you can use the bail configuration option.

Here is an example of a minimal webpack.config.js setup that will fail your Travis CI tests if any error happens at build time:

const plugins = [];
const TRAVIS = process.env.TRAVIS ? JSON.parse(process.env.TRAVIS) : false;

if (TRAVIS) {
  console.log('TRAVIS mode (will fail on error)');
  plugins.push(new webpack.NoErrorsPlugin());
}

const config = {
  bail: TRAVIS,
  // ... the rest of your config
};

module.exports = config;

Resources:

Make your own React production version with webpack

react-webpack

If you’ve been developing with React, you must have seen that you are provided with very verbose errors/warnings that can come in handy.

Quote from the download page of React:

We provide two versions of React: an uncompressed version for development and a minified version for production. The development version includes extra warnings about common mistakes, whereas the production version includes extra performance optimizations and strips all error messages.

When you’re making your production bundle, you should not include all the extra code used in development (which makes extra checks not useful in production and at the end makes your bundle heavy).

The way to do that is to use the Webpack.DefinePlugin or envify, if you’re using browserify.

By doing the following, you’ll be injecting a variable process.env.NODE_ENV set to "production" at build time which is used inside React as we’ll see.

webpack.config.prod.js

module.exports = {
  //...
  plugins:[
    new webpack.DefinePlugin({
      'process.env':{
        'NODE_ENV': JSON.stringify('production')
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress:{
        warnings: true
      }
    })
  ]
  //...
}

That way, you’ll be including the same kind of code which is in react.min.js inside your bundle. If you take a look at the source code of React inside ./node_modules/react/lib, you’ll see a lot of places with a ternary like process.env.NODE_ENV !== 'production'. All those development related features will be dropped at the minification step.

Resources:

Continue reading

Optimize your bundle’s weight with webpack

webpack-logo

The usage of a package manager for the dependencies in front-end JavaScript development has become mainstream for some time now. One of the downsides is that since it’s now very easy to install and require external modules in your application, if you’re not careful, you’ll end up with a big main.js file in production …

To avoid that, you can use multiple strategies of optimization:

  • uglify
  • deduplicate code
  • split your bundle in multiple ones and only load them on demand

But the very first thing to do is to drop the unnecessary code. For that, webpack provides the Webpack.DefinePlugin which lets you inject your own variables at build time, so that if they are set to false in a conditional, the minification step will drop the dead code.

But if you are using ES6 modules import statement, there is a catch …

webpack.config.js

module.exports = {
  //...
  plugins:[
    new webpack.DefinePlugin({
      '__DEVTOOLS__': false //set it to true in dev mode
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress:{
        warnings: true
      }
    })
  ]
  //...
}

test.js

import { DevTools, logger } from 'some-devtools';

if(__DEVTOOLS__){
  DevTools();
  logger();
}

With this configuration, the code inside the if statement will be dropped at minification since it will be inlined as if(false). But you’ll still be importing those packages that you won’t be using (aka dead code).

In this case you shouldn’t be using ES6 static imports but CommonJS require syntax:

if(__DEVTOOLS__){
  const { DevTools, logger } = require('some-devtools');
  DevTools();
  logger();
}

That way, if __DEVTOOLS__ === false, not only the calls inside this if statements will be dropped but the modules DevTools and logger wont even be part of the bundle, which will make it lighter.

Note: I made this example with webpack, but this kind of feature is available on other module bundlers such as browserify. An other way to resolve that kind of problem would be to specify a list of modules to exclude at build time in production mode …

Update: If you’re doing universal JavaScript (running your code on both client and server side), a good practice would be to use process.env.DEVTOOLS instead of __DEVTOOLS__. A good example is the React setup where you make your own production version of React.

Resources: