intrfce / laravel-frontend-enums
Stop using 'magic' strings/numbers in your frontend Javascript and use your actual application enums instead.
Installs: 4 994
Dependents: 0
Suggesters: 0
Security: 0
Stars: 17
Watchers: 2
Forks: 0
Open Issues: 0
Requires
- php: ^8.2.0
- laravel/framework: ^v11.0.0
- laravel/prompts: v0.*
Requires (Dev)
- orchestra/testbench: ^9.1
- pestphp/pest: ^2.23
- phpunit/phpunit: ^10.0
- tightenco/duster: ^2.5
README
Publish your PHP enums to the frontend of our application so you can refer to them in your JavaScript code.
Installation
You can install the package via composer:
composer require intrfce/laravel-frontend-enums
Usage
In your AppServiceProvider.php
, tell the package which Enums you want to publish:
use Intrfce\LaravelFrontendEnums\Facades\PublishEnums; PublishEnums::publish([ \App\Enums\MyEnum::class, \App\Enums\MyOtherEnum::class, ])->toDirectory(resource_path('js/Enums'));
Then run the publish command:
php artisan publish:enums-to-javascript
Your enums will be waiting at the path you specified with the extension .enum.js
:
MyEnum.enum.js
MyOtherEnum.enum.js
You can then import and use them in your JavaScript code:
import {MyEnum} from './Enums/MyEnum.enum.js'; import {MyOtherEnum} from './Enums/MyOtherEnum.enum.js'; console.log(MyEnum.FOO); // 0 console.log(MyOtherEnum.BAR); // 'bar'
Typescript Support
Typescript support is baked in: just add ->asTypescript()
to the list of enums in your AppServiceProvider.php
:
PublishEnums::publish([ \App\Enums\MyEnum::class, \App\Enums\MyOtherEnum::class, ]) ->asTypescript() ->toDirectory(resource_path('js/Enums'));
Files will be output as .ts
files and Typescript native enums:
export enum MyEnum { FOO = 0, BAR = 1, BAZ = 2, }
Automatically generate javascript files on change.
You can use the vite-plugin-watch
package from lepikhinb to automatically generate your javascript files when you make changes to your PHP enums:
npm install -D vite-plugin-watch
Then add the plugin to your vite.config.js
:
import { defineConfig } from "vite" import { watch } from "vite-plugin-watch" export default defineConfig({ plugins: [ watch({ pattern: "app/Enums/**/*.php", command: "php artisan publish:enums-to-javascript", }), ], })
Changelog
Please see CHANGELOG for more information what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security related issues, please email dan@danmatthews.me instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.