@elise_daugherty
To integrate Vue.js in Symfony 5, you can follow these steps:
Step 1: Create a new Symfony project using the Symfony CLI or Composer:
1
|
composer create-project symfony/skeleton myproject |
Step 2: Install the Symfony/WebpackEncoreBundle to manage your assets:
1
|
composer require symfony/webpack-encore-bundle |
Step 3: Create a webpack.config.js
file in the root directory of your project:
1 2 3 4 5 6 7 8 9 10 11 12 |
// webpack.config.js var Encore = require('@symfony/webpack-encore'); Encore .setOutputPath('public/build/') .setPublicPath('/build') .addEntry('app', './assets/js/app.js') .enableVueLoader() .enableSassLoader() ; module.exports = Encore.getWebpackConfig(); |
Step 4: Create a app.js
file in the assets/js/
directory of your project:
1 2 3 4 5 6 7 8 |
// assets/js/app.js import Vue from 'vue'; import App from './App.vue'; new Vue({ el: '#app', render: h => h(App), }); |
Step 5: Create an App.vue
file in the assets/js/
directory of your project:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<!-- assets/js/App.vue --> <template> <div> <h1>Hello Vue.js!</h1> </div> </template> <script> export default { name: 'App', } </script> <style scoped> h1 { color: red; } </style> |
Step 6: Create a new template file in the templates/
directory of your project:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
{# templates/base.html.twig #} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>My Symfony App</title> </head> <body> {% block body %}{% endblock %} {% block javascripts %} <script src="{{ asset('build/app.js') }}"></script> {% endblock %} </body> </html> |
Step 7: Create a new controller to render the template:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// src/Controller/DefaultController.php namespace AppController; use SymfonyBundleFrameworkBundleControllerAbstractController; use SymfonyComponentHttpFoundationResponse; use SymfonyComponentRoutingAnnotationRoute; class DefaultController extends AbstractController { /** * @Route("/", name="default") */ public function index(): Response { return $this->render('default/index.html.twig'); } } |
Step 8: Update the routes in config/routes.yaml
:
1 2 3 4 |
# config/routes.yaml index: path: / controller: AppControllerDefaultController::index |
Step 9: Build the assets using Encore:
1 2 |
yarn install yarn encore dev |
Step 10: Start the Symfony development server:
1
|
symfony server:start |
You should now be able to access your Symfony application and see the "Hello Vue.js!" text rendered by Vue.js.