Publish your PHP enums to the frontend of our application so you can refer to them in your JavaScript code.
You can install the package via composer:
composer require intrfce/laravel-frontend-enums
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 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,
}
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",
}),
],
})
Please see CHANGELOG for more information what has changed recently.
Please see CONTRIBUTING for details.
If you discover any security related issues, please email dan@danmatthews.me instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.