12/08/2018, 16:57

Bạn biết gì về Webpack?

Giới thiệu Những năm gần đây, khách hàng ngày càng yêu cầu cao về sản phẩm và phần lớn là về front-end. Việc xử lý ở front-end ngày càng được chú trọng. Front-end Dev phải làm sao để giải quyết vấn đề này? Webpack là một module bundler (https://github.com/webpack/docs/wiki/what-is-webpack) Webp ...

Giới thiệu

Những năm gần đây, khách hàng ngày càng yêu cầu cao về sản phẩm và phần lớn là về front-end. Việc xử lý ở front-end ngày càng được chú trọng. Front-end Dev phải làm sao để giải quyết vấn đề này? Webpack là một module bundler (https://github.com/webpack/docs/wiki/what-is-webpack) Webpack ra đời như một giải pháp giúp tăng tốc độ xử lý web, cũng như giúp quản lý resource trở nên hiệu quả hơn. Tại sao mình lại để webpack trong series 2018 - Cùng nhau học VueJS? VueJS cũng như các framework khác đều sử dụng webpack để quản lý vì tính năng ưu việt của nó. Tìm hiểu về VueCLI bạn sẽ hiểu hơn nhé.

Sử dụng webpack như thế nào?

Khởi tạo: Tạo folder có tên webpack-demo. mở folder lên và thực hiện gõ các lệnh bên dưới:

$ mkdir webpack-demo && cd webpack-demo
$ npm init -y
$ npm install --save-dev webpack
$ npm install -g webpack

Tạo lần lượt các file như bên dưới Tạo file index.js

import hello from './hello';
hello('Quy');

Tạo file hello.js

export default function xinchao(name) {
    console.log(name);
}

Tạo file index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="awidth=device-awidth, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    
</body>
</html>
<script src="./dist/bundle.js"></script>

Tạo file bundle.js file này để trống nhé vì các file js sẽ được bundle vào đây.

$ mkdir dist && cd dist
$ touch bundle.js

Tạo file webpack.config.js : Việc bundle các file sẽ dựa vào đây, bạn có thể thay đổi các config tùy vào yêu cầu và mục đích của bạn

const path = require('path');

module.exports = {
        entry: './src/index.js',
        output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
};

Cấu trúc project sau khi đã tạo xong, bạn có thể tham khảo: https://github.com/vanquynguyen/webpack-demo

 webpack-demo
  
+ |- dist
+   |- bundle.js
+ |- /src
+   |- index.js
+   |- hello.js
+ |- index.html
+ |- package.json
+ |- webpack.config.js

Sau khi đã tạo xong môi trường và config. Tiến hành webpack bằng lệnh:

$ webpack

Sau khi chạy lệnh webpack các file js trên sẽ được bundle vào file bundle.js File bundle.js sau khi thực hiện webpack

/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

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

Object(__WEBPACK_IMPORTED_MODULE_0__hello__["a" /* default */])('Quy');

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

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = xinchao;
function xinchao(name) {
    console.log(name);
}


/***/ })
/******/ ]);

Ta có thể thấy các file js đã được bundle vào file bundle.js, lúc này ta chỉ cần gọi script đến file bundle.js. Khá đơn giản đúng không nào             </div>
            
            <div class=

0