Laravel and Angular: Automated
Most tutorials that mention Laravel and Angular create two separate projects: one for the frontend and one for the backend; this leaves more to manage and adding an extra composer dependency to handle the CORS issue. The purpose of this article is to show how to integrate Angular into a new Laravel project using Laravel Mix. Each version of Angular has particular dependencies and because of how npm works it can be a hassle getting it all right. What will be shown is what gets deleted, changed, and created. This article was possible using these articles:
The script below takes care of the dependencies depending on which Angular version chosen. Versions 4–7 have been tested in Laravel versions 5.4–5.8. The script should only be run on a new Laravel project as files get deleted and rewritten.
All JS and Sass files and their processed output are deleted.
The purpose is to show Angular working without any other noise; unneeded JS dependencies are removed as well as Bootstrap and Sass.
The added packages are the bare essentials for Angular to work with Laravel Mix. Node package installs are found between lines 90 through 114 of the installation script.
Introduce TypeScript files and require a webpack custom config.
Modify ‘welcome.blade.php’ to load generated JS files and use a custom element for Angular application entry.
Create a custom config that links the ‘.ts’ extension to the ‘ts-loader’ module to process TypeScript files. The ‘plugins’ portion shown resolves to a certain folder (CORE_FOLDER) depending on the Angular version being installed (lines 222–232 of installation script).
Configure TypeScript and exclude folders from package managers.
The rest of the files are example TypeScript files using Angular components and modules. Where they reside depends on the Laravel version being used.
After all files have been properly managed and in their place, the installation can be tested by running:
npm run dev && php artisan serve
What has been described in this article were the modifications that need to happen in a new Laravel project to activate Angular as the project’s frontend. Because of simplicity of the TypeScript files used, one can see how they relate starting from ‘webpack.mix.js’ file. Following any tutorial on Angular development should prove successful from here on out. Otherwise for further development, add other packages using npm and add them to their respective places: vendor.ts, webpack.mix.js, etc.
Any TypeScript loader can be used and/or chained to other loaders. To increase the speed of the ‘ts-loader’ check out this article.