// 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 页面了.
有方法达到这样的目的吗?
你总共调用的代码也就
node app.bundle.js
,这还怎么“动态加载”啊?所以我猜你的问题是,希望有这样一种机制可以持续观察源代码,如果源代码有变化,就重新编译,并更新
app.bundle.js
。如果我猜的没错,那你只要增加一个选项就可以了