繁体   English   中英

如何使用Meteor通过动态路径导入

[英]How to import by dynamic path with Meteor

这就是我现在使用方法,固定装置和出版物导入所有集合声明的方式:

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通过动态路径导入某些内容吗?

在昨天发布的流星1.5之后, 现在支持动态导入

我刚刚写了一篇有关如何执行此操作的文章,更重要的是,有关何时何地执行此操作的文章。

https://code.zeroasterisk.com/2017/05/meteor-1-5-bundle-optimization/

TL; DR: import('./my_component')返回一个承诺,该承诺在客户端拥有时解析。

之前 :客户端捆绑包的正常导入部分

import PickDates from './PickDates';

after :动态导入不再是客户端捆绑包的一部分

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,
});

不支持动态导入。 有很多人想这样做(包括我自己),但是它在Meteor或其他地方尚不可用,因为导入是ES6功能

es6不支持动态导入(请参阅使用ES6语法和动态路径导入模块

但是,您可以使用Meteor中要求的CommonJS样式使用动态导入

所以这样的事情应该工作:

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`);
  }
}

不支持动态导入。

但是,这看起来像是反模式。 手动加载模块的好处(相对于旧式流星“急切加载” )的好处之一是,由于它是显式的,因此很容易看到导入代码的来源。

通过不批量导入所有内容来最小化导入也很重要,这样您就可以在代码中看到依赖关系。

也就是说,如果我更改了此模块的api,则可以搜索导入该模块的其他模块并更新

您所有的模块都需要访问所有集合及其方法,装置,出版物吗?

在大多数情况下,应该将此代码移至/server目录,而不是使用Meteor.isServer 共享代码后,您可以按此处所述使用require

还有其他模式(例如,代码拆分)会从动态加载中受益,但是我认为您最好考虑最小化导入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM