178. Modules
^< 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'
}
}
Author And Source
이 문제에 관하여(178. Modules), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@bianjy/178.-Modules저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)