Search code examples
javascriptnode.jsnpmrequirejs

How would you be able to use fast-json package in the browser?


I have been browsing ways on how I could improve my apps performance and came across these 2 packages. I am building a forum styled app that receives a bunch of information from APIs and regularly parses and stringifies it. I have already optimized my front end JS as much as I could(it's just vanilla JS at this point) but it sometimes still struggles to load on older phones. I would love to try these packages as they could potentially relieve my issue but they are both in NPM form.

I would like to use them in my browser UI scripts.Is there any way to use NPM packages directly in browser/ can you get a single script version of them?

Specifically:

https://www.npmjs.com/package/fast-json https://www.npmjs.com/package/fast-json-stringify


Solution

  • Very simple!

    1. Copy the code from fast-json/blob/master/lib/EventTree.js in your source code, but without module.exports block (is to bottom of the code)

    2. Copy the code from fast-json/blob/master/lib/FastJson.js in your source code, but without const { EventTree } = require('./EventTree'); (at top) and without module.exports = FastJson; (bottom)

    3. TEST TIME ^_^

    const fastJson = new FastJson();
    
    // Path is a string representing a javascript object path
    fastJson.on('ireland.people', (value) => {  
        console.log('ireland.people ->', value);
    });
    
    // Paths can be also an array of keys 
    fastJson.on(['spain', 'people', '1', 'name'], (value) => {   
        console.log(['spain', 'people', '1','name'], '->', value); 
    });
    
    // Wildcards can be used to match all items in object or array
    fastJson.on('spain.people[*].name', (value) => {  
        console.log('spain.people[*].name ->', value); 
    });
    
    fastJson.on('*.people[*].name', (value) => {  
        console.log('*.people[*].name ->', value); 
    });
    
    fastJson.write(data);