table of Contents
1 Introduction
As websites gradually become "Internet applications", the Javascript codes embedded in web pages become larger and more complex.
Javascript modular programming has become an urgent need. Ideally, developers only need to implement the core business logic, and everything else can load modules already written by others. However, Javascript is not a modular programming language, it does not support concepts such as "class" (class), package (package), and "module" (module).
Therefore, two modular specifications have been introduced:
CommonJS
Modular specificationES6
Modular specification
2. CommonJS specification
Each file is a module and has its own scope. Variables, functions, and classes defined in a file are all private and invisible to other files.
CommonJS
Use exports and require to export and import modules
Project structure:
first create it 四则运算.js
, use it as a tool class, define four methods, and then export all methods
//四个方法
const sum = function (a, b) {
return a + b
}
const sub = function (a, b) {
return a - b
}
const mul = function (a, b) {
return a * b
}
const div = function (a, b) {
return a / b
}
//导出
// module.exports = {
// sum: sum,
// sub: sub,
// mul: mul,
// div: div
// }
//可简写成
module.exports = {
sum,
sub,
mul,
div
}
Then create and test.js
introduce the above module test
const fun = require('./四则运算.js');
console.log(fun.sum(1,2));
console.log(fun.sub(1,2));
console.log(fun.mul(1,2));
console.log(fun.div(1,2));
Run program test
3. ES6 Modular Specification
ES6
Use export and import to export and import modules.
Writing one
Project structure:
first create it 工具.js
and use it as a tool class, which defines and exports two methods
export function get(){
console.log("获取");
}
export function save(){
console.log("保存");
}
Then create 工具.js
, used to import the above method and test
//导入方法
import {
get,save} from './工具.js';
get();
save();
Run the test:
It is found that an error is reported. This is because nodejs
the import
syntax of es6 is not supported by default , we need to Babel
convert to ES5 syntax and then execute
Initialize the project into a nodejs
project
npm init -y
Write .babelrc
configuration file
{
"presets": ["es2015"],
"plugins": []
}
Then install the transcoder, install it in the project
npm install --save-dev babel-preset-es2015
Then you can transcode, we will create a src
directory in the project root directory, and then move the 测试.js
and 工具.js
into, and then enter the following command to transcode
babel src -d dist
Then open the new build and dist/测试.js
run the test. The
result is displayed successfully!
Writing method two (recommended)
工具.js
change into:
export default {
get() {
console.log("获取");
},
save() {
console.log("保存");
}
}
测试.js
change into:
//以对象形式导入
import tool from './工具.js';
tool.get();
tool.save();
Then perform the same transcoding execution