zoukankan      html  css  js  c++  java
  • exports 和module.exports转

    https://blog.csdn.net/weixin_40817115/article/details/81534819

    情景重现

    a.js

    export let test = function () {
      console.log('1');
    }
    • 1
    • 2
    • 3

    b.js

    let a= require ('./a');
    a.test();
    • 1
    • 2

    运行node b,即出现如下报错:

    export default {
    ^^^^^^
    
    SyntaxError: Unexpected token export
    • 1
    • 2
    • 3
    • 4

    解决方法

    a.js改为如下:

    exports.test = function () {
      console.log('1');
    }
    • 1
    • 2
    • 3

    根本原因

    Node和浏览器端所支持的模块规范不同。

    条目Node浏览器
    模块规范 CommonJS ES6
    导出 * modules.exports; exports export; export default
    引入 require import;require
    1. 关于exports和module.exports
    • 在一个node执行一个文件时,会给这个文件内生成一个 exports和module对象,
      而module有一个exports属性。
    • exports = module.exports = {};
    2. 关于 export 和export default
    • export与export default均可用于导出常量、函数、文件、模块等
    • 在一个文件或模块中,export、import可以有多个,export default仅有一个
    • 通过export方式导出,在导入时要加{ },export default则不需要
    • export能直接导出变量表达式,export default不行。
  • 相关阅读:
    JS清除IE浏览器缓存的方法
    大数据基础2
    CI/CD
    手机连接fiddler
    npm run build 报错
    django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.2
    读取ini文件的方法
    ES小知识
    svn连接pycharm
    创建python文件时添加相关信息
  • 原文地址:https://www.cnblogs.com/zhangzs000/p/9744108.html
Copyright © 2011-2022 走看看