1. Solution by official documentation.
You may use Environment Variables https://laravel.com/docs/10.x/vite#environment-variables.
File .env
:
VITE_SOME_NAME=some value
File *.js
:
console.log(import.meta.env.VITE_SOME_NAME);
2. My working solution by logic and practice.
Passing any static and dynamic parameters to the JS script.
Any script - not only modules!
Assembly in one file.
File some_template-vue.blade.php
:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Laravel + VUE</title>
<script>
window.scrf_token = '{{ csrf_token() }}';
window.services = {
myService: {
constFromClass: '{{ App\Models\MyClass::CONST_NAME }}',
valueFromENV: '{{ env('SOME_PARAM', 'default value') }}',
urlFromRoute: '{{ route('some/url') }}',
urlFromRouteWithParam: '{{ route('some/url', ['param' => 'value']) }}'
}
}
</script>
<script src="{{ asset('js/app.js') }}" defer></script>
</head>
<body>
<nav>
<a href="{{ route('home') }}">Home</a>
</nav>
<div id="app">
</div>
</body>
</html>
As result you will get in output:
<script>
window.scrf_token = 'AbCdEfAbCdEfAbCdEfAbCdEfAbCdEfAbCdEfAbCdEf';
window.services = {
myService: {
constFromClass: 'some value from class',
valueFromENV: 'some value from ENV',
urlFromRoute: 'some URL from Route',
urlFromRouteWithParam: 'some URL from Route with param'
}
}
</script>
3. The idea of a Single Center of Responsibility through official practices.
File .env
:
VITE_SERVICE_URL="/get_service"
VITE_SERVICE_SOME_PARAM="some value"
File routes/web.php
:
Route::get(env('VITE_SERVICE_URL'), function () {
return '<script type="module"> console.log(import.meta.env.VITE_SERVICE_SOME_PARAM); </script>';
})->name('service');
File vite.config.js
:
import { defineConfig, loadEnv } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';
export default defineConfig(({ command, mode }) => {
// https://v4.vitejs.dev/config/#using-environment-variables-in-config
// Load env file based on `mode` in the current working directory.
// Set the third parameter to '' to load all env regardless of the `VITE_` prefix.
const env = loadEnv(mode, process.cwd(), '');
return {
define: {
__APP_ENV__: JSON.stringify(env.APP_ENV)
},
plugins: [
vue(),
laravel({
input: [
'resources/css/app.css',
'resources/js/app.js'
],
refresh: true,
}),
]
}
});
env()
helper. – Issy