@ops-ai/svelte-feature-flags-toggly
v1.0.8
Published
Provides feature flags support for Svelte applications allowing you to enable and disable features easily. Can be used with or without Toggly.io.
Downloads
882
Readme
Lightweight package that provides feature flags support for Svelte applications allowing you to check feature status and enable/disable them easily.
Can be used WITH or WITHOUT Toggly.io.
What is a Feature Flag
A feature flag (or toggle) in software development provides an alternative to maintaining multiple feature branches in source code. A condition within the code enables or disables a feature during runtime.
In agile settings the feature flag is used in production, to switch on the feature on demand, for some or all the users. Thus, feature flags make it easier to release often. Advanced roll out strategies such as canary roll out and A/B testing are easier to handle.
Installation
Simply install using NPM to install this package.
$ npm i -s @ops-ai/svelte-feature-flags-togglyBasic Usage (with Toggly.io)
Initialize Toggly
Import and initialize Toggly in your main application file (typically App.svelte or main.ts):
import { createToggly } from '@ops-ai/svelte-feature-flags-toggly'
// Initialize with your App Key & Environment name from your Toggly application page
await createToggly({
appKey: 'your-app-key', // You can find this in app.toggly.io
environment: 'your-environment-name', // You can find this in app.toggly.io
})Using the Feature Component
Now you can start using the Feature component anywhere in your application:
<script>
import { Feature } from '@ops-ai/svelte-feature-flags-toggly'
</script>
<Feature featureKey="firstFeature">
<p>This feature can be turned on or off.</p>
</Feature>Feature Component Options
You can also check multiple feature keys and make use of the requirement (all/any) and negate (bool) options (requirement is set to "all" by default).
Show if all features are on
<Feature featureKeys={['firstFeature', 'secondFeature']}>
<p>ALL the provided feature keys are TRUE.</p>
</Feature>Show if any feature is on
<Feature featureKeys={['firstFeature', 'secondFeature']} requirement="any">
<p>AT LEAST ONE the provided feature keys is TRUE.</p>
</Feature>Show if features are off (negate)
<Feature featureKeys={['firstFeature', 'secondFeature']} negate={true}>
<p>NONE of the provided feature keys is TRUE.</p>
</Feature>Programmatic Feature Checks
You can also check features programmatically using the store functions:
<script>
import { isFeatureOn, isFeatureOff, evaluateFeatureGate } from '@ops-ai/svelte-feature-flags-toggly'
let featureEnabled = false
async function checkFeature() {
featureEnabled = await isFeatureOn('myFeature')
}
async function checkMultipleFeatures() {
const result = await evaluateFeatureGate(['feature1', 'feature2'], 'any', false)
console.log('Gate result:', result)
}
</script>
<button on:click={checkFeature}>Check Feature</button>
{#if featureEnabled}
<p>Feature is enabled!</p>
{/if}Using Reactive Stores
You can also use Svelte stores for reactive feature flag checks:
<script>
import { createFeatureStore } from '@ops-ai/svelte-feature-flags-toggly'
const myFeature = createFeatureStore('myFeature')
</script>
{#if $myFeature}
<p>Feature is enabled!</p>
{/if}Users and Rollouts
Using this package with Toggly allows you to define custom feature rollouts.
Custom rollouts offers the ability to show features only to certain groups of users based on various custom rules which you can define in Toggly.
In case you want to support custom feature rollouts, remember to provide an unique identity string for each user to make sure they get the same feature values on future visits:
await createToggly({
appKey: 'your-app-key', // You can find this in app.toggly.io
environment: 'your-environment-name', // You can find this in app.toggly.io
identity: 'unique-user-identifier', // Use this in case you want to support custom feature rollouts
})Basic Usage (without Toggly.io)
You can also use the Svelte SDK without connecting to Toggly.io by providing feature defaults:
Initialize with Defaults
import { createToggly } from '@ops-ai/svelte-feature-flags-toggly'
const featureDefaults = {
firstFeature: true,
secondFeature: false,
}
await createToggly({
featureDefaults: featureDefaults,
})Now you can use the Feature component the same way as with Toggly.io:
<Feature featureKey="firstFeature">
<p>This feature can be turned on or off.</p>
</Feature>Configuration Options
The createToggly function accepts the following options:
interface TogglyOptions {
baseURI?: string // Base URI for Toggly API (default: 'https://client.toggly.io')
appKey?: string // Your Toggly app key
environment?: string // Environment name (default: 'Production')
identity?: string // User identity for targeting
featureDefaults?: { [key: string]: boolean } // Default feature values
showFeatureDuringEvaluation?: boolean // Show feature while evaluating (default: false)
featureFlagsRefreshInterval?: number // Cache refresh interval in ms (default: 180000)
}TypeScript Support
The Svelte SDK includes full TypeScript support with type definitions:
import {
Feature,
createToggly,
isFeatureOn,
type TogglyOptions
} from '@ops-ai/svelte-feature-flags-toggly'
const config: TogglyOptions = {
appKey: 'your-app-key',
environment: 'Production',
identity: 'user-123'
}
await createToggly(config)SvelteKit Integration
For SvelteKit applications, initialize Toggly in your root layout or a client-side component:
<!-- src/routes/+layout.svelte -->
<script>
import { onMount } from 'svelte'
import { createToggly } from '@ops-ai/svelte-feature-flags-toggly'
onMount(async () => {
await createToggly({
appKey: 'your-app-key',
environment: 'Production',
identity: 'user-123' // Get from session/auth
})
})
</script>
<slot />Best Practices
- Initialize Once: Call
createToggly()once at the root of your app - Use Feature Component: Prefer using the Feature component for declarative feature flag checks
- Provide User Context: Include identity for accurate targeting and rollouts
- Set Feature Defaults: Provide defaults for offline scenarios or when not using Toggly.io
- TypeScript: Take advantage of TypeScript support for better type safety
- Reactive Stores: Use
createFeatureStore()for reactive feature flag checks in your components
API Reference
createToggly(config: TogglyOptions): Promise<void>
Initializes the Toggly service and loads feature flags.
<Feature>
Svelte component for conditional rendering based on feature flags.
Props:
featureKey?: string- Single feature key to checkfeatureKeys?: string[]- Multiple feature keys to checkrequirement?: 'all' | 'any'- Requirement type (default: 'all')negate?: boolean- Whether to negate the result (default: false)
isFeatureOn(featureKey: string): Promise<boolean>
Check if a feature is enabled.
isFeatureOff(featureKey: string): Promise<boolean>
Check if a feature is disabled.
evaluateFeatureGate(featureKeys: string[], requirement?: 'all' | 'any', negate?: boolean): Promise<boolean>
Evaluate a feature gate with multiple flags.
createFeatureStore(featureKey: string)
Create a reactive Svelte store for a specific feature flag.
Building the Library
If you're contributing to or building this library from source:
Prerequisites
- Node.js 18+ and npm
- All dependencies installed
Build Steps
Install dependencies:
npm installRun type checking:
npm run typecheckBuild the library:
npm run buildThis will:
- Compile TypeScript to JavaScript
- Bundle the library for both ESM and CommonJS formats
- Generate TypeScript declaration files
- Output files to the
dist/directory
Verify the build:
ls -la dist/You should see:
svelte-feature-flags-toggly.es.js- ES Module buildsvelte-feature-flags-toggly.cjs- CommonJS buildindex.js- Svelte component entry pointtypes/- TypeScript declaration files
Testing the Build Locally
You can test the built package locally using npm link:
Link the package:
npm linkIn your test project:
npm link @ops-ai/svelte-feature-flags-togglyOr test with the example app:
cd example npm install npm run dev
Publishing to npm
Prerequisites for Publishing
npm account: You need an npm account with access to the
@ops-aiorganizationAuthentication: You must be logged in to npm:
npm loginOrganization access: Ensure you have publish permissions for
@ops-aiscope
Publishing Steps
Update version number:
Update the version in
package.jsonfollowing Semantic Versioning:- Patch (1.0.0 → 1.0.1): Bug fixes
- Minor (1.0.0 → 1.1.0): New features (backward compatible)
- Major (1.0.0 → 2.0.0): Breaking changes
# Or use npm version command npm version patch # for 1.0.0 → 1.0.1 npm version minor # for 1.0.0 → 1.1.0 npm version major # for 1.0.0 → 2.0.0Update CHANGELOG.md:
Document the changes in
CHANGELOG.mdwith the new version number and date.Build the library:
npm run buildVerify the build output:
# Check that dist/ contains all necessary files ls -la dist/Dry run (optional but recommended):
npm publish --dry-runThis shows what would be published without actually publishing.
Publish to npm:
npm publish --access publicThe
--access publicflag is required for scoped packages (@ops-ai/...) to be published publicly.
Publishing Checklist
Before publishing, ensure:
- [ ] Version number is updated in
package.json - [ ]
CHANGELOG.mdis updated with new version - [ ] All tests pass (if applicable)
- [ ] Build completes successfully
- [ ]
dist/directory contains all expected files - [ ] TypeScript declarations are generated correctly
- [ ] README.md is up to date
- [ ] License file is present
- [ ]
.npmignoreexcludes source files and examples
Post-Publishing
After successful publication:
Create a git tag:
git tag v1.0.0 git push origin v1.0.0Verify on npm: Visit
https://www.npmjs.com/package/@ops-ai/svelte-feature-flags-togglyto confirm the new version is available.Update documentation: If this is a major release or includes breaking changes, update the main Toggly documentation.
Troubleshooting
Error: "You do not have permission to publish"
- Ensure you're logged in:
npm whoami - Verify you have access to the
@ops-aiorganization - Contact the organization admin for access
Error: "Package name already exists"
- Check if the version already exists on npm
- Increment the version number
Build fails:
- Ensure all dependencies are installed:
npm install - Check TypeScript errors:
npm run typecheck - Verify
vite.config.tsis correctly configured
Find out more about Toggly.io
Visit our official website or check out a video overview of our product.
