JS中的 export 和 import 问题

现在Vuejs项目中做一个全局的配置文件

src/ 目录下新建了一个 config 目录
config 目录下新建了一个 index.js 文件

config/index.js 文件中这样写:

const KEY_NAME = 'key_name'
export default {
    KEY_NAME,
}

然后在其他的 .js 文件中这样写:

import * as config from '../config'

// 当使用config.[属性]的时候报错
config.KEY_NAME

错误内容是:TypeError: Cannot read property 'KEY_NAME' of undefined

请问这个该怎么导出导入呢?

阅读 4.7k
5 个回答

理解好export和export default区别:
export default仅有一个,你可以这么用,导出:export default KEY_NAME;导入import KEY_NAME from '../config'
export可以有多个,你可以这么用,如还有const other = 'other_name';导出:expor{KEY_NAME,other} ;导入import {KEY_NAME,other} from '../config'

把 * as 去掉
import config from '../config'

import * as config from '../config/index.js' 导入的时候可以忽略index.js 吗?

    • export default:是为了给用户提供方便,为模块指定默认输出,显然一个模块只能有一个默认输出
      ;这里的import命令可为该匿名函数指定任意的名字,同时在import的时候不用大括号:

      // export.js
      export default function () {
      console.log('foo');}
      
      // import.js
      import customName from './export';
      customName(); // 'foo'
    • 当不用default的时候,引入的时候要大括号;用default的时候不用大括号,名字可任意

       // 第一组
        export default function crc32() { // 输出 // ...}
        import crc32 from 'crc32'; // 输入
      
       // 第二组
        export function crc32() { // 输出// ...};
        import {crc32} from 'crc32'; // 输入
    撰写回答
    你尚未登录,登录后可以
    • 和开发者交流问题的细节
    • 关注并接收问题和回答的更新提醒
    • 参与内容的编辑和改进,让解决方法与时俱进
    推荐问题