简体   繁体   English

如何导出 NPM 模块以在没有 package 名称的情况下使用它?

[英]How to export NPM module to use it without package name?

I'm trying to export a NPM module to use it without package name.我正在尝试导出 NPM 模块以在没有 package 名称的情况下使用它。

This is the usual way to export module:这是导出模块的常用方法:

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

module.exports.hello = hello;

And we use this like that:我们像这样使用它:

const h = require("hello");

h.hello();

But I want to use it without h variable.但我想在没有 h 变量的情况下使用它。 So I want to use this module like that:所以我想像这样使用这个模块:

require("hello");

hello();

How can I export this module like it?我怎样才能像这样导出这个模块?

Of course, just expose your function on the global scope of your environment, this is window for the browser or global for node.当然,只需将您的 function 暴露在您环境的全局 scope 上,这是window用于浏览器或global用于节点。 If you're using a bundler like webpack, you can just use global , webpack will do the rest.如果您使用 webpack 之类的捆绑程序,则可以使用global , webpack 将执行 rest。

// hello.js

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

window.hello = hello;

module.exports = hello;
// main.js

require("./hello");

hello(); // the same as `window.hello();`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM