I am learning Vue JS and find that sometimes we import {} sometimes we import without {}. What is the difference, please?
import Home from '@/views/Home.vue'
import { createRouter, createWebHistory } from 'vue-router'
Thank you
I am learning Vue JS and find that sometimes we import {} sometimes we import without {}. What is the difference, please?
import Home from '@/views/Home.vue'
import { createRouter, createWebHistory } from 'vue-router'
Thank you
The import with {} is called named import and without {} is called default import.
When you export a component as export Component_Name you import it as import {Component_Name } from 'path_to_component';
When you export a component as export default Component_Name
you import it as import Component_Name from 'path_to_component'
;
It's nothing vue specific, it's just a feature of ES6 version of Javascript.
If you want all or more function(component) of the package you can use import Home from '@/views/Home.vue'
,
If you want a specific function(component) from the package you can use import { createRouter, createWebHistory } from 'vue-router'
To my mind, the way Javascript does imports is confusing, and is a common source of programming errors.
The problem is that there are no rules about default exports vs named exports, and there are no errors that come from importing the wrong thing.
For example,
import moment from 'moment' // The _right_ way to import it
const now = moment()
Compare that with this code, which looks remarkably similar, only the braces on the import are different:
import { moment } from 'moment' // The _wrong_ way to import it,
// but it doesn't throw an error (until you try and use it)
const now = moment() // Will throw an error, because moment is undefined
There is a good article here on the subject: https://humanwhocodes.com/blog/2019/01/stop-using-default-exports-javascript-module/
Conclusion
I’ve had several productivity problems importing default exports in my projects. While none of the problems are necessarily impossible to overcome, using named imports and exports seems to better fit my preferences when coding. Making things explicit and leaning heavily on tooling makes me a productive coder, and insofar as named exports help me do that, I will likely favor them for the foreseeable future. Of course, I have no control over how third-party modules I use export their functionality, but I definitely have a choice over how my own modules export things and will choose named exports.