75
loading...
This website collects cookies to deliver better user experience
npm init svelte@next my-commercejs-storefront
cd my-commercejs-storefront
npm install
npm run dev -- --open
@chec/commerce.js
dependency.npm install @chec/commerce.js
src/lib
(you'll need to create it) add the file commerce.js
. Here you'll want to instantiate @chec/commerce.js
and add your PUBLIC API KEY.import CommerceSDK from '@chec/commerce.js';
export const client = new CommerceSDK('pk_184625ed86f36703d7d233bcf6d519a4f9398f20048ec');
.svelte
files (such as index.svelte
) is import the client
and call the usual Commerce.js methods to get your products, categories, etc.<script context="module">
import { client } from '$lib/commerce.js';
export async function load() {
const { data: categories } = await client.categories.list();
const { data: products } = await client.products.list();
return {
props: {
categories,
products
}
};
}
</script>
<script>
export let categories;
export let products;
</script>
props
will look even more so.categories
and products
we'll output the values to a list.<ul>
{#each categories as category}
<li>
<a rel="prefetch" href="/categories/{category.slug}">{category.name}</a>
</li>
{/each}
</ul>
<ul>
{#each products as product}
<li>
<a rel="prefetch" href="/product/{product.permalink}">{category.name}</a>
</li>
{/each}
</ul>
src/routes/categories/[slug].svelte
we'll add the following script module:<script context="module">
import { client } from '$lib/commerce.js';
export async function load({ page }) {
const { slug } = page?.params;
const category = await client.categories.retrieve(slug, {
type: 'slug'
});
const { data: products } = await client.products.list({ category_slug: [slug] });
return {
props: {
category,
products
}
};
}
</script>
<script>
export let category;
export let products;
</script>
slug
from the page params
.slug
to retrieve the category from Commerce.js:const category = await client.categories.retrieve(slug, {
type: 'slug'
});
const { data: products } = await client.products.list({ category_slug: [slug] });
category.name
and list out the products belonging to that category:<h1>{category.name}</h1>
<ul>
{#each products as product}
<li>
<a rel="prefetch" href="/products/{product.permalink}">{product.name}</a>
</li>
{/each}
</ul>
[permalink].svelte
since we're linking to the product permalink from the index and category pages.src/routes/products/[permalink].svelte
:<script context="module">
import { client } from '$lib/commerce.js';
export async function load({ page }) {
const { permalink } = page?.params;
const product = await client.products.retrieve(permalink, {
type: 'permalink'
});
return {
props: {
product
}
};
}
</script>
<script>
export let product;
</script>
<h1>{product.name}</h1>
<p>{product.price.formatted_with_symbol}</p>