Skip to content

Commit

Permalink
šŸ”„ new routing conventions
Browse files Browse the repository at this point in the history
  • Loading branch information
ShafSpecs committed Dec 19, 2024
1 parent e1d3781 commit 162f955
Show file tree
Hide file tree
Showing 104 changed files with 327 additions and 30 deletions.
9 changes: 9 additions & 0 deletions app/routes/docs.main.($slug).ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { LoaderFunctionArgs, redirect } from "@remix-run/node";

export const loader = ({ params }: LoaderFunctionArgs) => {
if (!params.slug) {
return redirect('/docs/latest');
}

return redirect(`/docs/latest/${params.slug}`);
};
9 changes: 9 additions & 0 deletions app/routes/docs.next.($slug).ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { LoaderFunctionArgs, redirect } from "@remix-run/node";

export const loader = ({ params }: LoaderFunctionArgs) => {
if (!params.slug) {
return redirect('/docs/dev');
}

return redirect(`/docs/dev/${params.slug}`);
};
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
37 changes: 37 additions & 0 deletions posts/dev/guides/env.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
---
title: Environment Variables
description: "Environment variables are a way to store app state and config data outside of your codebase. A guide to access them safely within Remix PWA"
alternateTitle: Environment Variables
toc: false
---

Remix PWA does not do anything to or with environment variables (mostly). In Remix PWA, the `process` object is not available (as service workers run in the client), and as such, accessing them directly is not possible.

However, Remix PWA isn't unaware of some of these variables. The main and only one being `NODE_ENV`, this variable is used to determine the state for which the service worker is bundled. As a `production` value will bundle the service worker with optimizations and less exposed stuffs (like `Logger`s), while a `development` value will bundle the service worker with full utilities to help you debug and develop.

You can also utilise `process.env.NODE_ENV` (in that order) within your service worker as Remix PWA would handle substituting the value for you at compilation time.

## Custom Variables

Remix PWA now allows for injecting custom variables via the `buildVariables` option in the Vite plugin configuration. This allows you to inject variables that are accessible within the service worker.

```ts
// vite.config.ts
export default defineConfig({
plugins: [
remixPWA({
buildVariables: {
'process.env.PUBLIC_KEY': 'my-public-key',
// can also be in another format
'myVery_PuBlick3y': 'my-public-key-2',
},
}),
],
});

// entry.worker.ts
console.log(process.env.PUBLIC_KEY); // my-public-key
console.log(process.env.myVery_PuBlick3y); // my-public-key-2

console.log(process.env); // logs all the variables as an object
```
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
52 changes: 52 additions & 0 deletions posts/dev/guides/web-manifest.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
---
title: Web Manifest
description: "Web Manifests are the heart of PWAs. Explore how to create a Web Manifest for your Remix PWA in this guide."
alternateTitle: Web Manifest
---

Web Manifests in Remix PWA are quite a trifle affair really. They are the heart of PWAs, and they are what makes your app installable on devices.

## What is a Web Manifest?

A Web Manifest is a JSON file that provides information about your web app. It tells the browser about your app's name, description, icon, and other details. It is what the browser uses to install your app on a device.

## Creating a Web Manifest

Creating aweb manifest can be done manually by creating a JSON file within the `public` directory, but why the hassle? Using Remix PWA cli, you can now generate a Web Manifest for your app with a single command.

To generate a Web Manifest for your Remix PWA app, run the following command:

```bash
npx remix-pwa manifest
```

This command will generate a basic web manifest resource route within your application at `routes/manifest[.webmanifest].ts`. It comes with typings automatically, to generate a JavaScript file instead of TypeScript, you can pass the `--js` flag to the command. Note that you can customise the file destination by passing the `--dest` flag. Check out the CLI guide for more.

## Customising the Web Manifest

The generated Web Manifest is quite basic and actually missing one important thing. Icons. As `remix-pwa` no longer ships with placeholder icons, you would need to source and register them in your web manifest loader, no worries though, the typings are there to help you out. As well as any further customisation you might want to do like `screenshots`, `share_target`, `orientation` etc.

## Registering the Web Manifest

Remix PWA also comes shipped with a `ManifestLink` component that is a shorthand for registering the Web Manifest in your app. You can use it like so:

```tsx {{filename:'root.tsx'}}
import { ManifestLink } from '@remix-pwa/manifest/manifest-link';

export default function App() {
return (
<html>
<head>
{/* Within your <head> tag */}
<ManifestLink />
<Links />
</head>
{/* Rest of the Remix application */}
</html>
);
}
```

> Make sure to use above Remix's `<Links />` component.
And that's it! You now have a Web Manifest for your Remix PWA app. šŸŽ‰
File renamed without changes.
File renamed without changes.
8 changes: 4 additions & 4 deletions posts/next/metadata.json ā†’ posts/dev/metadata.json
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@
"title": "Logger",
"alternateTitle": "Logger",
"description": "Logger is a logging utility build for better looking logs in the console.",
"stub": true,
"stub": false,
"section": "Utilities",
"slug": "logger"
},
Expand Down Expand Up @@ -300,7 +300,7 @@
"title": "vite.config.ts",
"alternateTitle": "vite.config.ts",
"description": "Remix PWA Vite plugin configurations",
"stub": true,
"stub": false,
"section": "Utilities",
"slug": "vite-config"
},
Expand Down Expand Up @@ -357,7 +357,7 @@
"title": "Environment Variables",
"alternateTitle": "Environment Variables",
"description": "Environment variables are a way to store app state and config data outside of your codebase. A guide to access them safely within Remix PWA",
"stub": true,
"stub": false,
"section": "Guides",
"slug": "env"
},
Expand Down Expand Up @@ -413,7 +413,7 @@
"title": "Web Manifest",
"alternateTitle": "Web Manifest",
"description": "Web Manifests are the heart of PWAs. Explore how to create a Web Manifest for your Remix PWA in this guide.",
"stub": true,
"stub": false,
"section": "Guides",
"slug": "web-manifest"
}
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
107 changes: 107 additions & 0 deletions posts/dev/utils/logger.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
---
title: Logger
description: "Logger is a logging utility build for better looking logs in the console."
alternateTitle: Logger
---

`logger` is a `Console` wrapper for Remix PWA that provides much better looking logs in the console.

It can be utilized like a normal logger:

```ts
import { logger } from '@remix-pwa/sw/logger';

// System startup logs
logger.info('šŸš€ Service Worker initialized successfully');
logger.debug('šŸ“Š Debug mode enabled - verbose logging active');

// Cache operations
logger.groupCollapsed('šŸ“¦ Cache Operations');
logger.log('āœ… Static assets cached successfully');
logger.log('šŸ“ Cache manifest updated - v2.1.0');
logger.groupEnd();

// Warning and error scenarios
logger.warn('āš ļø Network connection unstable - falling back to cache');
logger.error('āŒ Failed to fetch resource: /api/users [Status: 404]');

// Feature usage tracking
logger.info('šŸ‘¤ User authenticated successfully');
logger.debug('šŸ” Processing request parameters', {
route: '/dashboard',
method: 'GET',
timestamp: new Date().toISOString()
});

// Performance monitoring
logger.groupCollapsed('āš” Performance Metrics');
logger.log('šŸ“Š Time to First Byte: 120ms');
logger.log('ā±ļø Total Page Load: 1.2s');
logger.log('šŸ—ƒļø Cache Hit Ratio: 85%');
logger.groupEnd();
```

Or can be customised to provide better ownership

## `Logger`

The `Logger` class is a class that allows you to create your own logger, with your own styles, prefix and more.

### Instantiating `Logger`

To create a new `Logger` instance, you can easily do so via the `Logger` constructor:

```ts
import { Logger } from '@remix-pwa/sw/logger';

const logger = new Logger();
```

When no options are provided, the logger will use the default options.

#### Constructor Options

The `Logger` constructor accepts the following options:

- `prefix` - The prefix to be used in the logs. By default, this is `remix-pwa`.
- `logLevel` - The log level to be used. By default, this is `info`. Check out the [Log Levels](#log-levels) section for more information.
- `styles` - The styles to be used in the logs. By default, this is a pre-defined set of styles for each log level, you
can choose to extend or override these styles, individually or collectively.
- `isProductionEnv` - This would be auto-filled in by Remix PWA Vite bundler. **Don't** set this manually.

### `Logger` methods

The `Logger` class provides the following methods:

- `debug` - Logs a message with the `debug` log level.
- `info` - Logs a message with the `info` log level.
- `log` - Logs a message with the `log` log level.
- `warn` - Logs a message with the `warn` log level.
- `error` - Logs a message with the `error` log level.
- `groupCollapsed` - Logs a group of messages with the `log` log level.
- `groupEnd` - Ends a group of messages.

They perform the same as the `console` methods, but with better looking logs.

The other set fo not-so-conventional methods include:

- `setLogLevel` - Sets the log level for the logger.
- `setStyles` - Sets the styles for the logger. Can be used to override styles after instantiation.

## Log Levels

Log levels in Remix PWA `Logger` is a hierarchical structure, that allows you to filter out logs based on their severity.

The log levels are as follows:

- `debug` - The most verbose log level. Used for debugging purposes.
- `info` - The default log level. Used for general information.
- `log` - The default log level. Used for general information.
- `warn` - The warning log level. Used for non-critical issues.
- `error` - The error log level. Used for critical issues.

The log levels are hierarchical, meaning that a log level will log all logs of its level and below.

## `logger`

The `logger` export is a pre-instantiated `Logger` instance with the default options.
File renamed without changes.
File renamed without changes.
File renamed without changes.
107 changes: 107 additions & 0 deletions posts/dev/utils/vite-config.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
---
title: vite.config.ts
description: "Remix PWA Vite plugin configurations"
alternateTitle: vite.config.ts
---

Remix PWA uses Vite to compile and bundle your service workers. The process isn't linear, so you are able to customize the process by utilising the configuration options exposed by the `remixPWA` plugin.

## Remix PWA Vite Plugin Configuration

```ts {{filename:'vite.config.ts'}}
import { vitePlugin as remix } from "@remix-run/dev";
import { remixPWA } from "@remix-pwa/dev";
import { defineConfig } from "vite";

export default defineConfig({
plugins: [
remix(), // remix plugin is important!
remixPWA({
workerBuildDirectory: "out",
scope: '/pwa',
// rest of your configurations here
}),
],
});
```

> The configuration is an object of type `PWAViteOptions`.
### `injectSWRegister`

The `injectSWRegister` option of type: `boolean` is used to set wether to automatically register the service worker or not via plugin injection.

By default, the service worker is registered automatically. Alternatively, you can set this to `false` and manually register the service worker in your application via the [`PWAScripts`](/docs/next/pwa-scripts) component.

### `workerBuildDirectory`

The `workerBuildDirectory` option of type: `string` is used to set the directory where the service worker is built to. **Default**: `public` in dev and `build/client` in production. Note the lack of leading or trailing slashes.

### `buildVariables`

The `buildVariables` option of type: `Record<string, string>` is used to inject build variables into the service worker. Do note that these variables are visible in the browser, so don't inject private keys!

```ts
// vite.config.ts
export default defineConfig({
plugins: [
remixPWA({
buildVariables: {
'process.env.API_URL': 'https://api.example.com',
'myVar': 'myValue',
},
}),
],
});

// entry.worker.ts
console.log(process.env.API_URL); // https://api.example.com
console.log(myVar); // myValue
```

### `scope`

The scope of the service worker within your application, this is used by the internal registration injection to set the scope of the service worker. **Default**: `/`.

### `entryWorkerFile`

The user entry worker file, relative to the app directory. **Default**: `entry.worker.ts`.

> Be keeping note of the lack of slashes in many.
### `workerMinify`

The `workerMinify` option of type: `boolean` is used to set wether to minify the service worker post-bundling or not. **Default**: `false`.

### `workerName`

The `workerName` option of type: `string` is used to set the name of the service worker file, without extensions. No extensions should be passed in (`js`, `mjs`, etc.). **Default**: `entry.worker`.

### `ignoredSWRouteFiles`

An array of route string patterns to ignore when generating the service worker. Note, this would mean that any worker route modules in those routes would not be included in the final build output. **Default**: `[]`.

The `ignoredSWRouteFiles` now understands string globs/patterns. For example, to ignore all routes that start with `/admin`, you can use `['admin/**']`. This ignores routes starting with `admin` and all its children. You can also ignore routes based on middle patterns or routes ending with a pattern.

```ts
[
'admin/**', // ignore all routes starting with admin
'*/admin', // ignore all routes ending with admin
'**/admin/**', // ignore all routes containing admin within (not at the start or end)
'*', // ignore all routes
'admin/dashboard/**' // can also ignore based on two or more route segments
]
```

> One asterik (*) or two, it doesn't matter. Both work.
### `workerSourceMap`

The `workerSourceMap` option of type: `boolean` is used to set wether to generate source maps for the service worker or not. **Default**: `false`.

### `workerEntryPoint`

This is used to set the entry point of the service worker (also known as runtime in Remix PWA). **Default**: `@remix-pwa/worker-runtime`.

To create your own runtime, check out the runtime guide.

File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
6 changes: 0 additions & 6 deletions posts/next/guides/env.mdx

This file was deleted.

6 changes: 0 additions & 6 deletions posts/next/guides/web-manifest.mdx

This file was deleted.

6 changes: 0 additions & 6 deletions posts/next/utils/logger.mdx

This file was deleted.

6 changes: 0 additions & 6 deletions posts/next/utils/vite-config.mdx

This file was deleted.

Loading

0 comments on commit 162f955

Please sign in to comment.