[Javascript] Introduce to Webpack

To use webpack, first you need to run:

npm install webpack

 

2. Create a webpack.config.js file:

module.exports = {
entry: './index.js',
output: {
filename: 'bundle.js',
path: __dirname
}
};

 

3. Using Command.js style to exports files, for example:

//alert-button.js

var _ = require('lodash');
module.exports = {
  setupButtons: function() {
    var alertButtons = document.querySelectorAll('[data-alert]');
    _.each(alertButtons, function(button) {
      button.addEventListener('click', function() {
        alert(button.innerText);
      });
    });
  }
};

Here, we use lodash in the file, therefore, we need to require lodash into the file.

 

//index.js

'use strict';
var AlertButtons = require('./alert-buttons');
var LameDomBinding = require('./lame-dom-binding');

document.addEventListener('DOMContentLoaded', function() {
  AlertButtons.setupButtons();
  LameDomBinding.bindEls(document.getElementById('textarea1'), document.getElementById('textarea2'));
});

index.js file use alert-button.js and lamedombinding.js, therefore, we also need to require those two fiels.

 

//lamedombinding.js

module.exports = {
  bindEls: function(el1, el2) {
    el1.addEventListener('keyup', function() {
      el2.value = el1.value;
    });
    el2.addEventListener('keyup', function() {
      el1.value = el2.value;
    });
  }
};

 

4. Our aim at replace all the javascript included files with only one file: bundle.js:

we run:

webpack --watch  

The bundle.js file will be created, then we can include only bundle.js into the html file.

posted @ 2015-03-03 04:17  Zhentiw  阅读(415)  评论(0编辑  收藏  举报