这就是我现在用方法,装置和出版物导入所有集合声明的方式:
import './news/collection.js';
import './news/methods.js';
if (Meteor.isServer) {
import './news/server/fixtures.js';
import './news/server/publications.js';
}
如果添加一些新集合,则必须再次编写:
import './comments/collection.js';
import './comments/methods.js';
if (Meteor.isServer) {
import './comments/server/fixtures.js';
import './comments/server/publications.js';
}
当你有大量的收藏品时,你必须一次又一次地写它。最后为了DRY你想写这样的东西:
let collections = ['news', 'comments', ... 'everything'];
for (let collection of collections) {
import `./${collection}/collection.js`;
import `./${collection}/methods.js`;
if (Meteor.isServer) {
import `./${collection}/server/fixtures.js`;
import `./${collection}/server/publications.js`;
}
}
现在发生The Unexpected token, expected {
错误。
我搜索了Meteor文档并且无法相信它:是否真的无法通过Meteor的动态路径导入某些东西?
答案 0 :(得分:3)
动态导入现在支持
我刚写了一篇关于如何做到这一点的文章,更重要的是,何时以及为何要这样做。
https://code.zeroasterisk.com/2017/05/meteor-1-5-bundle-optimization/
TL; DR:import('./my_component')
返回一个promise,当客户端拥有它时,它会解析。
之前:正常导入部分客户端捆绑
import PickDates from './PickDates';
之后:动态导入不再是客户端捆绑包的一部分
import Loader from 'react-loader';
// generic loading component to show while transfering section of code
const LoadingComponent = () => <span className="text-muted"><i className="fa fa-refresh" /></span>;
// new version of the component, now: loading --> rendered
const PickDates = Loader({
// this does the dynamic import, and returns a promise
loader: () => import('./PickDates'),
// this is our generic loading display (optional)
LoadingComponent,
// this is a delay before we decide to show our LoadingComponent (optional)
delay: 200,
});
答案 1 :(得分:1)
不支持动态导入。有许多人愿意这样做(包括我自己),但是在Meteor或其他地方它还没有,因为导入是ES6功能
答案 2 :(得分:1)
es6不支持动态导入(请参阅Importing modules using ES6 syntax and dynamic path)
但是,您可以使用CommonJS style requiring in Meteor
进行动态导入所以这样的事情应该有效:
let collections = ['news', 'comments', ... 'everything'];
for (let collection of collections) {
require(`./${collection}/collection.js`);
require(`./${collection}/methods.js`);
if (Meteor.isServer) {
require(`./${collection}/server/fixtures.js`);
require(`./${collection}/server/publications.js`);
}
}
答案 3 :(得分:1)
不支持动态导入。
然而,这看起来像一个反模式。手动加载模块的好处之一(与旧式meteor 'eager loading'相对)是因为它是显式的,很容易看出导入代码的来源。
通过不批量导入所有内容来最小化导入也很重要,这样您就可以在代码中看到依赖项。
即。如果我更改了这个模块的api,我可以搜索导入它的其他模块并更新
您的所有模块是否需要访问所有集合及其方法,固定装置和出版物?
大部分时间而不是使用Meteor.isServer
,您应该将此代码移动到/server
目录中。共享代码后,您可以将require
用作documented here
还有其他模式(即代码拆分)将从动态加载中受益,但我认为您最好尽量减少导入。