简体   繁体   中英

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.

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. 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. If you're using a bundler like webpack, you can just use global , webpack will do the rest.

// hello.js

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

window.hello = hello;

module.exports = hello;
// main.js

require("./hello");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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