Transpiling and bundling modules with webpack

Webpack is a newer module bundler continuously gaining popularity. It can be basically viewed as a replacement for grunt or gulp. Webpack has a broad feature set: It can be used to bundle AMD, CommonJS and ES2015 modules. Further, it provides a feature known as code splitting that allows to group the code in multiple bundles in order to optimize how it is downloaded. Moreover, webpack can be used to bundle javascript, css, images and other assets. It also provides loaders that can be used to preprocess files before bundling them. In this blog post, I’m going to scratch the surface of loaders. I like to demonstrate how to configure the babel-loader with webpack in order that the files are transpiled whenever webpack is called.

First of all, we need to install webpack in the project as well as globally using npm.


npm install webpack –save-dev
npm install webpack -g

Next, we need to install the babel-loader as well as the babel-core. These are 3rd party components provided by babel. If babel-cli and babel-preset-es2015 in not yet installed, install them as well.


npm install babel-loader babel-core –save-dev
npm install babel-cli babel-preset-es2015 –save-dev

Next, we have to configure the webpack.config.js which contains the configuration for webpack. It is basically a CommonJS module.


module.exports = {
entry: './js/app.js',
output: {
path: './build',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
}
]
}
};

The input file is assumed to be app.js placed in the folder js. The transpiled and bundled file will be located in the folder build and is called bundle.js. Without going into the details, the loader will look for all files ending with .js  exluding the files in the node_modules. Then, it will manipulate the files and turn them from es6 to es5. To make all this happen, we only need start a command line in the project and type in webpack.

There are a lot more useful loaders that can be configured. For example, there exist a css-loader which bundles all css files, a saas-loader that does the same for saas files and a url-loader that can be used to bundle images and fonts. Without further explanation, they are inserted below.


{
test: /\.css$/,
exclude: /node_modules/,
loader: 'style-loader!css-loader'
},
{
test: /\.scss$/,
exclude: /node_modules/,
loader: 'style-loader!css-loader!saas-loader'
},
{
test: /\.(png|jpg|ttf|eot)/,
exclude: /node_modules/,
loader: 'url-loader?limit=10000'
}

view raw

webpack_loaders

hosted with ❤ by GitHub

Werbung

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit deinem WordPress.com-Konto. Abmelden /  Ändern )

Facebook-Foto

Du kommentierst mit deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s