[CesiumJS] 2. CesiumJS Quickstart 따라하기
서버 실행하고, Hello world 까지 띄웠다.
이번에는 Quickstart 를 따라서 Cesium의 viewer 를 띄어본다.
https://cesium.com/learn/cesiumjs-learn/cesiumjs-quickstart/
CesiumJS Quickstart
This tutorial demonstrates how to set up a basic Cesium app on a web page.
cesium.com
01.
위 링크에서 중간쯤 보면 Install with NPM 부분이 있다.
이미 설치를 완료했기 때문에 예제코드를 따라해 본다.
- index.html 의 <body>에 viewer 가 들어간 디비젼을 만들어준다.
<div id="cesiumContainer"></div>
- src > index.js 에 예제코드를 넣는다.
-- 우선 되는 것 확인하고 리팩토링 하는 걸로
Cesium.Ion.defaultAccessToken = ' 토큰토큰 '
토큰을 넣어줘야 한다. Cesium 에 로그인 하고 토큰을 받아서 넣어준다.
또는, 로그인 상태에서 예제를 보면 토큰이 이미 들어가 있다.
// The URL on your server where CesiumJS's static files are hosted.
window.CESIUM_BASE_URL = '/';
import * as Cesium from 'cesium';
import "cesium/Build/Cesium/Widgets/widgets.css";
// Your access token can be found at: https://ion.cesium.com/tokens.
// This is the default access token from your ion account
Cesium.Ion.defaultAccessToken = '토큰토큰';
// Initialize the Cesium Viewer in the HTML element with the "cesiumContainer" ID.
const viewer = new Cesium.Viewer('cesiumContainer', {
terrainProvider: Cesium.createWorldTerrain()
});
// Add Cesium OSM Buildings, a global 3D buildings layer.
const buildingTileset = viewer.scene.primitives.add(Cesium.createOsmBuildings());
// Fly the camera to San Francisco at the given longitude, latitude, and height.
viewer.camera.flyTo({
destination : Cesium.Cartesian3.fromDegrees(-122.4175, 37.655, 400),
orientation : {
heading : Cesium.Math.toRadians(0.0),
pitch : Cesium.Math.toRadians(-15.0),
}
});
02. html 과 js 를 작성했으니 서버를 실행한다.
> npm run dev
03. 온갖 에러가 발생한다.
-- Module not found: Error: Can't resolve 'url' in ~
-- 5 아래의 버전에는 polyfills 라는 모듈을 기본으로 제공했는데 지금은 아니라는 것 같다.
-- 사용하려면 resolve.fallback: {} 을 추가하라고 한다.
-- ERROR in ./node_modules/@cesium/engine/Source/Core/Resource.js 1843:15-28 를 검색해보면,
누가 이미 물어봤다.
https://community.cesium.com/t/compile-error-in-webpack-project/21601
Compile Error in webpack project
Hi, when I try to use the new packages “@cesium/engine” and “@cesium/widgets” in my Angular / Webpack project, I get a number of compiler warnings and errors like: Warning: /path/to/project/node_modules/@cesium/widgets/Source/VRButton/VRButtonViewM
community.cesium.com
-- 해결 방법으로 예제코드를 보여준다.
// The path to the CesiumJS source code
const cesiumSource = 'node_modules/cesium/Source';
const cesiumWorkers = '../Build/Cesium/Workers';
const CopyWebpackPlugin = require('copy-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
context: __dirname,
entry: {
app: './src/index.js'
},
output: {
filename: 'app.js',
path: path.resolve(__dirname, 'dist'),
sourcePrefix: ''
},
resolve: {
fallback: { "https": false, "zlib": false, "http": false, "url": false },
mainFiles: ['index', 'Cesium']
},
module: {
rules: [{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}, {
test: /\.(png|gif|jpg|jpeg|svg|xml|json)$/,
use: [ 'url-loader' ]
}]
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html'
}),
// Copy Cesium Assets, Widgets, and Workers to a static directory
new CopyWebpackPlugin({
patterns: [
{ from: path.join(cesiumSource, cesiumWorkers), to: 'Workers' },
{ from: path.join(cesiumSource, 'Assets'), to: 'Assets' },
{ from: path.join(cesiumSource, 'Widgets'), to: 'Widgets' },
{ from: path.join(cesiumSource, 'ThirdParty'), to: 'ThirdParty' }
]
}),
new webpack.DefinePlugin({
// Define relative base path in cesium for loading assets
CESIUM_BASE_URL: JSON.stringify('')
})
],
mode: 'development',
devtool: 'eval',
};
GitHub - CesiumGS/cesium-webpack-example: The minimal recommended setup for an application using Cesium with Webpack.
The minimal recommended setup for an application using Cesium with Webpack. - GitHub - CesiumGS/cesium-webpack-example: The minimal recommended setup for an application using Cesium with Webpack.
github.com
04. 일단 해결
resolve: {
fallback: { "https": false, "zlib": false, "http": false, "url": false },
mainFiles: ['index', 'Cesium']
},
이 내용을 추가해야 하는데,
우리는 false 할 게 아니라 사용할 것이다.
- webpack.config.js 파일에 추가해주자. ( node 설치부터 따라했다면, 아래 예제처럼 생겼을 것임 )
-- 모양이 좀 다르긴 하지만 아래와 같이 추가해준다.
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const WorkboxWebpackPlugin = require("workbox-webpack-plugin");
const isProduction = process.env.NODE_ENV == "production";
const stylesHandler = MiniCssExtractPlugin.loader;
const config = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "dist"),
},
devServer: {
open: true,
host: "localhost",
},
plugins: [
new HtmlWebpackPlugin({
template: "index.html",
}),
new MiniCssExtractPlugin(),
],
module: {
rules: [
{
test: /\.(js|jsx)$/i,
loader: "babel-loader",
},
{
test: /\.css$/i,
use: [stylesHandler, "css-loader", "postcss-loader"],
},
{
test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
type: "asset",
},
// Add your rules for custom modules here
// Learn more about loaders from https://webpack.js.org/loaders/
],
},
resolve: {
fallback: {
http: require.resolve("stream-http"),
assert: require.resolve("assert/"),
https: require.resolve("https-browserify"),
zlib: require.resolve("browserify-zlib"),
stream: require.resolve("stream-browserify"),
util: require.resolve("util/")
},
},
};
module.exports = () => {
if (isProduction) {
config.mode = "production";
config.plugins.push(new WorkboxWebpackPlugin.GenerateSW());
} else {
config.mode = "development";
}
return config;
};
05. 서버 실행 하면 아직 에러가 난다.
> npm run dev
package.json 파일을 아래처럼 수정한다.
필요한 여러 기능들을 다운받아야 한다고 한다.
터미널에서 다운받지 않아도 package.json 에서 추가하면 설치된다.
{
"devDependencies": {
"@babel/core": "^7.21.4",
"@babel/preset-env": "^7.21.4",
"@webpack-cli/generators": "^3.0.1",
"autoprefixer": "^10.4.14",
"babel-loader": "^9.1.2",
"css-loader": "^6.7.3",
"html-webpack-plugin": "^5.5.0",
"mini-css-extract-plugin": "^2.7.5",
"postcss": "^8.4.21",
"postcss-loader": "^7.2.4",
"prettier": "^2.8.7",
"style-loader": "^3.3.2",
"webpack": "^5.77.0",
"webpack-cli": "^5.0.1",
"webpack-dev-server": "^4.13.2",
"workbox-webpack-plugin": "^6.5.4"
},
"version": "1.0.0",
"description": "My webpack project",
"name": "my-webpack-project",
"scripts": {
"dev": "webpack-dev-server --mode development",
"build": "webpack --mode=production --node-env=production",
"build:dev": "webpack --mode=development",
"build:prod": "webpack --mode=production --node-env=production",
"watch": "webpack --watch",
"serve": "webpack serve"
},
"dependencies": {
"assert": "^2.0.0",
"browserify-zlib": "^0.2.0",
"cesium": "^1.104.0",
"https-browserify": "^1.0.0",
"stream-browserify": "^3.0.0",
"stream-http": "^3.2.0",
"url": "^0.11.0"
}
}
--
[webpack-cli] Error: Cannot find module 'mini-css-extract-plugin'
에러가 나면서 안된다.
이건 다음 글에서 해결해 본다.