Bhaumik Bhatt
Bhaumik Bhatt

Reputation: 490

How to export a function and an array

I have an array of nationalities in and a function that returns the name of nationality from the CountryCode. Both of them are in a file called nationality.js.

Here is the function

map_code_to_nationality = (code) => {
    return nationalities.filter((data) => {
        return data.CountryCode == code
    })[0].Nationality
}

Now I want to export the function and the list of nationality (i.e. an array of nationalities). I tried to export both of them like this.

export const map_code_to_nationality
export const nationalities

Now if I use function keyword for map_code_to_nationality in the export statement the editor shows a syntax error and the export statements stated above gives an error in the browser that

Attempted import error: 'map_code_to_nationality' is not exported from '../../static_data/nationality_list'.

I have imported it in other file like this

import { map_code_to_nationality, nationalities } from '../../static_data/nationality_list'

How do I use both the function and array by exporting them?

Upvotes: 0

Views: 2339

Answers (3)

Muhammad Zia
Muhammad Zia

Reputation: 88

you can do :

export {map_code_to_nationality, nationalities};

and then use them in other modules, like :

import { map_code_to_nationality, nationalities } from '../../static_data/nationality_list';

Upvotes: 1

Rohan Patil
Rohan Patil

Reputation: 175

//In module.js add below code

export function multiply() {
    return 2 * 3;
}

// Consume the module in calc.js

import { multiply } from './modules.js';

const result = multiply();

console.log(`Result: ${result}`);

// Module.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Module</title>
</head>
<body>

  <script type="module" src="./calc.js"></script>
</body>
</html>

Its a design pattern same code can be found below, please use a live server to test it else you will get CORS error

https://github.com/rohan12patil/JSDesignPatterns/tree/master/Structural%20Patterns/module

Here you can also export an array as well, but remember to import it from the module

Upvotes: -1

Dragos Strugar
Dragos Strugar

Reputation: 1634

You should export them in an object, like so:

export const obj = {
  map_code_to_nationality,
  nationalities
}

And then use it in your import like so

import { obj } from '../../static_data/nationality_list';

obj.map_code_to_nationality
obj.nationalities

Alternatively, if you want somewhat more elegant syntax (with default export):

export default {
  map_code_to_nationality,
  nationalities
}

And then in the driver code, use the following:

import obj from '../../static_data/nationality_list';

obj.map_code_to_nationality
obj.nationalities

Upvotes: 1

Related Questions