OpenLayersとwebpackでビルド環境を構築したメモ。OpenLayersのバージョンはv6.1.1を利用。
GitHubでも公開しています。OpenLayersでのビルド環境を手軽に始めたい方ぜひご利用ください。
ディレクトリ構成
package.json
{
"name": "openlayers-starter",
"version": "6.1.1",
"description": "",
"main": "main.js",
"scripts": {
"build": "webpack",
"dev": "webpack-dev-server"
},
"keywords": [],
"author": "Yasunori Kirimoto",
"license": "ISC",
"devDependencies": {
"webpack": "^4.39.1",
"webpack-cli": "^3.3.6",
"webpack-dev-server": "^3.8.0"
},
"dependencies": {
"css-loader": "^1.0.1",
"file-loader": "^2.0.0",
"ol": "^6.1.1",
"style-loader": "^0.23.1",
"url-loader": "^1.1.2"
}
}
webpack.config.js
const webpack = require("webpack");
module.exports = {
mode: 'production',
entry: './_resouce/main.js',
output: {
path: __dirname + '/dist',
filename: 'app.js'
},
module: {
rules: [
{
test: /\.css$/,
loaders: ['style-loader', 'css-loader']
},
{
test: /\.(png|svg|jpg|gif)$/,
use: {
loader: 'url-loader',
options: {
name: './dist/img/icon/[name].[ext]'
}
}
}
]
},
devServer: {
contentBase: __dirname + '/dist',
publicPath: '/',
watchContentBase: true,
open: true
}
};
./_resouce
main.js
// CSS一式を読み込んでパッケージ
import "ol/ol.css";
import "./css/style.css";
// JS一式を読み込んでパッケージ
import './js/script.js';
./_resouce/css
style.css
html, body {
height: 100%;
padding: 0;
margin: 0;
}
#map {
z-index: 0;
height: 100%;
}
./_resouce/js
script.js
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import { fromLonLat } from 'ol/proj';
// MIERUNE MONO読み込み
const map = new Map ({
target: 'map',
layers: [
new TileLayer({
source: new XYZ({
url: 'https://tile.mierune.co.jp/mierune_mono/{z}/{x}/{y}.png',
attributions: 'Maptiles by <a href="http://mierune.co.jp" target="_blank">MIERUNE</a>, under CC BY. Data by <a href="http://osm.org/copyright" target="_blank">OpenStreetMap</a> contributors, under ODbL.',
attributionsCollapsible: false,
tileSize: [256, 256],
minZoom: 0,
maxZoom: 18
})
})
],
view: new View ({
center: fromLonLat([139.767, 35.681]),
zoom: 11
})
});
./dist
app.jsは自動でビルド
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OpenLayers Starter</title>
</head>
<body>
<div id="map"></div>
<script src="app.js"></script>
</body>
</html>
ファイルの準備ができたら対象ディレクトリでコマンド実行
パッケージインストール
npm install
ビルド
npm run build
開発
npm run dev
- 参考文献
OpenLayers
webpack