I am having a hard time understanding exporting and importing stuff in typescript, how should this one be constructed for example?
src/functions/handle.ts:
export default function handle() {
// do something here.
console.log("It is handled");
}
src/functions/index.ts:
import handle from './handle';
export default {
handle
};
src/run.ts:
import allFunctions from './functions';
console.log(allFunctions);
If I run node dist/run.js (I am compiling into distdirectory) after compiling, I get undefined. But if I use
import allFunctions from './functions/'
(notice the "/" at the end)
it references to an object that includes the exported function.
I also tried using export * from './handle' but the result is the same.
What is the correct way to accomplish this?
I guess what you are trying to achieve is to re-export all your functions from a single file so you just have to import that file to access them all
First of all, you cannot re-export default exports, so you will have to go for named exports. Anyway, avoid default exports, they do not provide much benefits and confuse everyone.
src/functions/handle.ts:
export function handle() {
// do something here.
console.log("It is handled");
}
src/functions/index.ts::
export * from './handle';
export * from './anotherFile';
...
src/run.ts:
import * as allFunctions from './functions/index'
Related
I have referred all the questions in stackoverflow.
But none of the suggested why and when to use default export.
I just saw that default can be metioned "When there is only one export in a file"
Any other reason for using default export in es6 modules?
Some differences that might make you choose one over the other:
Named Exports
Can export multiple values
MUST use the exported name when importing
Default Exports
Export a single value
Can use any name when importing
This article does a nice job of explaining when it would be a good idea to use one over the other.
It's somewhat a matter of opinion, but there are some objective aspects to it:
You can have only one default export in a module, whereas you can have as many named exports as you like.
If you provide a default export, the programmer using it has to come up with a name for it. This can lead to inconsistency in a codebase, where Mary does
import example from "./example";
...but Joe does
import ex from "./example";
In contrast, with a named export, the programmer doesn't have to think about what to call it unless there's a conflict with another identifier in their module.¹ It's just
import { example } from "./example";
With a named export, the person importing it has to specify the name of what they're importing. They get a nice early error if they try to import something that doesn't exist.
If you consistently only use named exports, programmers importing from modules in the project don't have to think about whether what they want is the default or a named export.
¹ If there is a conflict (for instance, you want example from two different modules), you can use as to rename:
import { example as widgetExample } from "./widget/example";
import { example as gadgetExample } from "./gadget/example";
You should almost always favour named exports, default exports have many downsides
Problems with default exports:
Difficult to refactor or ensure consistency since they can be named anything in the codebase other than what its actually called
Difficult to analyze by automated tools or provide code intellisense and autocompletion
They break tree shaking as instead of importing the single function you want to use you're forcing webpack to import the entire file with whatever other dead code it has leading to bigger bundle sizes
You can't export more than a single export per file
You lose faster/direct access to imports
checkout these articles for a more detailed explanation:
https://blog.neufund.org/why-we-have-banned-default-exports-and-you-should-do-the-same-d51fdc2cf2ad
https://humanwhocodes.com/blog/2019/01/stop-using-default-exports-javascript-module/
https://rajeshnaroth.medium.com/avoid-es6-default-exports-a24142978a7a
With named exports, one can have multiple named exports per file. Then import the specific exports they want surrounded in braces. The name of imported module has to be the same as the name of the exported module.
// imports
// ex. importing a single named export
import { MyComponent } from "./MyComponent";
// ex. importing multiple named exports
import { MyComponent, MyComponent2 } from "./MyComponent";
// ex. giving a named import a different name by using "as":
import { MyComponent2 as MyNewComponent } from "./MyComponent";
// exports from ./MyComponent.js file
export const MyComponent = () => {}
export const MyComponent2 = () => {}
You can also alias named imports, assign a new name to a named export as you import it, allowing you to resolve naming collisions, or give the export a more informative name.
import MyComponent as MainComponent from "./MyComponent";
You can also Import all the named exports onto an object:
import * as MainComponents from "./MyComponent";
// use MainComponents.MyComponent and MainComponents.MyComponent2 here
One can have only one default export per file. When we import we have to specify a name and import like:
// import
import MyDefaultComponent from "./MyDefaultExport";
// export
const MyComponent = () => {}
export default MyComponent;
The naming of import is completely independent in default export and we can use any name we like.
From MDN:
Named exports are useful to export several values. During the import, one will be able to use the same name to refer to the corresponding value.
Concerning the default export, there is only a single default export per module. A default export can be a function, a class, an object or anything else. This value is to be considered as the “main” exported value since it will be the simplest to import.
There aren't any definitive rules, but there are some conventions that people use to make it easier to structure or share code.
When there is only one export in the entire file, there is no reason to make it named.
Also, when your module has one main purpose, it could make sense to make that your default export. In those cases you can extra named exports
In react for example, React is the default export, since that is often the only part that you need. You don't always Component, so that's a named export that you can import when needed.
import React, {Component} from 'react';
In the other cases where one module has multiple equal (or mostly equal) exports, it's better to use named exports
import { blue, red, green } from 'colors';
1st Method:-
export foo; //so that this can be used in other file
import {foo} from 'abc'; //importing data/fun from module
2nd Method:-
export default foo; //used in one file
import foo from 'blah'; //importing data/fun from module
3rd Method:-
export = foo;
import * as foo from 'blah';
The above methods roughly compile to the following syntax below:-
//all export methods
exports.foo = foo; //1st method
exports['default'] = foo; //2nd method
module.exports = foo; //3rd method
//all import methods
var foo = require('abc').foo; //1st method
var foo = require('abc')['default']; //2nd method
var foo = require('abc'); //3rd method
For more information, visit to Default keyword explaination
Note:- There can be only one export default in one file.
So whenever we are exporting only 1 function, then it's better to use default keyword while exporting
EASIEST DEFINITION TO CLEAR CONFUSIONS
Let us understand the export methods, first, so that we can analyze ourselves when to use what, or why do we do what we do.
Named exports: One or more exports per module. When there are more than one exports in a module, each named export must be restructured while importing. Since there could be either export in the same module and the compiler will not know which one is required unless we mention it.
//Named export , exporting:
export const xyz = () =>{
}
// while importing this
import {xyx} from 'path'
or
const {xyz} = require(path)
The braces are just restructuring the export object.
On the other hand , default exports are only one export per module , so they are pretty plain.
//exporting default
const xyz =() >{
};
export default xyz
//Importing
import xyz from 'path'
or
const xyz = require(path)
I hope this was pretty simple to understand, and by now you can understand why you import React modules within braces...
Named Export: (export)
With named exports, one can have multiple named exports per file. Then import the specific exports they want surrounded in braces. The name of imported module has to be the same as the name of the exported module.
// imports
// ex. importing a single named export
import { MyComponent } from "./MyComponent";
// ex. importing multiple named exports
import { MyComponent, MyComponent2 } from "./MyComponent";
// ex. giving a named import a different name by using "as":
import { MyComponent2 as MyNewComponent } from "./MyComponent";
// exports from ./MyComponent.js file
export const MyComponent = () => {}
export const MyComponent2 = () => {}
Import all the named exports onto an object:
// use MainComponents.MyComponent and MainComponents.MyComponent2 here
import * as MainComponents from "./MyComponent";
Default Export: (export default)
One can have only one default export per file. When we import we have to specify a name and import like:
// import
import MyDefaultComponent from "./MyDefaultExport";
// export
const MyComponent = () => {}
export default MyComponent;
Note: The naming of import is completely independent in default export and we can use any name we like.
Here's a great answer that explains default and named imports in ES6
I was going through the codebase of an old project that uses Ember-CLI 1.13 and found something strange.
There are many helpers that are not directly used inside templates but are used in component js files by importing into them. One such example is
//..helpers/my-helper.js
export function func1 (param1, param2) {
//return something;
}
export function func2 (param1, param2) {
//return something;
}
export function func3 (param1, param2) {
//return something;
}
export default Ember.Helper.helper(func1);
export default Ember.Helper.helper(func2);
export default Ember.Helper.helper(func3);
And inside a component js file, I could see the above helpers being imported and used.
//../components/my-component.js
import Ember from "ember";
import { func1 } from '../helpers/my-helper';
import { func2 } from '../helpers/my-helper';
import { func3 } from '../helpers/my-helper';
I have few questions:
Shouldn't we create a utility instead of a helper in this case?
Is it ok to include many functions in a single helper file?
Are the imports inside the component file necessary?
Shouldn't we create a utility instead of a helper in this case?
Yes, but sometimes programmers are lazy or very restricted in time (even though moving function to utilities doesn't look like time-consuming task)
Is it ok to include many functions in a single helper file?
Yes, it is fine to have many functions in file and export them, but as far as I know, only default export will work in templates as helper. And I am 99% sure that not having default export will lead to build error.
Are the imports inside the component file necessary?
If these imports are used in component's code, then they are necessary. Otherwise, no.
I am not used to seeing a import * often
The react + readux code I am going through uses import *
According to firefox documentation about import *
This inserts myModule into the current scope, containing all the
exports from the module in the file located in /modules/my-module.js.
suppose we have an export statement like this in our code (call it articleTypes.js) .
export const ARTICLES_FETCHED = 'articles.ARTICLES_FETCHED';
Doing this, Would make actually probably make sense we didn't use export default above
import * as types from './actionTypes'
But If we alter the above lines like this
export default const ARTICLES_FETCHED = 'articles.ARTICLES_FETCHED';
and do something like this
import types from './actionTypes'
Will it work the same way as the above code? or will this actually work? and will this be a better approach?
But If we alter the above lines like this
export default const ARTICLES_FETCHED = 'articles.ARTICLES_FETCHED';
and do something like this
import types from './actionTypes'
Will it work the same way as the above code?
Will it work the same way as the above code?
No, types would be equal to 'articles.ARTICLES_FETCHED'
On the other hand, this module:
export default {ARTICLES_FETCHED: 'articles.ARTICLES_FETCHED'}
would act the same as this module:
export const ARTICLES_FETCHED = 'articles.ARTICLES_FETCHED'
The main benefit from using import * as myVar from 'module' is that you get all the exports from module wrapped up in a neat variable myVar.
I would like to combine some modules into a single file that can be imported. These are local files and not part of an npm module.
Module Kitten (kitten.js)
export function Feed() {}
export function Play() {}
In my code I can access 'Feed' and 'Play':
// This works but I would like to avoid this due to my paths
import { Feed, Play } from './some/long/path/kitten.js'
// Then use it
Feed()
As I have many 'pets' I can contenate them in a master file - say pets.js
export * as Kitten from './some/long/path/kitten.js'
export * as Puppies from './some/long/path/puppies.js'
...
In my code I can then do:
import { Kitten, Puppies } from './pets'
// Then use it as
Kitten.Feed()
is it possible to have both a) the master pets file and b) call Feed() without doing Kitten.Feed()?
The following doesn't work as it's not a valid path. It's possible it would work as 'pets/Kitten' if it was an npm module - am not sure.
import { Feed, Play } from './pets/Kitten'
I was thinking something along the lines of:
import * as Pets from from './pets'
import { Feed, Play } from Pets.Kitten // or 'Pets/Kitten'
But clearly that doesn't work. I am wondering if it's at all possible.
I am using this in Node with Babel 6 and ES6 module loading. I see a lot of similar questions but they all use default exports which I am not using.
But that doesn't allow me to import selected functions.
Sure it does. The relative-path import works the same as module import. You can destructure the results just the same.
import { Play } from 'Pet/Puppy';
// is identical to
import { Play } from '../node_modules/Pet/Puppy';
If you take a look at the import syntax (s15.2.2), you can see that the from part expects a string. It doesn't care what's in the string, that's up to the module system (the browser, node, etc).
Ah.. object destructuring.. Forgot about that.
import { Kitten, Puppies } from './pets'
const {Feed, Play} = Kitten;
Thanks to https://stackoverflow.com/a/30132149/856498
Seemingly a very simple task...
export default function() {
return {
googleClientID:'xxxx'
}
}
Is it the best way to export object literal with app settings?
You can export object itself:
export default {
googleClientID:'xxxx'
};
The difference is that in your case you will get brand new object every time you call exported function. In this case you will get the same object every time. Depends on what you need.
You can simply export an object
export default { googleClientID:'xxxx' };
A default export can be a function, a class, an object or anything else. This value is to be considered as the "main" exported value since it will be the simplest to import.
#madox2 's and #void 's answer may be some kind of common misunderstanding.
I just ran into a similar problem while issuing a PR to DefinitelyTyped -- #18725. The typescript compiler complains about the generated files.
A example should be:
// ...
import zip from "./zip";
import zipObject from "./zipObject";
import zipObjectDeep from "./zipObjectDeep";
import zipWith from "./zipWith";
export default {
// ...
zip,
zipObject,
zipObjectDeep,
zipWith
};
At the first glance, i didn't think its my problem. Because i just copy the code from lodash-es. But then i can't find any simple approach to remove the errors.
So I go to the spec for answer. Wow, the spec doesn't talk about default export of an object, if I read it right.
Conclusion:
The follow is spec-respected:
export { googleClientID:'xxxx' }
Just found some more references:
https://medium.com/#timoxley/named-exports-as-the-default-export-api-670b1b554f65#a279
https://medium.com/#rauschma/note-that-default-exporting-objects-is-usually-an-anti-pattern-if-you-want-to-export-the-cf674423ac38
Exporting: not nicest, but handy when importing later.
export const ROOT = '/tmp/test'
export const EXT = '.backup'
// ... and so on
Importing: cleanest usage (and we usually import more than export).
import { ROOT, EXT } from './literals.js'
const file = ROOT + yourFileName + EXT