Webpack allows us to use commonjs in the browser, meaning we can use node modules and npm for our dependencies on the front end. Just like on node, we can use require(), but this is ES2015. Let's look at the new module feature.
import _ from 'lodash';
// compiles to
var _ = require('lodash');
Using the import and from keywords, we can access other modules. Above is an example of importing a node module, or commonjs module. Because it is such and not an ES2015 module, we can import it with any variable name we'd like. However, when importing an ES2015 module, the naming of the variable is dependent on how it was exported. Also, like commonjs, if we're going to use a module we created we must prefix the path with ./, otherwise node will look for the module in the node_modules directory. Here are a few import and export patterns.
// importing as any var name
// must be exported as default
// @app.js
import config from './config';
// @config.js
// ...
export default config;
///////////////////////////////////////////////////////////////////
// import and export named modules
// @app.js
import {config} from './config';
// @config.js
export var config = {};
// or at the bottom of the file
export {config};
The path to the modules is relative the the current file, just like commonjs because webpack compiles it all down using commonjs remember 💯. Working with many imports and exports in the same module is easy. Very similar to commonjs as well.
// no defaults, all named
// @app.js
import {mod1, mod2, mod3} from './myModule';
// @myModule.js
var mod1, mod2, mod3;
export {mod1, mod2, mod3};
// or
export mod1 = {};
export mod2 = {};
export mod3 = {};
Angular already has a module system, so how does it work with the ES2015 module system? There are a few approaches. You can have just one angular module and rely completely on ES2015 modules. This is fine but isn't ideal when testing and limits some flexibility. Another approach, what we'll be doing, is to create a new angular module for every component. We can test the angular modules independently and hax some pretty good flexibilty. However, there cant be much more bolilerplate and repeated code with this approach.
There are other patterns like using default modules with named modules and how to handle that. The above is what you'll be using most of the time. Things to remeber are:
- You can export an assignment expression
- The brackets on the import and exports are not object literals