This was an answer to question at stack overflow that I couldn't post because it was closed before I could post it. https://stackoverflow.com/questions/57129851/how-to-use-js-frameworks-like-react-and-vue-and-es6-with-a-php-project
For a newcomer to front-end frameworks, I'd say probably the easiest way is to make small incremental changes replacing jQuery with Vue. I'd say Vue, and NOT React, because of the learning curve and changes since v. 16 that make it less friendly for un-compiled use. The React team seems to have dropped interest in supporting this kind of progressive approach by deprecating React.createClass
from the main package. You can still do it, but it's an extra package now.
You can add incremental chages by adding a new script tag like
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
into your PHP template which will load Vue in addition to jQuery until you have removed jQuery completely)
Then find a component you want to convert from jQuery to Vue.
You can now add a Vue template or component into your PHP layout/page and the JS script into the page, a page script file, or a component-specific script file.
Rinse and repeat for other components.
It's important to note though that this is not the best practice. Ideally you'd have a JS pipeline that generates a SPA(Single Page App) and deals with APIs from your PHP app. This is my preferred way of developing apps, but it's not a must. Doing it the way I described will add some pain when it comes to managing the app long-term, but it's likely not as bad as managing jQuery. As long as you organize your files well, using this method is a reasonable way to get started with adding some advanced functionality. If you know you're going to support modern browsers only, you can start defining templates in the script using template literals, which will help with code management, since you can keep your vue layouts in js files instead of in php templates. Later on, as you get more comfortable, you can start consolidating the project into a unified SPA that gets all the benefits of a compiled project.
Top comments (2)
Do you know of any example repos which have used this approach and have a good file structure?
I'm interested in potentially using this method in a legacy WP project as a precursor to going whole hog into SPA
I'm not aware of any, but it's tricky to find examples because such a change would be a transitory state. It is also frequently project specific.
You can look up more about the strangler pattern for updating legacy systems gradually. But I suspect that "theory" might not be that helpful in implementation of things like structuring your files, which are usually project-specific.