我正在和Webpack一起做一个使用OpenLayers 6在ES6上的项目。
这是我的第一个真正的ES6项目,我想使它组织起来(有点模块化),但我正在努力使用进出口。
目前我的结构是:
- all.js
- map/
- index.js
- gpx.jsall.js文件是“入口点”。
all.js
import 'ol/ol.css';
import map from './map/index';
import { vector as GPXvector } from './map/gpx';
map.addLayer(GPXvector);地图/index.js
import { Map, View } from 'ol';
import { OSM } from 'ol/source';
import { Tile as TileLayer } from 'ol/layer';
const map = new Map({
layers: [
new TileLayer({
source: new OSM()
})
],
target: 'map',
view: new View({
center: [1037749, 5135381],
zoom: 10
})
});
export { map as default };map/gpx.js
import { Vector as VectorLayer } from 'ol/layer';
import { Circle as CircleStyle, Fill, Stroke, Style } from 'ol/style';
import { unByKey } from 'ol/Observable';
import VectorSource from 'ol/source/Vector';
import GPX from 'ol/format/GPX';
import map from './index.js'; // Is that good ??
const style = {
// [...] Some style here
};
const source = new VectorSource({
url: 'test.gpx',
format: new GPX()
});
var onChange = source.on('change', function() {
if (source.getState() == 'ready') {
map.getView().fit(source.getExtent()); // Access to "map" from "index.js" HERE
unByKey(onChange);
}
});
const vector = new VectorLayer({
source: source,
style: function (feature) {
return style[feature.getGeometry().getType()];
}
});
export { vector, source };我想从map文件(请参阅源代码中的注释)访问map/gpx.js实例(在map/index.js中初始化)。
但是我觉得我从map/index.js inside all.js导入了map/gpx.js,而map/gpx.js本身也从map/index.js导入了map。
在我看来,这就像是某种“循环”导入,在这里,处理导入顺序将变得一团糟,例如,当我在项目中获得更多文件时。
另外,如果你有任何建议让我正确地从ES6开始,这是很酷的!
编辑1
我换了别的东西,看看它是否允许更多的粒度。
all.js
import 'ol/ol.css';
import map from './ntrak/index';
import MyGPX from './ntrak/gpx';
const gpx = new MyGPX(map, 'test.gpx');map/gpx.js
import { Vector as VectorLayer } from 'ol/layer';
import { Circle as CircleStyle, Fill, Stroke, Style } from 'ol/style';
import { unByKey } from 'ol/Observable';
import VectorSource from 'ol/source/Vector';
import GPX from 'ol/format/GPX';
const style = {
// [...] Some style here
};
const _onSourceChange = function(map, source) {
if (source.getState() == 'ready') {
map.getView().fit(source.getExtent());
unByKey(_onSourceChange);
}
}
export default class {
constructor(map, url, fit = true) {
this.map = map;
this.url = url;
this.fit = fit;
this.loadGPX();
}
loadGPX() {
this.source = new VectorSource({
url: this.url,
format: new GPX()
});
if (this.fit) {
this.source.on('change', () => _onSourceChange(this.map, this.source));
}
this.vector = new VectorLayer({
source: this.source,
style: function(feature) {
return style[feature.getGeometry().getType()];
}
});
this.map.addLayer(this.vector);
}
};我认为这很酷,因为它允许在同一个地图实例上获得多个GPX向量。
但是,如果我想做更多与我的GPX源或向量交互的事情,我需要每次都传递实例,而不是直接导入GPX文件。
你认为如何?
发布于 2020-06-18 11:11:14
您可以使用CircularDependencyPlugin for webpack来跟踪这种循环依赖关系。
在您的示例中不存在循环依赖,import map from './index.js'; // Is that good ??是可以的。
您的es6代码对我来说很好,我看到一个var用法(var onChange = ...),您应该替换它。
https://stackoverflow.com/questions/62447003
复制相似问题