moment-hijri npm package work in sapper but not work in svelte-kit

39 Views Asked by At

I have a sapper project, that is completely ready. I am trying to convert sapper to svelte-kit latest version. Everything is working well. But moment-hijri npm package work savelte-kit.

I need to convert the normal date to the Hijri date. So I am using moment-hijri.

When I am trying to import moment from moment-hijri, it's give me error.

+page.svelte:

<script>
    import moment from "moment-hijri"
</script>

<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quaerat quisquam, nisi itaque obcaecati earum debitis nemo voluptate, quasi placeat iusto reiciendis assumenda consectetur. Tempora iste explicabo debitis reprehenderit dolorem praesentium, incidunt doloremque optio ut, quas quibusdam illo saepe blanditiis iure dolore voluptas impedit soluta culpa vitae voluptatem similique. Aperiam labore ut laborum cupiditate repudiandae corporis saepe eaque, placeat ea magnam architecto dicta! Quia labore quo dolores, repellendus minus odio praesentium veniam laudantium quas mollitia explicabo asperiores! Velit reprehenderit sint soluta tenetur alias, amet sit voluptate quas repellat animi autem neque inventore ut dolore vero quae asperiores facilis id eaque nobis.</p>

browser: [https://i.stack.imgur.com/2tJHb.png]

package.json

{
    "name": "my-app",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "dev": "vite dev",
        "build": "vite build",
        "preview": "vite preview"
    },
    "devDependencies": {
        "@sveltejs/adapter-auto": "next",
        "@sveltejs/kit": "next",
        "svelte": "^3.44.0",
        "vite": "^3.1.0-beta.1"
    },
    "type": "module",
    "dependencies": {
        "moment-hijri": "^2.1.2",
        "moment": "^2.29.1"
    }
}

How can I solve this problem? Is there any alternative npm package to change the normal date to the Hijri date?

1

There are 1 best solutions below

1
SSBakh On

moment-hijri most likely relies on data that's strictly client-side, so the trick is to only import it when your code is executing client-side. A way to do that is to use dynamic imports (relevant REPL) and mounting moment-hijri in onMount (which only ever runs on client-side) like so:

<script lang="ts">
    import { onMount } from 'svelte';

    onMount(async () => {
        const moment = (await import('moment-hijri')).default;
        // Rest of your code  
    })
</script>

There's also a way to tell SvelteKit to make your page strictly client-side (docs) by adding the following to your page options:

export const ssr = false;

However, this isn't really recommended in most cases, so use with care.