Search code examples
webpackvue.jsvuejs2silex

How to configure Vue2 environment with Silex or other PHP framework


I'm trying to configure Vue2 to run with Silex framework application on a local development environment. I created Vue application using CLI tool. Changed the open URL in /build/dev-server.js from http://localhost/+port to http://localhost/ so npm run dev will open a Silex application. And added the following script url: http://localhost:8080/app.js in a php view.

Now when I run npm run dev, new tab in the browser is created with url http://localhost/. Vue application runs and I see my content (so webpack dev servers runs). The problem is it doesn't hot reload. When I check browser console I see that application constantly try to open http://localhost/__webpack_hmr.

So the question is, how to configure Vue development environment so it will work with Silex framework on a http://localhost:80 and webpack dev server with hot reload on http://localhost:8080 and still be able to run application by opening http://localhost/


Solution

  • I use Laravel, however, there isn't anything that's really specific to Laravel in my setup, so this should be the same for you with a few tweaks for wherever your files are stored:

    First you will want to make sure your script is being loaded from webpack-dev-server, so:

    <script src="http://localhost:8080/app.js"></script>
    

    I actually have this placed in a conditional based on an environment variable, so it only does this in my development system and loads the bundled js in production.

    Next you need to make sure your webpack dev config has app.js being served from webpack-dev-server. You can do that using publicPath which should point to the directory where your javascript files are being served from:

    output: {
        path: path.resolve(__dirname, '../../../public/js/'),
        publicPath: 'http://localhost:8080/js/',
        filename: 'app.js'
    },
    

    For my purposes I've also set the path to public/js because that's where my app.js file is relative to the webpack config, so just set that to wherever your js files are being bundled in silex.

    Now, you just want to configure dev server:

    devServer: {
        hot: true, // this enables hot reload
        headers: { "Access-Control-Allow-Origin": "*" },
        host: "localhost",
        port: 8080,
        contentBase: path.join(__dirname, "../../../public"), // points to Laravel public folder
    },
    

    I then add a npm script to package.json using npm-run-all - once again I'm pointing to the public folder for my php server:

    "scripts": {
      "serve": "php -S localhost:80 -t public,
      "hmr": "webpack-dev-server --env=webpack.dev",
      "dev": "npm-run-all --parallel hmr serve"
    }
    

    Now you should just be able to do :

    npm run dev

    to fire up both servers and then access your site from http://localhost:80