I've been looking to run Vite in development mode (watch JS and CSS files) for my Symfony 7 app which is served with a DDEV webserver.
// package.json
{
// ...
"scripts": {
"dev": "vite",
"build": "vite build"
},
}
Now, https://my.ddev.site is running fine and my assets are loaded great when using $ npm run build
. But using $ npm run dev
is not working for me. It seems my assets are loaded from the wrong host in development mode. They are loaded from:
<script type="module" src="http://127.0.0.1:3000/build/assets/app.js"></script>
Where I would want it to be:
<script type="module" src="/build/assets/app.js"></script>
Ideally I want my assets to be watched on development mode and the browser automatically updated.
I've tried loading a different host, proxy or other settings with in vite.config.js:
// vite.config.js
import { defineConfig } from "vite";
import symfonyPlugin from "vite-plugin-symfony";
import autoprefixer from "autoprefixer";
/* if you're using React */
// import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [
/* react(), // if you're using React */
symfonyPlugin(),
autoprefixer
],
server: {
// host: "https://my.ddev.site", // Error: getaddrinfo ENOTFOUND https://my.ddev.site
// origin: 'https://my.ddev.site', // Does update the asset path but ends up in a loop
proxy: {
// Using the proxy instance
'^/': {
target: 'https://my.ddev.site',
changeOrigin: true,
configure: (proxy, options) => {
// proxy will be an instance of 'http-proxy'
},
},
},
},
build: {
rollupOptions: {
input: {
app: "./assets/app.js"
},
}
},
});
but no luck so far. Can someone help me? I don't know if this helps but I'm working on MacOS
Thanks!
After reading https://ddev.com//blog/working-with-vite-in-ddev/ (thanks @rfay) I've added this to my DDEV config:
// .ddev/config.yaml
web_extra_exposed_ports:
- name: vite
container_port: 5173
http_port: 5172
https_port: 5173
Restarted DDEV
Added this to vite.config.js:
const port = 5173;
const origin = `${process.env.DDEV_PRIMARY_URL}:${port}`;
export default defineConfig({
// Adjust Vites dev server to work with DDEV
// https://vitejs.dev/config/server-options.html
server: {
// respond to all network requests:
host: '0.0.0.0',
port: port,
strictPort: true,
// Defines the origin of the generated asset URLs during development
origin: origin
}
});
Now the path is correct but I'm getting a CORS error:
Access to script at 'http://my.ddev.site:5173/build/@vite/client' from origin 'http://my.ddev.site' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Getting closer, still not working