178. Modules

7358 ワード

link: https://medium.com/sungthecoder/javascript-module-module-loader-module-bundler-es6-module-confused-yet-6343510e7bde

^< mental module - climbing the mountain of modules >

problems


the lack of Code Reusability


Imagine the code getting massive. A massive javascript file, hundreds and thousands of lines of code.
If we need to add another page, maybe in about dot html page, we have to copy this code and put it into the other html file.

the polution of Global Namespace


Once I use up 'a' as a variable in this case in the window object, I can never use 'a' again and maybe hundreds of lines down. By mistake I assign a variable 'a' and erase my 'a' function.
You want to make sure that you don't pollute the global namespace. That is the window object with all these names because of collisions with team members in working on different pieces of the codes.

the repeat of Script Tags


If we need to add another page, like an 'about' page, we still have to copy and paste Script Tags.
We don't want to do that.

the lack of dependency resolution


The scripts are added in proper order.
<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
	<script type="text/javascript" src="./1.js"></script>
	<script type="text/javascript" src="./2.js"></script>
	<script type="text/javascript" src="./3.js"></script>
	<script type="text/javascript" src="./4.js"></script>
	</body>
</html>
For example, if this script access a function from the number 4.js file, it's going to fail because the number 4.js hasn't loaded yet. So that's lack of dependency resolution.
And here's the pollution of global namespace. All the functions and variables that are declared in each of these files will be on the window object.

IIFE

  • Immediately Invoked Function Execution
  • Every time you added a file, you had to make sure that you add it in the right place because that file might be dependent on another file loading before it.

    Browserify


    Browserify is a module bundler.
    'browserify' use 'common js'.
    -------CommonJS + Browserify------------
    //js1
    module.exports = function add(a, b){
      return a+b;
    }
    
    //js2
    var add = require("./add");
    

    ES6+Webpack2

     -------ES6+Webpack2------------
     //js1
     export const add = (a, b) => a + b;
     //or
     export default function add() {
     	return a + b;
     }
    
    //js2
    import { add } from "./add";
    //or
    import add from './add';

    Webpack


    Webpack is a module bundler.
    Webpack bundles Javascript files.
    module.exports = {
    	entry: './app/main.js',
    	output: {
    		path: './dist'
    		filename: 'bundle.js'
    	}
    }