nystudio107 / craft-vite

Allows the use of the Vite.js next generation frontend tooling with Craft CMS
MIT License
52 stars 16 forks source link

[QUESTION] Using with Lalavel valet (https) #4

Closed watarutmnh closed 3 years ago

watarutmnh commented 3 years ago

Question

Hello, I got similar issue at the below ticket. https://github.com/nystudio107/craft-vite/issues/1#issue-876796855

[vite] connecting..., then [vite] server connection lost. polling for restart...

This endless repeats. It seems to be not working with my local environment using Lalavel valet with secure option (https). If I unsecure the site to make it to http, it works OK.

Any configuration on settings to make it work with https on valet?

Additional context

// vite.php
<?php

use craft\helpers\App;

return [
    'useDevServer' => App::env('ENVIRONMENT') === 'dev',
    'manifestPath' => '@webroot/dist/manifest.json',
    'devServerPublic' => 'http://localhost:3000/',
    'serverPublic' => App::env('PRIMARY_SITE_URL') . '/dist/',
    'errorEntry' => '',
    'cacheKeySuffix' => '',
    'devServerInternal' => '',
    'checkDevServer' => false,
];
// vite.config.js
import legacy from '@vitejs/plugin-legacy'
import ViteRestart from 'vite-plugin-restart';

export default ({ command }) => ({
  base: command === 'serve' ? '' : '/dist/',
  build: {
    manifest: true,
    outDir: './web/dist/',
    rollupOptions: {
      input: {
        app: '/src/app.js',
      }
    },
  },
  plugins: [
    legacy({
      targets: ['defaults', 'not IE 11']
    }),
    ViteRestart({
      reload: [
          './templates/**/*',
      ],
    }),
  ],
 server: {
    host: '0.0.0.0',
  },
});
khalwat commented 3 years ago

Can you try turning on https as suggested at the end of this section? https://nystudio107.com/blog/using-vite-js-next-generation-frontend-tooling-with-craft-cms#configuring-the-vite-plugin-for-craft-cms

You'd end up with something like:

// vite.php
<?php

use craft\helpers\App;

return [
    'useDevServer' => App::env('ENVIRONMENT') === 'dev',
    'manifestPath' => '@webroot/dist/manifest.json',
    'devServerPublic' => 'https://localhost:3000/',
    'serverPublic' => App::env('PRIMARY_SITE_URL') . '/dist/',
    'errorEntry' => '',
    'cacheKeySuffix' => '',
    'devServerInternal' => '',
    'checkDevServer' => false,
];

and the vite.config.js file:

// vite.config.js
import legacy from '@vitejs/plugin-legacy'
import ViteRestart from 'vite-plugin-restart';

export default ({ command }) => ({
  base: command === 'serve' ? '' : '/dist/',
  build: {
    manifest: true,
    outDir: './web/dist/',
    rollupOptions: {
      input: {
        app: '/src/app.js',
      }
    },
  },
  plugins: [
    legacy({
      targets: ['defaults', 'not IE 11']
    }),
    ViteRestart({
      reload: [
          './templates/**/*',
      ],
    }),
  ],
 server: {
    https: true,
    host: '0.0.0.0',
  },
});

But this isn't going to end up being an issue with the Vite plugin, but rather just how to get Vite to work with your local dev environment.

khalwat commented 3 years ago

btw feel free to keep posting on here if you have anything else I can assist with

watarutmnh commented 3 years ago

@khalwat Yes I tried as your article and above but it causes error in console.

GET https://localhost:3000/src/app.js net::ERR_CERT_AUTHORITY_INVALID

khalwat commented 3 years ago

Sounds like you need to authorize that self-signed certificate in your browser.

https://www.pico.net/kb/how-do-you-get-chrome-to-accept-a-self-signed-certificate

Sorry, I'm not too familiar with Valet.

khalwat commented 3 years ago

Ah, maybe this helps? https://dev.to/web2033/vite-enabling-https-on-localhost-2ckf

khalwat commented 3 years ago

This looks helpful actually... https://github.com/liuweiGL/vite-plugin-mkcert

watarutmnh commented 3 years ago

@khalwat Thanks for the info! I created a pair of certification using mkcert and now my assets are valid and it will load into my test site.

But still same issue remains what I got at first. server connection lost and restart It keeps refreshing browser..

my current vite.config.js

import legacy from '@vitejs/plugin-legacy';
import ViteRestart from 'vite-plugin-restart';
import * as fs from 'fs';

// https://vitejs.dev/config/
export default ({ command }) => ({
  base: command === 'serve' ? '' : '/dist/',
  build: {
    manifest: true,
    outDir: './web/dist/',
    rollupOptions: {
      input: {
        app: '/src/app.js',
      }
    },
  },
  plugins: [
    legacy({
      targets: ['defaults', 'not IE 11']
    }),
    ViteRestart({
      reload: [
          './templates/**/*',
      ],
    }),
  ],
  server: {
    https: {
      key: fs.readFileSync('localhost-key.pem'),
      cert: fs.readFileSync('localhost.pem'),
    },
    host: '0.0.0.0',
  },
});
watarutmnh commented 3 years ago

I just solved it by configuring server.hmr !

// vite.config.js
import legacy from '@vitejs/plugin-legacy';
import ViteRestart from 'vite-plugin-restart';
import * as fs from 'fs';

export default ({ command }) => ({
  base: command === 'serve' ? '' : '/dist/',
  build: {
    manifest: true,
    outDir: './web/dist/',
    rollupOptions: {
      input: {
        app: '/src/app.js',
      }
    },
  },
  plugins: [
    legacy({
      targets: ['defaults', 'not IE 11']
    }),
    ViteRestart({
      reload: [
          './templates/**/*',
      ],
    }),
  ],
  server: {
    https: {
      key: fs.readFileSync('localhost-key.pem'),
      cert: fs.readFileSync('localhost.pem'),
    },
    host: '0.0.0.0',
    hmr: {
      host: 'localhost',
    }
  },
});
khalwat commented 3 years ago

Oh right, if you're on Valet, you might want to remove:

    host: '0.0.0.0',

...which is only needed for Docker/VM setups. That might solve your problem without the hrm.host setting.

watarutmnh commented 3 years ago

Yes, the host: '0.0.0.0', is not necessary as I checked.

But it will have issue again without

hmr: {
      host: 'localhost',
    }

It might be Valet sepecific..

khalwat commented 3 years ago

Great to know, thanks!

terryupton commented 3 years ago

For anyone coming into this and struggling to follow the above. Here is a full step by step I took to get https working with Vite and Valet on OSX.

  1. Install mkcert via Brew brew install mkcert brew install nss https://github.com/FiloSottile/mkcert

  2. Then run mkcert -install to install globally

  3. Inside your project run mkcert localhost to install certificates (pem files) locally.

  4. Update the vite.config.js as follows:

    server: {
    https: {
      key: fs.readFileSync('localhost-key.pem'),
      cert: fs.readFileSync('localhost.pem'),
    },
    hmr: {
      host: 'localhost',
    },
    },
  5. run Vite and https should work 👍🏻

svondervoort commented 2 years ago

@terryupton could you explain your setup a bit more? I'm running into the same issue while trying out some stuff to get this error resolved:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/assets/js/app.js. (Reason: CORS request did not succeed). Status code: (null).

I used valet secure on my project folder to make it work with https but for some reason I still get a Connection is not secured error. I also changed the PRIMARY_SITE_URL in the .env to https:// ofcourse. and used your fix mentioning the mkcert.

vite.config.js

import * as fs from 'fs';
import ViteRestart from 'vite-plugin-restart';

export default ({command}) => ({
    base: command === 'serve' ? '' : '/dist/',
    publicDir: 'assets/public',
    build: {
        emptyOutDir: true,
        manifest: true,
        outDir: './web/dist/',
        rollupOptions: {
            input: {
                app: './assets/js/app.js',
            }
        },
    },
    plugins: [
        ViteRestart({
            reload: [
                './templates/**/*',
            ],
        }),
    ],
    server: {
        https: {
            key: fs.readFileSync('localhost-key.pem'),
            cert: fs.readFileSync('localhost.pem'),
        },
        hmr: {
            host: 'localhost',
        },
    }
});

vite.php

<?php

use craft\helpers\App;

return [
    'useDevServer' => App::env('ENVIRONMENT') === 'dev' || App::env('CRAFT_ENVIRONMENT') === 'dev',
    'manifestPath' => '@webroot/dist/manifest.json',
    'devServerPublic' => 'https://localhost:3000/',
    'serverPublic' => App::env('PRIMARY_SITE_URL') . '/dist/',
    'errorEntry' => '',
    'cacheKeySuffix' => '',
    'devServerInternal' => '',
    'checkDevServer' => false,
    'includeReactRefreshShim' => false,
    'includeModulePreloadShim' => true,
    'criticalPath' => '@webroot/dist/criticalcss',
    'criticalSuffix' => '_critical.min.css',
];

Also some package version info

"fs": "^0.0.1-security",
"vite": "^3.1.0",
 "vite-plugin-restart": "^0.2.0"

Hope you can help me out here :)

terryupton commented 2 years ago

Hey @well-made try this:

So I had to update my vite.php config to use port 5173 from 3000: 'devServerPublic' => 'https://localhost:5173/', and 'devServerInternal' => 'https://localhost:5173/',

In the latest version of vote they moved the default port from 3000 to 5137.

Or you can override this in the vite.config.js

  server: {
    port: 3000,
}

And then update the port inside devServerPublic and devServerInternal

svondervoort commented 2 years ago

Ah yes, I just noticed this weird port after trying a reboot. Settings port: 3000 worked. Thanks for the super fast reply!