前端模块化导入导出

前端模块化引入与导出

事实上,前端模块化的方式有四种

1. AMD规范 : require.js
2. CMD规范 : Sea.js
3. CommonJS规范:nodejs规范
4. ES6模块化规范

然而,在实际项目中,用到的模块化导入导出方式并没有如此多,前两种导出方式并不经常用。

根据那啥二八法则,举例展示主要的导出方式:CommonJS规范和ES6模块化规范

CommonJS规范

第一种方式:

// m1.js

let a = 10;

function sum(a, b) {
    return a + b;
}


class Animal {
    constructor() {
        this.age = 20;
    }
}

exports.a = a;
exports.sum = sum;
exports.Animal = Animal;

第二种方式:

// m1.js

let a = 10;

function sum(a, b) {
    return a + b;
}


class Animal {
    constructor() {
        this.age = 20;
    }
}

module.exports = {
    a,
    sum,
    Animal
}

导入:

const m1 = require("./m1");


console.log(m1);            // { a: 10, sum: [Function: sum], Animal: [class Animal] }

console.log(m1.a);          // 10
console.log(m1.sum(1, 2));      // 3

let cat = new m1.Animal();
console.log(cat.age);       // 20

个人感觉第二种导出方式更加方便 ,需要注意的是,不推荐两种方式同时使用

在this的指向问题上,还是需要注意的

exports是module.exports的引用, 在js文件中有exports, 交互模式下是没有exports的

在js文件中 this指向的是这个模块导出的对象 module.exports

在交互模式下 this === global成立

在js文件中 ⬇

let aa = 10;
exports.a = 10;


console.log(exports);                       // { a: 10 }
console.log(module.exports);                // { a: 10 }
console.log(exports === module.exports);    // true
console.log(this);                          // { a: 10 }
console.log(this === module.exports);       // true
console.log(this === exports);              // true

交互模式下⬇

Welcome to Node.js v18.6.0.
Type ".help" for more information.
> this === global
true
> exports
Uncaught ReferenceError: exports is not defined
> module.exports
{}
> this === module.exports
false

ES6模块化规范

首先说明一点,在nodejs中,默认是不支持ES6模块化规范的,我们会用到第三方转换工具(babel-cli 和 browserify)将其转换为 Commonjs 规范,当然,在框架开发中这些都是安排好的

导出数据方式一:

export let name = "nodejs";
export let age = 11;

导出数据方式二:

let name = "nodejs";
let age = 11;

export {name, age}

针对导出数据的前两种方式的导入数据:

import {name,age} from "./m1.js"

导出数据方式三:

// 默认导出只能写一次
export default {name, age}

导入并使用数据:

import m3 from "./m3"
console.log(m3.name);
console.log(m3.age);

在es6中的默认导出的写法,允许和前面的导出方式一起写:

导出数据:

let name = "nodejs";
let age = 11;

export let email = "nodejs@163.com";

// 默认导出只能写一次
export default {name, age}

导入并使用数据:

import m3, {email} from "./m3"

console.log(m3.name);
console.log(m3.age);
console.log(email);

版权声明:本文为m0_51126511原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。