0

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?

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

1 Comment

window.process = process; that was the trick! I was trying hard to find a way how to call the function in some module from the browser and your answer seems to be the only answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.