svelte kit svelte-apexcharts window is not define 대응

임종필·2022년 4월 5일
0

svelte

목록 보기
1/7

svelte kit 에서는 클라이언트와 함께 서버측 렌더링을 지원합니다.
그래서 서버측에서 사용하지 않는 변수의 경우 build 시 에러가 나고 빌드가 안됩니다.
대표적인 변수가 window 입니다.

이경우 서버에서는 사용하지 않도록 조치를 취해야하는데,

svelte kit 의 경우 browser 라는 브라우저(클라이언트)의 유부를 알려누는 변수를 제공합니다.

그런데, 일반 변수나 함수가 실행되는 조건을 browser 로 조절하는 것은 쉬운데,

잘사용하지 않는 import 의 경우는 조금 해깔릴 수 있습니다.

그래서 예문을 첨부하여 보았습니다.


<script lang="ts"  >
import { browser } from '$app/env';
let chart:any   

onMount(
    async ()=>{
		if(browser){

			const charts = await import('svelte-apexcharts');
   			chart = charts.chart

		}
	}
)

let options:any
options = {
//차트 옵션 들...
}
</script>

 <div use:chart={options} />
 

PS. 이제는 svelte-apexcharts 를 사용하지 않아도 됩니다.

그냥 apexcharts 챠트를 이용할 수 있습니다.

  import ApexCharts from 'apexcharts';
  
  let options =  {
		chart: {
			type: 'line',
			zoom: {
				enabled: false
			},
			toolbar: {
				show: false
			}
		},
		series: [
			{
				name: '콜수',
				data: ['100','300','250']
			}
		],
		xaxis: {
			categories: ['2023-01-01','2023-01-02','2023-01-03'],
			labels: {
				show: false
			}
		},
		yaxis: {
			labels: {
				show: false
			}
		},
		stroke: {
			width: 2,
			curve: 'straight'
		},
		colors: ['#EB5757'],
		grid: {
			row: {
				colors: ['transparent', 'transparent'],
				opacity: 0.5
			}
		}
	};
    
  onMount(async () => {

		//const ApexCharts = (await import('apexcharts')).default;
		chart = new ApexCharts(container, options);
		chart.render();
	});
    
    const updateChart = () => {
		chart.updateOptions({
			xaxis: {
				categories: categories
			},
			series: [
				{
					name: '콜수',
					data: cdata
				}
			]
		});
	};

이렇게 일반적으로 import 해서 사용하면 됩니다.
여기서 중요한 점은 chart.updateOptions() 을 이용해서
차트의 값을 변경해준다는 점입니다.

profile
프롭테크 프로그래머

0개의 댓글