【问题标题】:How to export NPM module to use it without package name?如何导出 NPM 模块以在没有包名的情况下使用它?
【发布时间】:2020-05-14 09:19:51
【问题描述】:

我正在尝试导出一个 NPM 模块以在没有包名的情况下使用它。

这是导出模块的常用方法:

function hello(){
    console.log("hello");
}

module.exports.hello = hello;

我们是这样使用的:

const h = require("hello");

h.hello();

但我想在没有 h 变量的情况下使用它。所以我想像这样使用这个模块:

require("hello");

hello();

我怎样才能像这样导出这个模块?

【问题讨论】:

    标签: javascript node.js npm node-modules


    【解决方案1】:

    当然,只需在环境的全局范围内公开你的函数,这是window 用于浏览器或global 用于节点。如果您使用的是 webpack 之类的打包工具,您可以使用 global,其余的由 webpack 完成。

    // hello.js
    
    function hello() {
        console.log("hello");
    }
    
    window.hello = hello;
    
    module.exports = hello;
    
    // main.js
    
    require("./hello");
    
    hello(); // the same as `window.hello();`
    

    【讨论】:

      猜你喜欢
      • 2017-07-09
      • 1970-01-01
      • 2021-01-27
      • 1970-01-01
      • 1970-01-01
      • 2019-11-27
      • 2018-11-10
      • 1970-01-01
      • 2018-09-26
      相关资源
      最近更新 更多