How can I alias a default import in JavaScript?
JavascriptEcmascript 6Es6 ModulesJavascript Problem Overview
Using ES6 modules, I know I can alias a named import:
import { foo as bar } from 'my-module';
And I know I can import a default import:
import defaultMember from 'my-module';
I'd like to alias a default import and I had thought the following would work:
import defaultMember as alias from 'my-module';
But that results in a parsing (syntax) error.
How can I (or can I?) alias a default import?
Javascript Solutions
Solution 1 - Javascript
defaultMember
already is an alias - it doesn't need to be the name of the exported function/thing. Just do
import alias from 'my-module';
Alternatively you can do
import {default as alias} from 'my-module';
but that's rather esoteric.
Solution 2 - Javascript
Origins, Solution and Answer:
Background:
A module can export functionality or objects from itself for the use in other modules
The Modules Used for:
- Code reuse
- Separation of functionalities
- Modularity
What are Import Aliases?
Import aliases are where you take your standard import, but instead of using a pre-defined name by the exporting module, you use a name that is defined in the importing module.
Why is this important?
You may be importing multiple exported modules but the names of the exports (from different modules) are the same, this confuses JS. Aliases solve this.
Example of Multiple Alias Failed Compilation:
Failed to compile.
/somepath/index.js
SyntaxError: /somepath/index.js: Identifier 'Card' has already been declared (6:9)
> Importing Aliases will allow you to import similarly named exports to > your module.
import { Button } from '../components/button'
import { Card } from '../components/card'
import { Card } from 'react-native-elements'
When importing named exports (not default):
// my-module.js
function functionName(){
console.log('Do magic!');
}
export { functionName );
Import in module:
import { functionName as AliasFunction} from "my-module.js"
default export?
What isDefault export allows us to export a single value or to have a fallback value for your module.
For importing default exports:
// my-module.js
function functionName(){
console.log('Do magic!');
}
export default functionName;
Solution
The defaultMember
mentioned in the question is an alias already, you can change the name to whatever you will like.
functionName()
);
Now import the exported function (import AliasFunction from "my-module.js"
Or like this (as mentioned by @Bergi):
import {default as AliasFunction} from 'my-module.js';