What is the reason that the ES6 module import expression fails to import JSON files located in the assets folder when using certain path arguments?

A puzzling ES6 import scenario came up where the following import statement did not function as expected within methods of a Vue.js SFC:

const fullContentFile = '@/assets/rules/rules.json'
import(fullContentFile).then(data => console.log('data 8: ', data))

An error was thrown in the browser's console:

Uncaught (in promise) Error: Cannot find module '@/assets/rules/rules.json'
    at eval (eval at ./src/components/staboqwi lazy recursive (app.js:2117), <anonymous>:5:11)

The setup of my project to replicate this issue included:

  1. vue create import-issue (create a Vue.js project and accept the defaults)
  2. Create a file: src/assets/rules/rules.json with the following content:
    [1,2,3,4,5]
  1. In App.vue add the following created() method:
created() {
  // The first three imports work consistently:
  import('@/assets/rules/rules.json').then(data =>
    console.log('data 1: ', data)
  )
  
  const file = 'rules'
  import('@/assets/rules/' + file + '.json').then(data =>
    console.log('data 2: ', data)
  )

  const fileName = 'rules.json'
  import('@/assets/rules/' + fileName).then(data =>
    console.log('data 3: ', data)
  )

  // The next two imports lead to compilation errors when used within htmlcars project
  const fileName2 = 'rules/rules.json'
  import('@/assets/' + fileName2).then(data =>
    console.log('data 4: ', data)
  )

  const fileName3 = 'assets/rules/rules.json'
  import('@/' + fileName3).then(data => console.log('data 5: ', data))

  // These imports do not work:
  const contentFile = '/assets/rules/' + file + '.json'
  import('@' + contentFile).then(data => console.log('data 6: ', data))

  const atContentFile = '@/assets/rules/' + file + '.json'
  import(atContentFile).then(data => console.log('data 7: ', data))

  const fullContentFile = '@/assets/rules/rules.json'
  import(fullContentFile).then(data => console.log('data 8: ', data))
},

By examining the different import variations, it becomes clear that the only distinction lies in what is passed to the path argument as a String and what is saved in a const/variable.

I dedicated 2 evenings to researching on Google and Stack Overflow for an explanation. Perhaps someone more experienced in JavaScript could shed light on why the last three imports behave differently from the preceding ones.

An interesting observation is that the 4th and 5th imports disrupt the compilation process of the htmlcars project if the create() method is added to its App.vue file (remember to include the src/assets/rules/rules.json). If these imports are commented out, the project builds successfully. What could be causing this? The imports have no connection to the scss files that fail to compile.

Answer №1

It is important to understand that import() statements in modern JS projects, like those using Vue, are processed by Webpack during the build phase rather than at runtime

During the build process, Webpack must identify which files are being imported so they can be prepared for use at runtime (such as transpiling JS or preprocessing SCSS). However, due to the dynamic nature of this import function and the fact that Webpack cannot actually run your code, it can only make an educated guess about what the argument passed into import() represents.

Therefore, comparing different scenarios based on how JavaScript executes does not provide a complete picture, as the ultimate deciding factor is Webpack's ability to interpret the expression within () correctly...

To learn more about this topic, refer to Webpack's documentation on Dynamic expressions in import()

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

Issue with Material-UI AppBar buttons repositioning to center of screen upon page refresh

One of the components in my project is a Material-UI AppBar, which consists of various elements such as icons and buttons. Here is the code snippet for this component: import React from 'react' import AppBar from 'material-ui/AppBar' i ...

How to update icon for fa-play using Javascript in HTML5

I recently added an autoplay audio feature to my website. I would like to implement the functionality to pause and play the music, while also toggling the icon to fa-play at the same time. This is the HTML code I am using: <script type="text/javascri ...

What is the most effective method to convert PHP data into JSON and present it in the jQuery success scenario?

In the realm of jQuery, I have this particular piece of code: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script type="text/javascript" > $(function() { $("input[type ...

Using AJAX in jQuery to toggle the visibility of rows in a table with the each

Currently, I am working on an MVC 5 application where I am attempting to utilize a script to toggle the visibility of buttons in each row based on data retrieved from a database using Ajax. function setButtons() { $('#MyList > tbody > ...

Issues with WebPack and Vue.js proxy configuration not functioning as expected on virtual machine

I am currently in the process of developing a website using vue.js on my Mac with the webpack-dev-server and Vue CLI. I am looking to fetch data from my backend, which is hosted on a Vagrant VM (local.dev), using Vue Resource. I attempted to set up a proxy ...

Dealing with text changes in JQuery inputs: best practices

Although this question has been raised numerous times, a definitive answer remains elusive. My goal is to trigger a process (such as an ajax call) when a user types into an input field. Initially, I attempted to utilize the onchange event, but it failed to ...

Can you explain the function of mdLiveAnnouncer in Angular Material and how it operates?

Could someone provide an explanation of $mdLiveAnnouncer using this code snippet? module.controller('AppCtrl', function($mdLiveAnnouncer) { // Making a basic announcement (Polite Mode) $mdLiveAnnouncer.announce('Hey Google'); // ...

What methods can be used to maintain the selected date when the month or year is changed in the react-datepicker component of reactjs?

At the moment, I am using the Month selector and Year selector for Date of Birth in the react-datepicker component within a guest details form. The current functionality is such that the selected date is highlighted on the calendar, which works fine. How ...

Set up the transformation of object rest spread using Babel along with Webpack and Node

I am currently developing a Vue application integrated with Vuex and I am looking to utilize the ... operator for object merging. However, I am facing challenges in installing the Babel transformer needed for this task. Below is my configuration file. I a ...

Converting PHP code to utilize AJAX in JS

Within the confines of a single file (invasions.php), I have the following code: <!DOCTYPE html> <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'> <head> <meta http-equiv='con ...

Is the required attribute malfunctioning in HTML5?

I've come across some similar inquiries, but none of them address my specific question. I am working on a form where certain details are required, while others are optional. I have used the required tag for the mandatory fields. The submit button is l ...

Guide to retrieving fresh information from an API using a desktop application built on node and electron

Looking for advice on efficiently retrieving new order data from the Shopify API for a private desktop application I'm working on. Should I query the API at regular intervals while the application is active, or is there a way to implement webhooks in ...

Generating a string indicating the range of days chosen

Imagine a scenario where there is a selection of days available to the user (they can choose multiple). The list includes Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, each with an associated number from 0 to 6. For instance, Sunday ...

Vuex - modify store state without changing the original object

Currently, I am encountering an issue where my attempt to duplicate a store object for local modification is causing the original store object to also be changed. The specific method I am using is ...mapState["storeObject"] To illustrate, here is a breakd ...

Transforming the setting into redux using setTimeout

I am currently working with the following context: interface AlertContextProps { show: (message: string, duration: number) => void; } export const AlertContext = createContext<AlertContextProps>({ show: (message: string, duration: number) =&g ...

Massive HTML Table Containing Rows upon Rows

Currently, I have a server that can provide me with a list of objects in json format, and my goal is to showcase them in a table on the client side. Initially, I thought about dynamically modifying the DOM after receiving data from the server. Building th ...

Enhance your MUI treeview by incorporating stylish connecting borders

I've been trying to add borders that connect to the nodes in the mui treeview, but I'm having difficulty with not having a vertical border when it's the last leaf node. It currently looks like this: See border example here. However, it sh ...

Trouble accessing JSON file on FileZilla/FTP server

When I transfer my project to the FTP server, the JSON file I am using for data is not functioning properly. However, when I run the program on XAMP, my local server, it works perfectly. Upon inspecting the element on the FTP server, I noticed that the JSO ...

`Creating the perfect bar``

Currently working on my resume using Angular and I am interested in incorporating a visual representation of my skill level in specific subjects. Came across something that caught my eye here: https://i.sstatic.net/84cir.png The challenge now is figuring ...

Getting the value of a repeater label in JavaScript can be achieved by following these

Here is my javascript code: function btnEditClick() { alert(document.getElementById('<%=LblRefPhyID.ClientID %>').value); } <asp:Repeater ID="repeaterRefPhysicianList" runat="server"> <ItemTemplate> < ...