webpack 引入模块的一个疑问

// app.js
var msg = require("./msg.js")

console.log(msg)


// msg.js
module.exports = "Hello World"

使用 webpack 打包后:

// app.bundle.js
/******/ (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] = {
/******/             exports: {},
/******/             id: moduleId,
/******/             loaded: false
/******/         };

/******/         // Execute the module function
/******/         modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/         // Flag the module as loaded
/******/         module.loaded = 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;

/******/     // __webpack_public_path__
/******/     __webpack_require__.p = "";

/******/     // Load entry module and return exports
/******/     return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

    var msg = __webpack_require__(1)

    console.log(msg)

/***/ },
/* 1 */
/***/ function(module, exports) {

    module.exports = "Hello world"

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

在这里可以发现 msg.js 已经打包进去了, 当我们修改这个 msg.js 的时候, 执行 node app.bundle.js 的执行结果还是没有变化, 有没有一种实现去实现动态加载那个 msg.js 文件???

追加解释:

不是这个意思, 比如我现在想用 react 做一个模板引擎, 通过读 config.js 这样的配置文件中的配置, 来生成新的 html 页面. 上面 webpack 打包的时候, 将 config.js 文件都包含进去了, 所以当你修改 config.js 文件的时候, 达不到只需要执行一次打包后的js文件就生成不同的html文件的目的. 需要重新用 webpack 来打包.

我现在想做一个工具:
这个工具达到的目的是通过读 config.js 文件,来生成 html 页面. 这样对于使用者来说, 他不需要知道生成的具体逻辑, 只需要配置 config.js, 然后运行我提供给他的文件 比如 app.bundle.js 这样, 就能生成 html 页面了.

有方法达到这样的目的吗?

阅读 6k
2 个回答

你总共调用的代码也就node app.bundle.js,这还怎么“动态加载”啊?
所以我猜你的问题是,希望有这样一种机制可以持续观察源代码,如果源代码有变化,就重新编译,并更新app.bundle.js

如果我猜的没错,那你只要增加一个选项就可以了

webpack -w

感觉个人思想陷入了误区.

webpack 的作用是一个打包工具, 顾名思义就是所有的文件打包 + 同时有个入口函数, 直接执行那个入口函数就行.

昨天上面的那种情形, 其实可以不使用 webpack, 因为是个工具,那么直接把工程看成一个包, 直接给设计人员使用就行.

nodejs 对 javascript 的 es6 语法也已经支持了. 只不过有 3 个模式:

详细介绍

所以在这种情形下, 可以直接执行 > node --harmony --harmony_destructuring app.js

在这里感谢 @leftstick 的回答

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进