【问题标题】:Resolving nodejs modules from other than node_modules location, is it possible?从 node_modules 位置以外的位置解析 nodejs 模块,有可能吗?
【发布时间】:2020-12-15 16:07:35
【问题描述】:

例如,当我需要一个位于node_modules 中的模块时,我可以编写const module = require('module')import module from 'module'。如果模块位于另一个位置我需要写const module = require('../location/module')等...

这种行为并不总是需要的,例如,如果我有示例,我希望用户能够复制/粘贴和运行,也可以从项目文件夹本身运行此示例。

这可以实现吗?

【问题讨论】:

    标签: node.js node-modules


    【解决方案1】:

    我不明白为什么我被否决了,但我最终编写了以下包装器来完成这项工作:

    const customRequire = function (moduleName, path) {
      let module
      try {
        module = require(moduleName)
      } catch (e) {
        try {
          module = require(`${path}/${moduleName}`)
        } catch (e1) {
          throw Error(`module ${moduleName} on path ${path} wasn't found`)
        }
      }
      return module
    }
    

    现在,如果您复制/粘贴此代码,它将起作用。如果您将在定义了所需模块且不在node_modules 中的项目中运行它,它也可以工作。

    上述解决方案适用于 CommonJS 模块系统,对于 ES6 你需要使用函数import, 到dynamically import modules

    import('/modules/my-module.js')
      .then((module) => {
        // Do something with the module.
      });
    

    【讨论】:

      猜你喜欢
      • 2012-06-12
      • 2011-11-30
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-22
      • 2018-09-01
      • 2013-09-29
      相关资源
      最近更新 更多