Skip to content
Advertisement

Exporting a variable from server side JS file to client side JS file

I am attempting to export a simple object variable from a server side JS file to a client side JS file. In the server side file I am doing some web-scraping that ultimately results in a simple object variable. In the client side file I want to be able to access that variable.

I have found that I am indeed able to export a variable, but, if there is any commonJS syntax (correct me if I’m wrong) present in the server side file, then it will not work. The client side file will attempt to read the entire server side file including the commonJS syntax – which it can’t.

The following code demonstrates my code and the issue:

Server side file:

const module = require('random_module');

let myVar = {
  firstName: "John",
  lastName: "Doe"
}
    
export { myVar };

Client side file:

import { myVar } from 'server-side.js';

console.log(myVar);

In the example above, the require statement inhibits the import/export from working. If I remove that line, it works. However, I cannot simply remove the require statements, because these are needed in my code. I could of course have my web scraper output to a JSON file and then read from that, but that seems verbose.

Other people have tackled the issue of sharing code between node and the browser, such as this this post, however, I only need to export a simple object variable – not an entire module.

Why does the client side file attempt to read the entire server side file despite my explicit export statement targeting a simple object variable? How can I circumvent this issue?

Thank you.

Advertisement

Answer

Why does the client side file attempt to read the entire server side file despite my explicit export statement targeting a simple object variable?

It has to execute the code in the module to get the result.

It has no way of knowing that line 1 isn’t needed but lines 3-8 are.

If you import a module, you import a module. The destructuring operation is done on the whole object exported by the module.


If you’re outputting data and not code then don’t use a module. Have the browser request JSON with Ajax. You don’t need to change the web scraper so it outputs the data differently. You can write a web service end point in your server that imports the module you already have and makes the data in it available.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement