Javascript Modules
💻Programming Language
javascript
JavaScript Modules (import/export)
Differences
- AMD – one of the most ancient module systems, initially implemented by the library require.js.
- CommonJS – the module system created for Node.js server.
- UMD – one more module system, suggested as a universal one, compatible with AMD and CommonJS.
Read more here.
ES6+ syntax
There are two types of exports:
-
Default export
foo.jsconst foo = () => { ... } export default foo;other.jsimport foo from './foo'; -
Named export
foo.jsexport const foo = () => { ... }other.jsimport { foo } from './foo';
Export an import
From react-navigation-tabs, i.e. node_modules/react-navigation-tabs/lib/typescript/src/index.d.ts:
export { default as createMaterialTopTabNavigator } from './navigators/createMaterialTopTabNavigator';ES5 and older syntax
Use import and export statements to require modules.
Understanding module.exports and exports in Node.js
Own modules
Export module
foobar.js
var foo = "Hello";
var bar = function() { console.log("Amazing!" };
module.exports = { foo: foo, bar: bar };CommonJS (require/exports)
CommonJS is the module system created for Node.js server.
other.js
require('../actions/foobar.js');or
Bar.js
var Bar = React.createClass({ ... });
module.exports = Bar;other.js
require('../actions/Bar');Add third-party module (file with js functions)
require command
var express = require('express');Import Organization
- All imports needed in a file are grouped at the top.
- We form 3 groups (external, internal and component scope) of imports each separated by an empty line.
// imports from external sources (npm)
import React, { PropTypes, Component } from 'react';
import { StyleSheet } from 'react-native';
import { keys, pick, compose } from 'ramda';
// imports from other parts of the application like utils or other components (use absolute imports if configured)
import CachedImage from 'components/CachedImage';
import { pickKeys } from 'util/object';
// imports from component scope: always relative
import styles from './styles';
import GridItem from './components/GridItem';Animations
AnimatedContainer,TweenAnimationBuilder
Discuss on Twitter ● Improve this article: Edit on GitHub