javascript – Joi reference error when importing schema in node.js

I’m seeing a reference error generated in node.js when importing a Joi schema from another module. What am I doing wrong when referencing these imported schemas?

Simplified example below:

index.js:

import Joi from 'joi';

const channelNames = ['first', 'second'];

export const channelNameSchema = Joi.string().valid(...channelNames);
export const channelIdSchema = Joi.string();

channel.js:

import Joi from 'joi';
import { channelNameSchema, channelIdSchema } from './index.js';

export const channelSchema = Joi.object({
    name: channelNameSchema.required(),
    id: channelIdSchema.required(),
}).required();

// validate the data and return
const createChannel = async (name, id) => {
    const channelData = await channelSchema.validateAsync({ name, id });
    return channelData;
};

When I save this, I get the following node error generated:

ReferenceError: Cannot access 'channelNameSchema' before initialization.

If I move channelSchema inside the createChannel function, the error disappears; however, I then can’t re-export the channelSchema for use in other modules.


Update
After some more digging, it appears that this is unrelated to Joi schemas and down to just an issue in the nodejs firebase functions emulator (or my fundamental understanding of node import/exports ????)

The following generates the same error:

// index.js

export const test="this is a test";

// channel.js

import { test } from './index.js';

export const channel = {
    test: test,
    anotherVar: 'another',
};

// emulator debug
ReferenceError: Cannot access 'test' before initialization.

Possibly related to Firebase Functions’ local emulator compiling?

Read more here: Source link