import

Defination

The import statement is used to import functions, objects or primitives that have been exported from an external module, another script, etc.

Syntax

1
import defaultMember from "module-name";
2
import * as name from "module-name";
3
import { member } from "module-name";
4
import { member as alias } from "module-name";
5
import { member1 , member2 } from "module-name";
6
import { member1 , member2 as alias2 , [...] } from "module-name";
7
import defaultMember, { member [ , [...] ] } from "module-name";
8
import defaultMember, * as name from "module-name";
9
import "module-name";
Copied!

Examples

1
// --file.js--
2
function getJSON(url, callback) {
3
let xhr = new XMLHttpRequest();
4
xhr.onload = function () {
5
callback(this.responseText)
6
};
7
xhr.open('GET', url, true);
8
xhr.send();
9
}
10
11
export function getUsefulContents(url, callback) {
12
getJSON(url, data => callback(JSON.parse(data)));
13
}
14
15
// --main.js--
16
import { getUsefulContents } from 'file';
17
getUsefulContents('http://www.example.com', data => {
18
doSomethingUseful(data);
19
});
Copied!

Usage

1
// --Todo.js--
2
import React from 'react';
3
4
const Todo = ({content}) => (
5
<li><a href="/#">{content}</a></li>
6
)
7
8
export default Todo;
9
// --TodoList.js--
10
import React from 'react';
11
import Todo from './Todo';
12
13
const TodoList = ({ todos }) => (
14
<ul>
15
{todos.map((todo) => (
16
<Todo key={todo.id} content={todo.content} />
17
))}
18
</ul>
19
);
20
21
export default TodoList;
Copied!

References