我有一个文件,我在其中动态创建导出,例如:
import fs from 'fs';
import path from 'path';
import Sequelize from 'sequelize';
import config from '../config';
const sequelize = new Sequelize(config.database.name, config.database.user, config.database.password, {
dialect: 'postgres',
host: config.database.host,
logging: false,
define: {
underscored: true
}
});
const db = {
sequelize,
Sequelize
};
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== 'index.js');
})
.forEach(function(file) {
const model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if ('associate' in db[modelName]) {
db[modelName].associate(db);
}
});
export default db;
使用 babel 5 寄存器钩子(Hook),这种代码工作得很好。现在我正要升级到 babel 6,所以我使用了 require('babel-register')
。它工作正常,除了如果我想调用动态添加的属性,例如
import { sequelize } from './the_above_file';
那么变量sequelize
始终是未定义
。
但如果我打电话
import db from './the_above_file';
那么db.sequelize
就有一个值。
有办法解决这个问题还是我必须避免导出中的动态值;
最佳答案
import {sequelize } from './the_above_file';
应该永远不会工作,因为您没有使用该名称的 named 导出。您只有一个默认导出,它是一个对象。默认导出的属性与命名导出不同。
这被认为是 Babel 5 中的一个错误,Babel 6 修复了它。
你可以做到
import db from './the_above_file';
const { sequelize } = db;
提取默认导出的属性sequelize
。
关于javascript - 使用 babel-register 动态添加导出结果到 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39258665/