像 nodejs 一样模块化开发

    1. module.exports = {
    2. // 入口
    3. entry: {
    4. 'index': './index.js'
    5. },
    6. // 输出
    7. output: {
    8. path: './',
    9. /*
    10. [name] 是 entry 中的 key
    11. entry: {
    12. key: value
    13. }
    14. */
    15. filename: "[name].b.js"
    16. }
    17. };

    module.exports 是 CommonJS 规范中定义一个文件对外接口的语法, 文件对外的接口是一个 object ,其中定义了一些配置参数。

    output 控制构建后的文件的存放位置和命名。 path 定义所有构建后文件的所在目录,本例中构建到当前文件夹。

    filename 控制构建后文件的文件名

    1. // content.js
    2. module.exports = "some string"
    1. /******/ (function(modules) { // webpackBootstrap
    2. /******/ // The module cache
    3. /******/ // The require function
    4. /******/ function __webpack_require__(moduleId) {
    5. /******/ // Check if module is in cache
    6. /******/ if(installedModules[moduleId])
    7. /******/ return installedModules[moduleId].exports;
    8. /******/ // Create a new module (and put it into the cache)
    9. /******/ var module = installedModules[moduleId] = {
    10. /******/ exports: {},
    11. /******/ id: moduleId,
    12. /******/ loaded: false
    13. /******/ };
    14. /******/ // Execute the module function
    15. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
    16. /******/ // Flag the module as loaded
    17. /******/ module.loaded = true;
    18. /******/ // Return the exports of the module
    19. /******/ return module.exports;
    20. /******/ }
    21. /******/ __webpack_require__.m = modules;
    22. /******/ // expose the module cache
    23. /******/ __webpack_require__.c = installedModules;
    24. /******/ // __webpack_public_path__
    25. /******/ __webpack_require__.p = "";
    26. /******/ // Load entry module and return exports
    27. /******/ return __webpack_require__(0);
    28. /******/ })
    29. /************************************************************************/
    30. /******/ ([
    31. /* 0 */
    32. /***/ function(module, exports, __webpack_require__) {
    33. var content = __webpack_require__(1)
    34. document.body.innerHTML = document.body.innerHTML + content
    35. /***/ },
    36. /* 1 */
    37. /***/ function(module, exports) {
    38. module.exports = "some string"
    39. /******/ ]);

    前面带 /**/ 的代码都是 webpack 的模块化代码,它内置了一个模块加载器

    模块 0 是 index.js 的代码,模块 1 是 的代码。如果你再 require 一个模块那么就会有模块 3。