The 'import' statement remains undefined until I include an additional console log

I am currently working on a Vue3 project that I have set up using vue-cli and run with npm run serve. In order for all services to use a specific const, I have defined it in my main.js file.

// main.js
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import 'bootstrap'
import 'bootstrap/dist/css/bootstrap.min.css'
import "jquery"
import "bootstrap-icons/font/bootstrap-icons.css";

let x = 'google'
export {x};

const app = createApp(App)
app.use(store)
app.use(router)
app.mount("#app")

The services/GetCategoriesService.js file looks like this:

import { x } from "../main.js"

console.log(x)

In my components/footer.vue file within the <script> tag, I am executing the service script:

import * as $ from 'jquery'
import "../services/GetCategoriesService"

Initially, this setup results in 'undefined' being logged. Strangely, adding an extra console.log in my service script triggers hot reloading (without refreshing the page) and I can now see two console.log outputs with 'google'. However, upon refreshing the page, the outputs turn back to 'undefined'. Adding another console.log without refreshing leads to three 'google' prints, and then refreshing again shows three 'undefined' logs, which is quite puzzling. This issue is observed in Firefox version 105.0.

It is worth noting that using a named export of x and logging x inside a function (called from footer.vue) results in the same behavior.

Answer №1

It seems like you are encountering a circular import situation. To unravel this issue, we must delve into the workings of the import process.

The process of import can be broken down into 3 distinct phases:

  1. Construction: involves locating, fetching, and parsing all files into module records.
  2. Instantiation: entails locating memory slots for all exported values (without assigning values). It then links exports and imports to these memory slots.
  3. Evaluation: involves executing the code to assign actual values to the variables.

Illustration of the typical scenario:

// main.js
import { x } from './x'
console.log(x)

// x.js
let x = 1
export {x}

The console.log(x) in the above example will output 1 due to the sequence of actions outlined below:

  1. Construction: download and parse main.js -> download and parse x.js
  2. Instantiation: reserve memory for x but defer value assignment
  3. Evaluation: execute the code in x.js first (as it doesn't rely on any module) => assign value to x => execute the code in main.js => display the expected value in the console.log since the value of x is already set

The scenario of circular import:

// main.js
import { x } from './x'
console.log(x)
let a = 2
export {a}

// x.js
import {a} from './main'
console.log(a)
let x = 1
export {x}

The console.log(x) in main.js will output 1, but the console.log(a) in x.js will print undefined since x.js is executed first. The JavaScript engine traverses through the dependency graph and starts with the module at the bottom (usually the independent module).

Why does refreshing the page display undefined in the console.log?

As per our discussion above

Why does hot-reload reflect the expected value in console.log?

Hot-reloading simply replaces the modified module, in this case, GetCategoriesService.js. Hence, the main.js remains unchanged with its variables already having defined values

This explanation draws insights from the concepts presented in this insightful article. We highly recommend exploring it for a comprehensive understanding

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to create a TypeScript function that mimics a JavaScript function

As I look at this javascript code: // find the user User.findOne({ name: req.body.name }, function(err, user) { if (err) throw err; if (!user) { res.json({ success: false, message: 'Authentication failed. User not found.' ...

A step-by-step guide on incorporating vue-select into a basic HTML webpage

My initial experience with Vue + vue-select is a learning curve. I followed the guidelines in the vue-select documentation to import Vue and vue-select. The HTML page for my first attempt is as follows: <!DOCTYPE html> <html lang="en&qu ...

Utilize the <a> element as a button to submit the data form

I am looking to transfer data from a form to another PHP page without using a button within the form itself. Instead, I have placed a separate button outside of the form for submission. How can I achieve this by sending the form data to the other page? Bel ...

Is There a Sparse Array Element in JavaScript?

Is there a more efficient method to check for the presence of an array element within multiple layers of a structure? For example: if (typeof arr[a][b][c] === 'undefined') { ...do something... } If [a] or [b] are missing, we cannot accurately t ...

Error: The data entered is invalid because the delimiter ":" [0x3a] is missing in nodejs

I seem to be encountering an issue: Error: The data is invalid and there seems to be a missing delimiter ":" [0x3a] at Function.decode.find (/Users/Seleena/Documents/torrent/node_modules/bencode/lib/decode.js:114:9) at Function.decode.buffer ...

The Axios interceptor is failing to retrieve the user's current authentication token from the Vuex store

Currently, I am utilizing Axios to transmit user input to a DRF API, which then returns an authentication token. This token is being saved in the Vuex store. However, when I attempt to request another API endpoint using Axios with the most recent token in ...

The web server is serving an HTML file instead of the expected JSON response

Is there a way to extract the JSON data from ? I have tried using AJAX but it only retrieves the entire HTML page instead. $.ajax({ url: 'http://www.bartdekimpe.be/anoire/index.php/admin/getGamesUserJson/34', success: function(data) { ...

Using a Javascript for loop to extract the initial event date from a Google Calendar

In my home.html file, the script below is responsible for: Connecting the website to a Google Calendar API Fetching dates and names of rocket launches My concern arises when a calendar for the same rocket has multiple launches in a single month. I aim fo ...

Best practices for placing your image while utilizing require to resolve the image path in Vue

Where should you place the image for the commands to function correctly? <b-img :src="require('../static/picture.jpg')" /> <b-card-img :img-src="require('../static/picture.jpg')" /> The code above was sourced from the Vue ...

Is there a way to eliminate nested or parent objects from an array using JavaScript?

I am looking for a way to remove an object based on its id without using a MongoDB query. Instead, I want to remove the object from an array stored in a variable using a JavaScript function. For example, if I provide id=ObjectId("5b693e7ddd65ec16a46b7f82" ...

Guide to using VueJS for sending a POST request with a JSON array containing data and uploading a File or Picture for each element in the array

I am currently facing a challenge with Axios where I need to send formData from a dynamic Form to PHP. Users should be able to add multiple "persons" along with their respective data and pictures. Below is the format of the data: data: { person:{ ...

Failed to retrieve the requested item using fetch, encountering a NetworkError

My API is being accessed to retrieve data using this code snippet. It sends the email and password to the API: onSubmitSignIn = () => { fetch('http://localhost:3001/signin', { method: 'post', headers: {'Content-Type&ap ...

Activate and deactivate animation using one button with jQuery

Looking for a solution using Jquery. Can you animate an element when clicking a button and then stop the animation with the same button? Here is an example code snippet in JavaScript: $('<div>').css({ 'width':'200 ...

When working with create-react-app and TypeScript, you may encounter an error stating: "JSX expressions in 'file_name.tsx' must

After setting up a React project with TypeScript using the CLI command create-react-app client --typescript, I encountered a compilation error when running npm start: ./src/App.js Line 26:13: 'React' must be in scope when using JSX react/r ...

Issue with the back button in the browser when changing router query parameters

I am currently implementing a basic route definition: { path: 'customers', name: 'customers', component: Customers, props: true } Initially, I am navigating to the general /customers route. Howev ...

Discovering a website's console content using the "web-request" npm package

I recently added the web-request NPM package to my project with the goal of retrieving console messages from a specific website. However, I encountered an issue as I was unsure of how to achieve this. var result = await WebRequest.get('http://disco ...

Make an ajax request to a method in YII framework

I need to send an AJAX call to a function within the directory structure outlined below: Yii::$app->request->absoluteUrl."protected/humhub/modules/post/controllers/PostController/UploadMusicFile"; Here is my view function: function uploadImage ...

JavaScript code for initiating the npm start command

Is it possible to include the npm-start command in a JavaScript script? Requirement: Develop a JS script capable of triggering the npm-start command. Operating System: Microsoft Windows I need to turn it into a Windows service. However, in the code snip ...

Automating the Process of File Downloads Using Ajax and PHP

I am currently working on a form that requires users to enter a secret key. Once the key is submitted, it is verified against a database. If the key is found, the relevant file associated with the key should be downloaded automatically. I have successfully ...

CodeIgniter session not being updated after AJAX call

What could be the reason for CodeIgniter session not updating values after an AJAX request? Controller index: public function index() { $this->session->set_userdata( 'greetings', 'hello!' ); } AJAX request: $.ajax({ ty ...