我目前通过webpack/babel在React应用程序中使用ES6。
我使用索引文件收集一个模块的所有组件并导出它们。不幸的是,它是这样的:
import Comp1_ from './Comp1.jsx';
import Comp2_ from './Comp2.jsx';
import Comp3_ from './Comp3.jsx';
export const Comp1 = Comp1_;
export const Comp2 = Comp2_;
export const Comp3 = Comp3_;
所以我可以很好地从其他地方导入它,像这样:
import { Comp1, Comp2, Comp3 } from './components';
显然这不是一个很好的解决方案,所以我在想,有没有其他的办法。我似乎不能直接导出导入的组件。
安装@babel/plugin-proposal-export-default-from
yarn添加-D @babel/plugin-proposal-export-default-from
在你的。babelrc里。json或任何配置文件类型
module.exports = {
//...
plugins: [
'@babel/plugin-proposal-export-default-from'
]
//...
}
现在你可以直接从文件路径导出:
export Foo from './components/Foo'
export Bar from './components/Bar'
祝你好运…
默认的出口
// Default export (recommended)
export {default} from './module'
// Default export with alias
export {default as d1} from './module'
所有的出口
// In >ES7, it could be
export * from './module'
// In >ES7, with alias
export * as d1 from './module'
函数名称导出
// export by function names
export { funcName1, funcName2, …} from './module'
// export by aliases
export { funcName1 as f1, funcName2 as f2, …} from './module'
解构对象导出
// export destructured object
export const { myVar, myFunction } = myObjectWithEverything
// export destructured object, with renaming
export const { v1: myVar, f1: myFunction } = myBigObject
与数组
// it works with array as well
export const [ funcName1, funcName2 ] = myBigArray
更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export
太晚了,但我想分享我解决它的方法。
有模型文件,有两个命名导出:
export { Schema, Model };
并有控制器文件,它有默认的导出:
export default Controller;
我在索引文件中以这样的方式暴露:
import { Schema, Model } from './model';
import Controller from './controller';
export { Schema, Model, Controller };
假设我想导入所有的:
import { Schema, Model, Controller } from '../../path/';
安装@babel/plugin-proposal-export-default-from
yarn添加-D @babel/plugin-proposal-export-default-from
在你的。babelrc里。json或任何配置文件类型
module.exports = {
//...
plugins: [
'@babel/plugin-proposal-export-default-from'
]
//...
}
现在你可以直接从文件路径导出:
export Foo from './components/Foo'
export Bar from './components/Bar'
祝你好运…
多年来,我一直在寻找如何在模块化JavaScript中同时导出命名导出和默认导出模块。经过大量的试验,我找到的解决方案非常简单和有效。
// index.js
export { default as Client } from "./client/Client.js";
export { default as Events } from "./utils/Events.js";
// Or export named exports
export { Client } from "./client/Client.js";
export { Events } from "./utils/Events.js";
export * as default from "./index.js";
这将允许以两种方式导入每个导出的模块:
// script.js
import { Client } from "index.js";
new Client();
import module from "index.js";
new module.Client();
// You could also do this if you prefer to do so:
const { Client } = module;
你可以随意摆弄它,让它适合你的需要,但它适合我。希望能有所帮助!