You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/13-modules/01-modules-intro/article.md
+11-7Lines changed: 11 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -188,9 +188,13 @@ That's exactly because the module is executed only once. Exports are generated,
188
188
189
189
In other words, a module can provide a generic functionality that needs a setup. E.g. authentication needs credentials. Then it can export a configuration object expecting the outer code to assign to it.
190
190
191
-
For instance, the `admin.js` module may provide certain functionality (e.g. authentication), but expect the credentials to come into the `config` object from outside.
191
+
Here's a classical pattern:
192
+
1. A module exports some means of configuration, e.g. a configuration object.
193
+
2. On the first import we initialize it, write to its properties. The top-level application script may do that.
194
+
3. Further imports use the module.
195
+
196
+
For instance, the `admin.js` module may provide certain functionality, but expect the credentials to come into the `config` object from outside:
192
197
193
-
First, we can export the `config` object (here it's initially empty, but that's not always the case):
194
198
```js
195
199
// 📁 admin.js
196
200
exportlet config = { };
@@ -200,6 +204,8 @@ export function sayHi() {
200
204
}
201
205
```
202
206
207
+
Here, `admin.js` exports the `config` object (initially empty, but that's not always the case).
208
+
203
209
Then in `init.js`, the first script of our app, we set `config.user`:
204
210
205
211
```js
@@ -208,7 +214,9 @@ import {config} from './admin.js';
208
214
config.user="Pete";
209
215
```
210
216
211
-
...Now the module is configured. It's `config` property has the right user, and it can say hi to them (or provide authentication or whatever):
217
+
...Now the module is configured.
218
+
219
+
Further importers can call it, and it correctly shows the current user:
212
220
213
221
```js
214
222
// 📁 another.js
@@ -217,10 +225,6 @@ import {sayHi} from './admin.js';
0 commit comments