1 | # mirror-creator
|
2 |
|
3 | One more way to create an object with values equal to its key names.
|
4 |
|
5 | [![npm version](https://img.shields.io/npm/v/mirror-creator.svg?style=flat-square)](https://www.npmjs.com/package/mirror-creator)
|
6 | [![build status](https://img.shields.io/travis/shakacode/mirror-creator/master.svg?style=flat-square)](https://travis-ci.org/shakacode/mirror-creator)
|
7 | [![dependencies status](https://img.shields.io/gemnasium/shakacode/mirror-creator.svg?style=flat-square)](https://gemnasium.com/shakacode/mirror-creator)
|
8 | [![license](https://img.shields.io/npm/l/mirror-creator.svg?style=flat-square)](https://www.npmjs.com/package/mirror-creator)
|
9 |
|
10 | ## Install
|
11 |
|
12 | Get it via `npm`:
|
13 |
|
14 | ```
|
15 | npm install --save mirror-creator
|
16 | ```
|
17 |
|
18 | ## Usage
|
19 |
|
20 | ```javascript
|
21 | // actionTypes.js
|
22 | import mirrorCreator from 'mirror-creator';
|
23 |
|
24 | export default mirrorCreator([
|
25 | 'SOME_ACTION_TYPE',
|
26 | 'ANOTHER_ACTION_TYPE',
|
27 | 'ONE_MORE_ACTION_TYPE',
|
28 | ]);
|
29 |
|
30 | // Or you can specify prefix to avoid type name conflicts
|
31 | export default mirrorCreator([
|
32 | 'SOME_ACTION_TYPE',
|
33 | 'ANOTHER_ACTION_TYPE',
|
34 | 'ONE_MORE_ACTION_TYPE',
|
35 | ], { prefix: 'mydomain/' });
|
36 |
|
37 | // actionCreator.js
|
38 | import actionTypes from 'actionTypes';
|
39 |
|
40 | dispatch({ type: actionTypes.SOME_ACTION_TYPE });
|
41 | ```
|
42 |
|
43 | **Pros**: DRY & clean.
|
44 | **Cons**: If you use Closure Compiler advanced mode for JS minification — keys are not optimized. Use [`keyMirror`](https://github.com/STRML/keyMirror) instead. [Details](https://github.com/facebook/react/issues/1639#issuecomment-45188026).
|
45 |
|
46 |
|
47 | ## Why
|
48 |
|
49 | Use it if you don't like native or `keyMirror` ways of defining constants in flux / redux apps.
|
50 |
|
51 | Native way:
|
52 |
|
53 | ```javascript
|
54 | // actionTypes.js
|
55 | export const SOME_ACTION_TYPE = 'SOME_ACTION_TYPE';
|
56 | export const ANOTHER_ACTION_TYPE = 'ANOTHER_ACTION_TYPE';
|
57 | export const ONE_MORE_ACTION_TYPE = 'ONE_MORE_ACTION_TYPE';
|
58 |
|
59 | // actionCreator.js
|
60 | import * as actionTypes from 'actionTypes';
|
61 |
|
62 | dispatch({ type: actionTypes.SOME_ACTION_TYPE });
|
63 | ```
|
64 |
|
65 | **Pros**: No third-party lib required.
|
66 | **Cons**: Duplications. Noisy.
|
67 |
|
68 |
|
69 | `keyMirror` way:
|
70 |
|
71 | ```javascript
|
72 | // actionTypes.js
|
73 | import keyMirror from 'keyMirror';
|
74 |
|
75 | export default keyMirror({
|
76 | SOME_ACTION_TYPE : null,
|
77 | ANOTHER_ACTION_TYPE : null,
|
78 | ONE_MORE_ACTION_TYPE: null,
|
79 | });
|
80 |
|
81 | // actionCreator.js
|
82 | import actionTypes from 'actionTypes';
|
83 |
|
84 | dispatch({ type: actionTypes.SOME_ACTION_TYPE });
|
85 | ```
|
86 |
|
87 | **Pros**: DRY. If Closure Compiler advanced mode is used — keys are optimized.
|
88 | **Cons**: `null` noise.
|