zoukankan      html  css  js  c++  java
  • ES6和Node.js的import和export

    记录一下import和export的几种写法。

    1.ES6的导入和导出

    0.入口文件为index.js,引用add-content.js的内容

    1.  export default 方式,直接导出变量

    add-content.js的内容如下

    1 function write() {
    2   document.write('Hello World')
    3 }
    4 
    5 var app = {}
    6 app.write = write
    7 
    8 export default app;

    index.js引用要这样写

    1 import app from './add-content'
    2 app.write()

    2.  export  { } 方式,适合同时导出多个变量

    add-content.js的内容如下

     1 function write() {
     2   document.write('Hello World')
     3 }
     4 
     5 var app = {}
     6 app.write = write
     7 
     8 export {
     9   app
    10 }

    index.js引用要加上引号,如下

    1 import { app } from './add-content'
    2 app.write();

    3. export与变量声明的简写方式

    add-content.js的内容如下

    1 function write() {
    2   document.write('Hello World')
    3 }
    4 
    5 export var app = {
    6   write: write
    7 }

    index.js引用要加上引号,如下

    1 import { app } from './add-content'
    2 app.write();

    2.nodejs的导入和导出

    0.入口文件为index.js,引用mock.js的内容

    1.mock.js中使用module.exports方式导出

    1 module.exports = {
    2   name: 'mock.js',
    3   message: 'hello world'
    4 }

    index.js引用要这样写

    1 let mock = require('./mock')
    2 console.info(mock.name)

    2.mock.js中直接使用exports导出

    1 exports.name = 'mock'
    2 exports.message = 'hello world'

    index.js引用要这样写

    1 let mock = require('./mock')
    2 console.info(mock.name)
    3 console.info(mock.message)

    其原理是将exports指向了module.exports,而module.exports在初始化时是一个空对象。

    相当于在导出的文件里面添加了如下代码:

    1 var module = {
    2   exports: {}
    3 }
    4 var exports = module.exports

    3.导出时容易出现的两个错误

    3.1 给exports赋值,如下

    1 exports = {
    2   name: 'mock'
    3 }

    由第2部分知:exports是指向了module.exports,如果重新给exports赋值,它会指向新对象,而module.exports还是空对象。

    3.2 module.exports和exports混用

    1 exports.name = 'mock'
    2 exports.message = 'hello world'
    3 
    4 module.exports = {
    5   getName () {
    6     return 'get name function'
    7   }
    8 }

    由于对module.exports进行了赋值,所以exports方式添加的属性就会丢失,即访问不到name和message属性。

    个人建议使用module.exports = { ... } 导出会比较清晰。

    总结一下:

    ES6 Moudle:import / export

    浏览器使用也需要Babel的支持

    CommonJS: require / module.exports or exports

    node的模块化规范,浏览器使用时需要用browserify解析

    AMD: require / defined

    是requireJS的规范 define(['./a', './b'], function(a, b) {  //... })

     require是同步导入,支持动态导入,是值拷贝,导出值不会影响导入值;

    import是异步导入,导入值会随导出值变化

    备忘~

  • 相关阅读:
    python学习-装饰器
    python-内置函数
    HA高可用解决方案-RHCS部署
    mac安装nose,command not found:nosetests
    iPhone的home键进果汁了,按起来粘粘的感觉
    Reportng 的测试报告在 Jenkins 中显示不全
    atom markdown报错:AssertionError: html-pdf: Failed to load PhantomJS module.
    markdown的图片外链
    reportng定制修改
    运行maven build报错No goals have been specified for this build.
  • 原文地址:https://www.cnblogs.com/jyughynj/p/12077674.html
Copyright © 2011-2022 走看看