webpack入門

在使用webpack以前,我曾經使用過gulp(也稍微寫過一下博文),雖然來講都是打包工具,可是當公司一下把一個webpack模板扔過來的時候,我一會兒就懵了,不知所措,只能慢慢的來從新學習webpack。css


 在之前使用gulp的時候,通常有一個套路以下,html

gulp.task('name...', function() {
  gulp.src('路徑/***通配符.後綴').pipe(各類gulp插件)
})

而後各類task運行都有本身的任務:編譯scss、壓縮js、打包js、壓縮圖片....一項項的都要本身寫,最後完成打包。webpack


到了webpack就徹底沒有了這個套路,甚至一開始,我沒有寫任何配置和任務,webpack均可以正常的運行。es6

最簡單的一個例子:web

直接寫一個hello.js:gulp

//hello.js 
function hello(){
  alert('hello!!');
}
而後直接運行:
webpack hello.js hello.bundle.js
就直接生成了一個hello.bundle.js:
/******/ (function(modules) { // webpackBootstrap
/******/     // The module cache
/******/     var installedModules = {};
/******/
/******/     // The require function
/******/     function __webpack_require__(moduleId){
/******/      //...............一大堆webpack內部須要用的函數,例如require模塊化實現的代碼
/******/      }
/******/  })        
/************************************************************************/
//這是咱們的代碼,由於只有一個模塊,被編寫爲第0個
/******/ ([
/* 0 */
/***/ (function(module, exports) {
//webpack不能識別咱們的代碼是否對錯,只能幫咱們這樣分好模塊
//若是這裏是es6代碼,webpack默認是不幫咱們babel到es5的
function hello(){
  alert('hello!!');
}
/***/ })
/******/ ]);

 

稍微複雜點的例子:babel

hello.js:模塊化

import a from './world';
require('style-loader!css-loader!./style.css');
function hello(){
  alert('hello!!');
}
hello();
alert(a())

world.js函數

function world(){
  return 'world';
}

export default world;

style.css:工具

html,body{
  margin:0;
  padding:0;
}
body{
  background: red;
}

運行:

webpack hello.js hello.bundle.js

生成 hello.bundle.js:

//省略。。。
/************************************************************************/
//咱們的代碼
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__world__ = __webpack_require__(1);

__webpack_require__(2);
function hello(){
  alert('hello!!');
}
hello();
alert(Object(__WEBPACK_IMPORTED_MODULE_0__world__["a" /* default */])())


/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
function world(){
  return 'world';
}

/* harmony default export */ __webpack_exports__["a"] = (world);

//省略一些style-loader的代碼

/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(4)(false);
// imports


// module
exports.push([module.i, "html,body{\n  margin:0;\n  padding:0;\n}\nbody{\n  background: red;\n}\n", ""]);

最後,咱們只須要在html裏面引入這個打包好的hello.bundle.js就能夠了。js代碼會正常運行,css也會自動插入html中。


 

相信到了這裏你們清楚webpack到底是幹什麼的了,就是將一堆亂七八糟的東西都打包成一個js文件,咱們所須要的只是引入這個文件罷了。

相關文章
相關標籤/搜索