js导入导出方法的写法

  

// Name Export | Name Import
export const name = 'value'
import { name } from '...'

// Default Export | Default Import
export default 'value'
import anyName from '...'

// Rename Export | NameImport
export { name as newName }
import { newName } from '...'

// Name + Default | Import All
export const name = 'value'
export default 'value'
import * as anyName from '...'

// Export List + Rename | Import List + Rename
export {
  name1,
  name2 as newName2
}
import {
  name1 as newName1,
  newName2
} from '...'

1 命名

export const name = 'value';

import { name } from 'some-path/file';

console.log(name); // 'value'



❌ 错误写法
export 'value'

import { } // 👈 see I don't even know what to put here...give me a name!

2 默认导出

export default 'value'

import anyName from 'some-path/file';

console.log(anyName); // 'value'


❌ 默认无变量声明
export default const name = 'value'; // don't try to give me a name!

3 默认和名称导出合并到一个文件中

export const name = 'value';
export default 'value'

import anyName, { name } from 'some-path/file';

4 统一出口列表

const name1 = 'value1';
const name2 = 'value2';

export {
  name1,
  name2
}


const name1 = 'value1';
const name2 = 'value2';

export {
  name1,
  name2
}


// ❌ Export list ≠ Object
export {
  name: 'name'
}

重命名导出

const name = 'value'

export {
  name as newName
}


import { newName } from 'some-path/file'

console.log(newName); // 'value'

// Original name is not accessible
console.log(name); // ❌ undefined


❌ 无法将内联导出与导出列表结合使用
export const name = 'value';

// You're already exporting name ☝️, don't export me again
export {
  name
}

重命名导入

const name1 = 'value1';
const name2 = 'value2';

export {
  name1,
  name2 as newName2
}

import {
  name1 as newName1,
  newName2
} from '...'

console.log(newName1); // 'value1'
console.log(newName2); // 'value2'

❌
name1; // undefined
name2; // undefined

全部导入

export const name = 'value';

export default 'defaultValue';

import * as anyName from 'some-path/file';

console.log(anyName.name); // 'value'
console.log(anyName.default); // 'defaultValue'

posted @ 2021-12-14 10:21  JackieDYH  阅读(31)  评论(0编辑  收藏  举报  来源