Javascript 如何制作动态ES6模块?
我想使用一个函数生成一个普通对象,该对象将从ES6模块导出(在节点中运行之前,使用Babel传输我的代码)Javascript 如何制作动态ES6模块?,javascript,module,ecmascript-6,babeljs,Javascript,Module,Ecmascript 6,Babeljs,我想使用一个函数生成一个普通对象,该对象将从ES6模块导出(在节点中运行之前,使用Babel传输我的代码) 下面的模块是我想做的 模块a 函数generatePlainObject(param1、param2、param3){ 返回{ newProp1:param1, newProp2:param2, newProp3:param3, }; } 导出generatePlainObject(1,2,3); …因此我可以在另一个模块中使用从'module_a'导入{newProp1,newPro
下面的模块是我想做的
模块a
函数generatePlainObject(param1、param2、param3){
返回{
newProp1:param1,
newProp2:param2,
newProp3:param3,
};
}
导出generatePlainObject(1,2,3);
…因此我可以在另一个模块中使用从'module_a'
导入{newProp1,newProp2,newProp3},并轻松访问属性
但这会抛出一个错误(意外标记
)
我尝试过使用扩展运算符(…
),使用对象.assign({},funcResults)
并在导出之前将其存储在常量中,但它们都会弹出错误
这可能吗?我是否误解了我可以制作什么样的物品来出口?我是否必须显式地键入普通对象并包含其属性
非常感谢您的帮助。根据规范,ES6模块必须能够进行静态分析。这意味着它们不能在运行时生成。这允许进行很多很好的优化,比如
如果你真的想这样做,你可以像这样使用CommonJS模块
module.exports = generatePlainObject(1, 2, 3);
import { newProp1, newProp2 } from './otherFile';
export default generatePlainObject(1, 2, 3);
import theWholeObj from './otherFile';
console.log(theWholeObj.newProp1);
像这样进口
module.exports = generatePlainObject(1, 2, 3);
import { newProp1, newProp2 } from './otherFile';
export default generatePlainObject(1, 2, 3);
import theWholeObj from './otherFile';
console.log(theWholeObj.newProp1);
另一个选项是导出为默认值,然后像这样导入整个对象
module.exports = generatePlainObject(1, 2, 3);
import { newProp1, newProp2 } from './otherFile';
export default generatePlainObject(1, 2, 3);
import theWholeObj from './otherFile';
console.log(theWholeObj.newProp1);
像这样进口
module.exports = generatePlainObject(1, 2, 3);
import { newProp1, newProp2 } from './otherFile';
export default generatePlainObject(1, 2, 3);
import theWholeObj from './otherFile';
console.log(theWholeObj.newProp1);
这两种方法都是不可静态分析的,因此不可能使树木摇晃。这意味着无论何时导入newProp1
,您都将导入newProp2
和newProp3
,无论您是否使用它们。您使用的是哪种JavaScript环境,它是否支持export
?ES6导入和导出是静态的,应该对它们进行静态分析。是否存在阻止您将此对象导出为默认导出的内容?您可以使用CJS模块进行动态导出。export{a,b,c}
不是对象表达式,它是要导出的名称列表,因此不能用任意表达式替换它。