Search code examples
javascriptes6-modules

How to share a dynamic constant across modules?


I'm trying to properly modularise my code and keep things self contained, and build it all nicely chunked with webpack. The idea I'm wrestling with is how to get a constant shared across modules (i.e., something that would be in the global scope if put directly in the HTML).

Specifically, I have a logging module that looks like this:

'use strict';

import { v4 } from "uuid";

const ssid = v4();

function sendToLog(metric) {
    metric.ssid = ssid;
    // send to the api
}

// Send userAgent immediately
sendToLog({ ua: window.navigator.userAgent });

If I transpile that and just put it in the html file, then I later include, say, a WebVitals module

<script defer src="./dist/webvitals.js"></script>

import {getLCP} from 'web-vitals';

getLCP(sendToLog);

Then ssid will be the same in all of the calls to sendToLog. But, what I want to do is not inline the logging module, but instead have the WebVitals module (and others) import it:

logger.js:

'use strict';

import { v4 } from "uuid";

const ssid = v4();

export default function sendToLog(metric) {
    metric.ssid = ssid; 
}

and webvitals.js:

import {getLCP} from 'web-vitals';
import sendToLog from './logger';

getLCP(sendToLog);

how do I construct this so the ssid remains the same across every module that imports logger.js?


Solution

  • How do I construct this so the ssid remains the same across every module that imports logger.js?

    You already did. A module is evaluated only once, regardless how often it is imported. The top-level const ssid is essentially a static variable, an there is only a single sendToLog function, shared between all modules that import your logger.