如何使用 webpack 从控制台 require()? [英] How do I require() from the console using webpack?

查看:58
本文介绍了如何使用 webpack 从控制台 require()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从控制台 require()/导入模块?例如,假设我已经安装了 ImmutableJS npm,我希望能够在控制台中工作时使用模块中的函数.

How do I require() / import modules from the console? For example, say I've installed the ImmutableJS npm, I'd like to be able to use functions from the module while I'm working in the console.

推荐答案

这是另一种更通用的方法.

Here's another more generic way of doing this.

当前版本的 WebPack 公开了 webpackJsonp(...),可用于通过 ID 要求模块:

The current version of WebPack exposes webpackJsonp(...), which can be used to require a module by ID:

function _requireById(id) {
  return webpackJsonp([], null, [id]);
}

或在打字稿中

window['_requireById'] =
  (id: number): any => window['webpackJsonp'];([], null, [id]);

该 ID 在捆绑文件的模块顶部或通过源映射提供的原始源文件的页脚中可见.

The ID is visible at the top of the module in the bundled file or in the footer of the original source file served via source maps.

按名称要求模块要复杂得多,因为 WebPack 处理完所有源后似乎不会保留对模块路径的任何引用.但下面的代码似乎在很多情况下都能奏效:

Requiring a module by name is much trickier, as WebPack doesn't appear to keep any reference to the module path once it has processed all the sources. But the following code seems to do the trick in lot of the cases:

/**
 * Returns a promise that resolves to the result of a case-sensitive search
 * for a module or one of its exports. `makeGlobal` can be set to true
 * or to the name of the window property it should be saved as.
 * Example usage:
 *   _requireByName('jQuery', '$');
 *   _requireByName('Observable', true)´;
 */
window['_requireByName'] =
  (name: string, makeGlobal?: (string|boolean)): Promise<any> =>
    getAllModules()
    .then((modules) => {
      let returnMember;
      let module = _.find<any, any>(modules, (module) => {
        if (_.isObject(module.exports) && name in module.exports) {
          returnMember = true;
          return true;
        } else if (_.isFunction(module.exports) &&
                   module.exports.name === name) {
          return true;
        }
      });
      if (module) {
        module = returnMember ? module.exports[name] : module.exports;
        if (makeGlobal) {
          const moduleName = makeGlobal === true ? name : makeGlobal as string;
          window[moduleName] = module;
          console.log(`Module or module export saved as 'window.${moduleName}':`,
            module);
        } else {
          console.log(`Module or module export 'name' found:`, module);
        }
        return module;
      }
      console.warn(`Module or module export '${name}'' could not be found`);
      return null;
    });

// Returns promise that resolves to all installed modules
function getAllModules() {
  return new Promise((resolve) => {
    const id = _.uniqueId('fakeModule_');
    window['webpackJsonp'](
      [],
      {[id]: function(module, exports, __webpack_require__) {
        resolve(__webpack_require__.c);
      }},
      [id]
    );
  });
}

这是第一次尝试,所以一切都需要改进!

This is quick first shot at this, so it's all up for improvement!

这篇关于如何使用 webpack 从控制台 require()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆