[英]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.