Search code examples
javascriptvue.jslaravel-5.3

Script file inclusion in Laravel 5.3


How to include Script files like vue.js and app.js in Laravel 5.3 ? Is there any special way to include them ? I am including them like below.

<script src="http://127.0.0.1/addbook/node_modules/vue/dist/vue.js"></script>
<script src="js/app.js"></script>

Solution

  • As suggested by the other answer, you should read through Laravel elixir's doc first, with it we can simply write 5 lines of config and get a smooth front-end developing experience right away, which includes webpack for asset packaging, babel for transpiling ES6 code to ES5, and browser-sync for file watching and multi-device-synced browser auto refresh.

    On top of elixir, here's some practices I follow:

    • Include a generic app.js in your layouts/app.blade.php, which includes the codes you are absolutely sure you want in your every page. e.g. I put $('.datetime').datetimepicker(...) in it so the bootstrap datetime picker plugin inits the pickers for me wherever I put .datetime in html.
    • For those libraries you import with npm, import them in the specific view's js file so that webpack will compile your code with the library you inlcuded. You can either Vue = require('vue'); or import Vue from 'vue';, the latter is not supported by node.js or any browser but babel transpiles it for us.
    • Now you have a specific view, say, login.blade.php, which @extends the app.blade.php layout. Also we know that the best practice is to put the script files at the bottom of html's body so they don't block dom parsing and resource downloading. I personally use Laravel blade's syntax in login.blade.php like

    @push('childJS')
    <script src='/js/login.js'></script>
    @endpush
    

    and in app.blade.php:

        <script src='/js/app.js'></script>
        @stack('childJS')
    </body>
    

    so the 2 js files both appear at the bottom of body to get best performance and app.js always appear before login.js so that depencies between js files are resolved well.