export 和export default 都可以导出常量、函数、文件、模块等,但是他们之间有什么区别呢?
export :在一个文件或模块中,export 可以支持多个,通过export导出是需要加 【{}】,而export default 不需要
export default :在一个文件或者模块中,export default只支持一个。例:
export导出与引入:utils/index.js
/** * 将时间解析为字符串 * @param {(Object|string|number)} time * @param {string} cFormat * @returns {string | null} */export function parseTime(time, cFormat) { if (arguments.length === 0 || !time) { return null } const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}' let date if (typeof time === 'object') { date = time } else { if ((typeof time === 'string')) { if ((/^[0-9]+$/.test(time))) { // support "1548221490638" time = parseInt(time) } else { // support safari // https://stackoverflow.com/questions/4310953/invalid-date-in-safari time = time.replace(new RegExp(/-/gm), '/') } } if ((typeof time === 'number') && (time.toString().length === 10)) { time = time * 1000 } date = new Date(time) } const formatObj = { y: date.getFullYear(), m: date.getMonth() + 1, d: date.getDate(), h: date.getHours(), i: date.getMinutes(), s: date.getSeconds(), a: date.getDay() } const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => { const value = formatObj[key] // Note: getDay() returns 0 on Sunday if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] } return value.toString().padStart(2, '0') }) return time_str}/** * @param {number} time * @param {string} option * @returns {string} */export function formatTime(time, option) { if (('' + time).length === 10) { time = parseInt(time) * 1000 } else { time = +time } const d = new Date(time) const now = Date.now() const diff = (now - d) / 1000 if (diff < 30) { return '刚刚' } else if (diff < 3600) { // less 1 hour return Math.ceil(diff / 60) + '分钟前' } else if (diff < 3600 * 24) { return Math.ceil(diff / 3600) + '小时前' } else if (diff < 3600 * 24 * 2) { return '1天前' } if (option) { return parseTime(time, option) } else { return ( d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分' ) }}
index.vue
import { formatTime } from '@/utils'
formatTime(this.date)
export default导出与引入:utils/index.js
const func1 = () => { console.log('func1');}const func2 = () => { console.log('func2');}export default { func1, func2}
index.vue
import common from '@/utils';
common.func1()
1、export与export default均可用于导出常量、函数、文件、模块等
2、你可以在其它文件或模块中通过import+(常量 | 函数 | 文件 | 模块)名的方式,将其导入,以便能够对其进行使用
3、在一个文件或模块中,export、import可以有多个,export default仅有一个
4、通过export方式导出,在导入时要加{ },export default则不需要,export default为模块指定默认输出,这样就不需要知道所要加载模块的变量名
5、性能方面:export 的导入:按需引入,只打包被引入的,export default 的导入:整个文件都会被打包