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:
vue create import-issue
(create a Vue.js project and accept the defaults)- Create a file:
src/assets/rules/rules.json
with the following content:
[1,2,3,4,5]
- 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.