详解require和import

当前端应用越来越复杂时,我们想要将代码分割成不同的模块,便于复用、按需加载等。

require import 分别是不同模块规范下引入模块的语句,下文将介绍这两种方式的不同之处。

require/exports import/export
Node.js 所有版本 Node 9.0+(启动需加上 flag --experimental-modules) Node 13.2+(直接启动)
Chrome 不支持 61+
Firefox 不支持 60+
Safari 不支持 10.1+
Edge 不支持 16+

CommonJS 模块化方案 require/exports 是为服务器端开发设计的。服务器模块系统 同步读取模块文件内容 ,编译执行后得到模块接口。(Node.js 是 CommonJS 规范的实现)。

在浏览器端,因为其 异步加载脚本文件 的特性,CommonJS 规范无法正常加载。所以出现了 RequireJS、SeaJS 等(兼容 CommonJS )为浏览器设计的模块化方案。直到 ES6 规范出现,浏览器才拥有了自己的模块化方案 import/export。

两种方案各有各的限制,需要注意以下几点:

  • 原生浏览器不支持 require/exports ,可使用支持 CommonJS 模块规范的 Browsersify、webpack 等打包工具,它们会将 require/exports 转换成能在浏览器使用的代码。
  • import/export 在浏览器中无法直接使用 ,我们需要在引入模块的 <script> 元素上添加 type="module" 属性。
  • 即使 Node.js 13.2+ 可以通过修改文件后缀为 .mjs 来支持 ES6 模块 import/export,但是 Node.js 官方不建议在正式环境使用 。目前可以使用 babel 将 ES6 的模块系统编译成 CommonJS 规范(注意:语法一样,但具体实现还是 require/exports)。
  • require 是运行时动态加载,import 是静态编译。

    require是CommonJS的语法,加载的模块是对象(即 module.exports 属性),该对象只有在脚本运行完才会生成,输入时必须查找对象属性。

    // CommonJS模块
    let { stat, exists, readFile } = require('fs');
    // 等同于
    let _fs = require('fs');
    let stat = _fs.stat;
    let exists = _fs.exists;
    let readfile = _fs.readfile;
    

    整体加载fs模块(即加载fs所有方法),生成一个对象"_fs",然后再从这个对象上读取三个方法,这叫“运行时加载”,因为只有运行时才能得到这个对象,不能在编译时做到静态化。

    ES6 import 模块不是对象,它的对外接口只是一种静态定义,使得编译(代码静态解析阶段)时就能确定模块的依赖关系,以及输入和输出的变量。

    import { stat, exists, readFile } from 'fs';
    

    ES6模块不是对象,而是通过export命令显示指定输出代码,再通过import输入。

    从fs加载“stat, exists, readFile” 三个方法,其他方法不加载

    require/exports 输出的是一个值的拷贝,import/export 模块输出的是值的引用

    require/exports 输出的是值的拷贝。也就是说,一旦输出一个值,模块内部的变化就影响不到这个值。

    import/export 模块输出的是值的引用。JS 引擎对脚本静态分析的时候,遇到模块加载命令import,就会生成一个只读引用。等到脚本真正执行时,再根据这个只读引用,到被加载的那个模块里面去取值。

    若文件引用的模块值改变,require 引入的模块值不会改变,而 import 引入的模块值会改变。

    require 相关的用法

    // common/utils.js
    exports.name = 'cao ding shuan'
    module.exports.age = 24
    console.log(exports, module.exports) 
    // index.js
    const util = require('./common/util')
    // 输出 { name: 'cao ding shuan', age: 24 } { name: 'cao ding shuan', age: 24 }
    

    exports 是对 module.exports 的引用,相当于

    exports = module.exports = {};
    

    exports 指向了其他对象,exports 改变不会改变模块输出值,而修改了module.exports的指向,则会改变模块输出值。示例如下:

    // common/utils.js
    exports.a = 200;
    console.log(exports, module.exports)
    exports = { a: 300 }; //exports 指向其他内存区
    console.log(exports, module.exports)
    // index.js
    const util = require('./common/util')
    console.log('util', util)
    // 输出 
    // { a: 200 } { a: 200 } 
    // { a: 300 } { a: 200 }
    // util { a: 200 }
    
    // common/utils.js
    exports.a = 200;
    console.log(exports, module.exports)
    exports = { a: 300 }; //exports 指向其他内存区
    module.exports = { a: 400}; // module.exports 指向其他内存区
    console.log(exports, module.exports)
    // index.js
    const util = require('./common/util')
    console.log('util', util)
    // 输出 
    // { a: 200 } { a: 200 } 
    // { a: 300 } { a: 400 }
    // util { a: 400 }
    

    import/export 用法

    Module 主要由两个命令组成,import和export,export用于规定模块的对外接口,import命令用于输入其他模块提供的功能。

    export

    模块是独立的文件,该文件内部的所有的变量外部都无法获取。如果希望获取某个变量,必须通过export输出,

    // utils/index
    export const name = 'caodingshuan'
    export const age = 27
    export const sex = 'man'
    // index.js
    import { name, age, sex } from './utils/index'
    console.log(name, age, sex) 
    // 输出 caodingshuan 27 man 
    

    或者用更好的方式:用大括号指定要输出的一组变量

    // utils/index
    const name = 'caodingshuan'
    const age = 27
    const sex = 'man'
    export { name, age, sex }
    

    除了输出变量,还可以输出函数或者类(class)

    export function echoHello () {
      console.log('hello')
    

    还可以批量输出,同样是要包含在大括号里,也可以用as重命名:

    function v1() { ... }
    function v2() { ... }
    export {
      v1 as streamV1,
      v2 as streamV2,
      v2 as streamLatestVersion // 可有多个不同重命名
    

    注意: export 命令规定的是对外接口,必须与模块内部变量建立一一对应的关系

    // 写法一
    export var m = 1;
    // 写法二
    var m = 1;
    export { m };
    // 写法三
    var n = 1;
    export {n as m};
    // 报错
    export 1;
    // 报错
    var m = 1;
    export m;
    

    报错的写法原因是:没有提供对外的接口,第一种报错直接输出1,第二种报错虽然有变量m,但还是直接输出1,导致无法解构。

    同样的,functionclass的输出,也必须遵守这样的写法。

    // 报错
    function f() {}
    export f;
    // 正确
    export function f() {};
    // 正确
    function f() {}
    export { f };
    

    export语句输出的接口,都是和其对应的值是动态绑定的关系,即通过该接口取到的都是模块内部实时的值。

    export模块可以位于模块中的任何位置,但是必须是在模块顶层,如果在其他作用域内,会报错。

    function foo() {
      export default 'bar' // SyntaxError
    foo()
    

    import

    export定义了模块的对外接口后,其他JS文件就可以通过import来加载这个模块

    import命令接受一对大括号,里面指定要从其他模块导入的变量名,必须与被导入模块对外接口的名称相同

    如果想重新给导入的变量一个名字,可以用as关键字

    import { lastName as surname } from './profile';
    

    import后的from 可以指定需要导入模块的路径名,可以是绝对路径,也可以是相对路径, .js路径可以省略,如果只有模块名,不带有路径,需要有配置文件指定。

    注意,import命令具有提升效果,会提升到整个模块的头部,首先执行。(是在编译阶段执行的)

    因为import是静态执行的,不能使用表达式和变量,即在运行时才能拿到结果的语法结构(e.g. if...else...)

    module的整体加载

    除了指定加载某个输出值,还可以用*指定一个对象,所有的变量都会加载在这个对象上。

    使用 * 虽然很方便,但是不利于现代的构建工具检测未被使用的函数,影响代码优化。

    // circle.js。输出两个函数
    export function area(radius) {
      return Math.PI * radius * radius;
    export function circumference(radius) {
      return 2 * Math.PI * radius;
    // main.js 加载在个模块
    import { area, circumference } from './circle';
    console.log('圆面积:' + area(4));
    console.log('圆周长:' + circumference(14));
    //上面写法是逐一指定要加载的方法,整体加载的写法如下。
    import * as circle from './circle';
    console.log('圆面积:' + circle.area(4));
    console.log('圆周长:' + circle.circumference(14));
    

    注意,import引入后,不允许运行时改变引入模块。

    import * as circle from './circle';
    // 下面两行都是不允许的
    circle.foo = 'hello';
    circle.area = function () {};
    

    注意: 在验证代码的时候遇到如下报错

    access to script from origin 'null' has been blocked by CORS policy
    

    前面提到过,浏览器引入模块的 <script> 元素要添加 type="module 属性,但 module 不支持 FTP 文件协议(file://),只支持 HTTP 协议,所以本地需要使用 http-server 等本地网络服务器打开网页文件。

    export default

    之前的例子中,使用import导入时,都需要知道模块中所要加载的变量名或函数名,用户可能不想阅读源码,只想直接使用接口,就可以用export default命令,为模块指定输出

    // export-default.js
    export default function () {
      console.log('foo');
    

    其他模块加载该模块时,import命令可以为该匿名函数指定任意名字。

    // import-default.js
    import customName from './export-default';
    customName(); // 'foo'
    

    export default也可以用于非匿名函数前。

    下面比较一下默认输出和正常输出。

    // 第一组
    export default function crc32() { // 输出
      // ...
    import crc32 from 'crc32'; // 输入
    import customName from 'crc32'; // 输入
    // 第二组
    export function crc32() { // 输出
      // ...
    import { crc32 } from 'crc32'; // 输入
    

    可以看出,使用export default时,import语句不用使用大括号({})。

    注意: 一个文件只能导出一个 default 模块。

    import()函数

    importexport命令只能在模块的顶层,不能在代码块之中。否则会语法报错。

    这样的设计,可以提高编译器效率,但是没有办法实现运行时加载。

    因为require是运行时加载,所以import命令没有办法代替require的动态加载功能。

    所以引入了import()函数。完成动态加载。

    import(specifier)
    

    specifier用来指定所要加载的模块的位置。import能接受什么参数,import()可以接受同样的参数。

    import()表达式加载模块并返回一个 promise,该 promise resolve 为一个包含其所有导出的模块对象。

    我们可以在代码中的任意位置动态地使用它。例如:

    // utils/index.js
    export default {
      People: class People {
        constructor (name, age) {
          this.name = name
          this.age = age
        toString () {
          console.log(this.name, this.age)
        toError () {
          throw new Error('进入错误处理')
    // index.js
    import('./utils/index')
      .then((res) => {
        const newPeople = new res.default.People('cao ding shuan', 27)
        newPeople.toString()
        newPeople.toError()
      .catch(err => {
        console.error(err)
    // 输出
    // cao ding shuan 27
    // Error: 进入错误处理
    

    建议: 请不要滥用动态导入 import()(只有在必要情况下采用)。静态框架能更好的初始化依赖,而且更有利于静态分析工具和 tree shaking 发挥作用

    import()函数适用场合

    button.addEventListener('click', event => {
      import('./dialogBox.js')
      .then(dialogBox => {
        dialogBox.open();
      .catch(error => {
        /* Error handling */
    

    import模块在事件监听函数中,只有用户点击了按钮,才会加载这个模块。

    import()可以放在if...else语句中,实现条件加载。

    if (condition) {
      import('moduleA').then(...);
    } else {
      import('moduleB').then(...);
    

    require 与 import的差异

    引用与使用

    ES6 模块可以在 import 引用语句前使用模块,CommonJS 则需要先引用后使用

    ES6 模块

    //webUtils.js
    export const e = 'export';
    console.log(e) //export
    import { e } from './webUtils.js';
    console.log(e) //export
    

    CommonJS

    // utils.js
    exports.e = 'export';
    console.log(a) 
    a = require('./utils');
    console.log(a)
    

    Cannot access 'a' before initialization

    作用域区别

    import命令只能在模块顶层使用,不能在函数、判断语句等代码块之中引用;require可以。

       import fs from  './webUtils.js';
       function a(){
        import {e1} from './webUtils.js';
        console.log(e1)
       a();
       console.log(fs())
    

    Uncaught SyntaxError: Unexpected token '{'

    前面提到过 import/export 在代码静态解析阶段就会生成,不会去分析代码块里面的 import/export,所以程序报语法错误,而不是运行时错误。

    是否严格模式

    严格模式是采用具有限制性JavaScript变体的一种方式

    import/export 导出的模块默认调用严格模式。
    ES6 模块之中,顶层的this指向undefined,即不应该在顶层代码使用this

    var fun = () => {
        mistypedVaraible = 17; //报错,mistypedVaraible is not defined
    export default fun;
    

    require/exports 默认不使用严格模式,可以自定义是否使用严格模式。 例如

    exports.fun = () => {
     mistypedVaraible = 17; //没有调用严格模式,不会报错
    

    参考文章:

  • juejin.cn/post/684490…
  • juejin.cn/post/684490…
  • zh.javascript.info/modules-dyn…
  • www.zhangxinxu.com/wordpress/2…
  • zhuanlan.zhihu.com/p/75980415
  • juejin.cn/post/684490…
  •