webpack的安装和打包js,json文件

一,前言

在webpack的世界里,一切皆为模块(html除外)
webpack只能打包js和json文件
这篇介绍webpack的安装及如何打包js和json文件

二,安装

创建测试工程目录:webpack
使用npm安装webpack,创建package.json配置文件,包含项目名称和版本号
{
  "name":"webpack_test",
  "version":"1.0.0"
}
建议先全局安装webpack
再根据项目配置局部安装对应版本的webpack,
以免本机webpack版本和项目的webpack版本不一致导致不兼容
注意:mac系统要加sudo
    // 全局安装
    npm install webpack -g
    // 局部安装
    npm install webpack --save-dev
    // 指定版本号的局部安装
    npm install webpack@3.8.1

webpack4.x版本需要单独安装webpack-cli,所以指定版本使用3.8.1

    // 全局安装
    npm install webpack@3.8.1 -g
    // 局部安装
    npm install webpack@3.8.1 --save-dev

注意:如果不全局安装webpack将无法使用webpack命令

局部安装后,package.json文件新增devDependencies中webpack

{
  "name": "webpack_test",
  "version": "1.0.0",
  "devDependencies": {
    "webpack": "3.8.1"
  }
}

测试webpack安装:

控制台在项目目录下输入webpack -v
bogon:webpack Brave$ webpack -v
3.8.1

显示版本号表示安装成功


二,打包单个文件

1,工程目录webpack下,创建测试js文件, “src/js/entry.js”

/**
 * Created by Brave on 18/7/30.
 * webpack 需要打包的源文件 打包后的输出文件
 * webpack src/js/entry.js dist/js/bundle.js
 */
document.write("hello webpack");

webpack 打包文件命令:

    webpack 需要打包的源文件 打包后的输出文件

打包src/js/entry.js到目标地址dist/js/bundle.js的打包命令为:

    webpack src/js/entry.js dist/js/bundle.js

生成dist/js/bundle.js文件和控制台输出输出:

目录

bogon:webpack Brave$ webpack src/js/entry.js dist/js/bundle.js
Hash: 37eebb37801a4c66845d
Version: webpack 3.8.1
Time: 60ms
    Asset     Size  Chunks             Chunk Names
bundle.js  2.62 kB       0  [emitted]  main
   [0] ./src/js/entry.js 147 bytes {0} [built]
Time-打包耗时
Asset-静态资源(结构图右侧静态资源)
Size-输出文件大小
[0] ./src/js/entry.js 147 bytes {0} [built]
可以看到源文件147字节,打包后2.62KB

查看打包后的输出文件:

/******/ (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, exports) {

/**
 * Created by Brave on 18/7/30.
 * webpack 需要打包的源文件 打包后的输出文件
 * webpack src/js/entry.js dist/js/bundle.js
 */
document.write("hello webpack");

/***/ })
/******/ ]);
在输出的js中,首先是一个和webpack相关的立即执行函数
在调用立即执行函数时:
/* 0 */
/***/ (function(module, exports) {

/**
 * Created by Brave on 18/7/30.
 * webpack 需要打包的源文件 打包后的输出文件
 * webpack src/js/entry.js dist/js/bundle.js
 */
document.write("hello webpack");


/***/ })

这就是 [0] ./src/js/entry.js 147 bytes {0} [built]中0的含义

模块化的概念最终所有模块都会汇总到主模块
webpack打包入口为主模块,根据依赖关系依次加载模块

在dist目录下创建index.html作为首页,并引入打包后输出的js文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript" src="./js/bundle.js"></script>
</body>
</html>

浏览器打开index.html查看输出:

hello webpack

三,打包多个文件

创建第二个js文件-second.js并暴露两个模块

// webpack支持ES6 CommonJs AMD 不支持CMD
// ES6语法暴露模块
export function test1(x){
    return x + 1;
}

export function test2(x){
    return x + 2;
}

在主模块中引入second.js暴露的两个模块

/**
 * Created by Brave on 18/7/30.
 * webpack 需要打包的源文件 打包后的输出文件
 * webpack src/js/entry.js dist/js/bundle.js
 */
// 引入模块
import {test1, test2} from './second.js'

document.write("hello webpack" + '<br />');
document.write("test1 = " + test1(1) + '<br />');
document.write("test2 = " + test2(1) + '<br />');

重新打包主模块:

webpack src/js/entry.js dist/js/bundle.js

输出:

bogon:webpack Brave$ webpack src/js/entry.js dist/js/bundle.js
Hash: 9539fd61a10e50f142f4
Version: webpack 3.8.1
Time: 75ms
    Asset     Size  Chunks             Chunk Names
bundle.js  3.44 kB       0  [emitted]  main
   [0] ./src/js/entry.js 308 bytes {0} [built]
   [1] ./src/js/second.js 141 bytes {0} [built]

查看bundle文件:

/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__second_js__ = __webpack_require__(1);
/**
 * Created by Brave on 18/7/30.
 * webpack 需要打包的源文件 打包后的输出文件
 * webpack src/js/entry.js dist/js/bundle.js
 */
// 引入模块


document.write("hello webpack" + '<br />');
document.write("test1 = " + Object(__WEBPACK_IMPORTED_MODULE_0__second_js__["a" /* test1 */])(1) + '<br />');
document.write("test2 = " + Object(__WEBPACK_IMPORTED_MODULE_0__second_js__["b" /* test2 */])(1) + '<br />');


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

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = test1;
/* harmony export (immutable) */ __webpack_exports__["b"] = test2;
// webpack支持ES6 CommonJs AMD 不支持CMD
// ES6语法暴露模块
function test1(x){
    return x + 1;
}

function test2(x){
    return x + 2;
}

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

浏览器打开index.html:

hello webpack
test1 = 2
test2 = 3

三,webpack加载Json文件

webpack只能打包js和json文件,接下来测试一下加载json

src下创建data文件夹用于存放json数据文件,新建testdata.json

{
  "name":"Brave",
  "age":"29"
}

在入口文件src/js/entry.js中引入json文件,并打印输出:

/**
 * Created by Brave on 18/7/30.
 * webpack 需要打包的源文件 打包后的输出文件
 * webpack src/js/entry.js dist/js/bundle.js
 */
// 引入模块
import {test1, test2} from './second.js'
import data from '../data/testdata.json'

document.write("hello webpack" + '<br />');
document.write("test1 = " + test1(1) + '<br />');
document.write("test2 = " + test2(1) + '<br />');
document.write("dataObj = " + data + '<br />');
document.write("dataStr = " + JSON.stringify(data) + '<br />');

webpack重新打包输出文件,查看index.html输出信息:

hello webpack
test1 = 2
test2 = 3
dataObj = [object Object]
dataStr = {"name":"Brave","age":"29"}

四,webpack.config.js配置打包

项目目录webpack下,创建webpack的config配置文件webpack.config.js

webpack.config.js

/**
 * Created by Brave on 18/7/31.
 */
// 一个 Node.js 核心模块,用于操作文件路径
const path = require('path');

module.exports = {
    entry: './src/js/entry.js',//入口文件
    output: {
        // 指定bundle 的名称
        filename: 'bundle.js',
        // 指定bundle 生成的位置
        path: path.resolve(__dirname, 'dist/js/')
    }
};
有了webpack.config.js配置文件后,只需要运行webpack命令即可打包输出

webpack命令执行后,会在当前项目目录查找webpack.config.js文件,并根据配置信息进行打包输出

五,总结

在webpack的世界里,一切皆为模块(html除外)
webpack只能打包js和json文件

猜你喜欢

转载自blog.csdn.net/ABAP_Brave/article/details/81287833