As a Javascript developer, you will come across many occassions when you will have to export many functions, variables or other items from one file and import them in different files. You may end up with a code like the following
export const function1 = () => { /*something here */ } ; export const function2 = () => { /*something here */ } ; export const function3 = () => { /*something here */ } ; export const function4 = () => { /*something here */ } ; export const function5 = () => { /*something here */ } ; export const function6 = () => { /*something here */ } ; export const function7 = () => { /*something here */ } ;You can improve it using * if you want to import all the functions.And in the file you want to import you will be importing like the followingimport { function1, function2, function3, function5, function6, function7 } from './path_to_the_script'
import * as Functions from './path_to_the_script'This is a better way of importing all items from a script. I like another approach better which is to group the related exports together and give it a name and import the grouped items. So for example think of a Redux action file which may look like the following
const updateSearch = (payload) = ({type: UPDATE_SAERCH, payload}); const resetSearch = (payload) = ({type: RESET_SEARCH, payload}); const initializeSearch = (payload) = ({type: INIT_SEARCH, payload});These actions can be exported like the following
export const SearchActions = { updateSearch, resetSearch, initializeSearch }Now in the file where they are needed, we can import SearchActions. The prefix SearchAction in the code will make it clear that from where these actions are coming.
import {SearchActions} from './actions'; this.props.dispatch( SearchActions.updateSearch() );While using this approach the following rules must be followed:
- Only group together items that are related to each other in some sense e.g all of them are actions for one screen etc.
- Any function (action, helper, component) imported in a file MUST NOT be exported again. Exporting imported functions creates a so-called mapper which is against the technical requirements of the project.
- A class, function, constant etc may only be exported once. Exporting same item in multiple objects is a bad practice, for example (Notice method average is being exported from two different groups):
const sum = (a, b) = return a+b const difference = (a, b) = return a-b const average = (a, b, c) = return (a+b+c)/3 export math = { sum, difference, average # bad, exported twice! } export stats = { average # bad, exported twice! }
What do you think about the approach? Do you have a better idea of importing and exporting items?
Comments
Post a Comment