简体   繁体   中英

Using my own Node module in browser with Browserify

So I have a Node server - part of this server is a set of files which perform parsing of an object into a form needed by another library.

There's nothing special about this set of files - no dependencies, just plain JS - other than it being ES6 and using a lot of module.exports .

I'd like to be able to use this parser script in the browser - I don't need to worry about anything other than putting a string into it as input and getting back the parsed object.

It seemed that I would be able to use Browserify to convert my parsing script into something that would function in the browser. I've read the entirety of their documentation however and cannot seem to get it to function.

Let's say I have wrapped my parser library in the following script:

const parse = require('./parser);

module.exports = function (s) {
    return parse(s);
}

The I run browserify main.js > bundle.js .

From their documentation, it seems like I should then be able to add the following tag to my HTML:

<script src="bundle.js"></script>

And then I would expect to be able to do something like the following in a script on that page:

const result = bundle(s); to capture the result of parsing a string through my bundle. This is what the documentation seems to be demonstrating.

That however just gives ReferenceError: bundle is not defined . After looking through the very vague information online I also tried declaring a named function to export in main.js , then trying to do name(s) or bundle.name(s); , and have tried also doing window.name = name in main.js . Same problem.

What am I misunderstanding or doing wrong here?

Solution is to do the following in main.js :

const parse = require('./parser');

function process(string) {
    return parse(string);
}

window.process = process;

Then run browserify main.js -o bundle.js .

After which in index.html I can do:

<script src="bundle.js"></script>
<script>
    window.onload = function() {
        const result = process("my query string");
        // do what you want
    }
</script>

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