xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

ES6 & export & export default All In One

ES6 & export & export default All In One

export

// utils.js
export const sum = (a, b ) => a + b;

export const trim = str => str.trim();

// export 导入多个模块
// import 导入多个模块
import * as utils from './utils.js';

utils.sum(1, 2);
utils.trim(' abc ');


// console.log('sum =', utils.sum(1, 2));
// console.log('trim =', utils.trim(' abc '));

export default (one)

  1. export default 匿名
// utils.js
const sum = (a, b ) => a + b;

const trim = str => str.trim();

// export default, 但是没有命名/匿名
export default {
  sum,
  trim,
};

import * as utils from './utils.js';

// console.log('utils =', utils, JSON.stringify(utils));
// utils.default
const {
    sum,
    trim,
} = utils.default;
// 使用 default

sum(1, 2);
trim(' abc ');

console.log('sum =', sum(1, 2));
console.log('trim =', trim(' abc '));
  1. export default 命名
// utils.js
const sum = (a, b ) => a + b;

const trim = str => str.trim();


// export default, 命名
const utils = {
  sum,
  trim,
};

export default utils;
// 或者
export default {
  ...utils,
};

import utils from './utils.js';

// console.log('utils =', utils, JSON.stringify(utils));

const {
    sum,
    trim,
} = utils;
// 使用 default

sum(1, 2);
trim(' abc ');

console.log('sum =', sum(1, 2));
console.log('trim =', trim(' abc '));

export default (multi)

// utils.js
const sum = (a, b ) => a + b;

const trim = str => str.trim();

export default sum;
export default trim;
// ❌ 语法错误:Only one default export allowed per module.

solution

每个文件/每个模块,只允许有一个 export default 语句✅

// sum.js
const sum = (a, b ) => a + b;

export default sum;
// trim.js
const trim = str => str.trim();

export default trim;

// multi export
import sum from './sum.js';
import trim from './trim.js';

sum(1, 2);
trim(' abc ');


refs

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2021-07-20 12:12  xgqfrms  阅读(71)  评论(4编辑  收藏  举报