CoolFace
Datasetpublic

enigmare/v2-crawler

sourceHugging Faceupdated 28d agoView on Hugging Face
1likes889downloads
vite.jsonl615 linesDownload Raw Back to stackoverflow
1{"id":"stack-66147328","source":"stackoverflow","questionId":66147328,"title":"Is there a way to debug code in VsCode initiated with Vite?","tags":["vscode-debugger","vite"],"text":"Title: Is there a way to debug code in VsCode initiated with Vite?\nTags: vscode-debugger, vite\nSource: Stack Overflow\n\nQuestion:\nMy dev team configured a Node.js project with TypeScript to use Vite as dev server, using the npm script panel of VsCode.\nIs there a way to attach the debugger into this Vite server so we can debug the TSX code within the editor?\n\n========================================\n\nTop Answer:\nI write another answer, because the ones that are below were incomplete for me.\n\nFirst, paste in your launch.json file this code:\n\n```\n{\n \"version\":\"0.2.0\",\n \"configurations\":[\n {\n \"type\":\"chrome\",\n \"request\":\"launch\",\n \"name\":\"Launch Chrome against localhost\",\n \"url\":\"http://localhost:4000\",\n \"webRoot\":\"${workspaceFolder}/app\"\n }\n ]\n}\n```\n\nThen go to package.json, and add this to your dev command:\n\n```\n\"dev\": \"vite --port 4000\"\n```\n\nThen you run the command `npm run dev` and finally you can press F5 to start debugging.\n\n========================================\n\nCode:\n```json\n{\n    \"version\": \"0.2.0\",\n    \"configurations\": [\n        {\n            \"type\": \"chrome\",\n            \"request\": \"launch\",\n            \"name\": \"Launch Chrome against localhost\",\n            \"url\": \"http://localhost:4000\",\n            \"webRoot\": \"${workspaceFolder}/app\"\n        }\n    ]\n}\n```\n\n```text\nyarn dev\n```\n\n```text\nnpm run dev\n```\n\n```text\nvite\n```\n\n```json\n{\n  // Use IntelliSense to learn about possible attributes.\n  // Hover to view descriptions of existing attributes.\n  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"type\": \"firefox\",\n      \"request\": \"launch\",\n      \"name\": \"vuejs: firefox\",\n      \"url\": \"http://localhost:8080\",\n      \"webRoot\": \"${workspaceFolder}/src\",\n    }\n  ]\n}\n```\n\n```text\n\"webRoot\": \"${workspaceFolder}/src\",\n```\n\n```json\n{\n   \"version\":\"0.2.0\",\n   \"configurations\":[\n      {\n         \"type\":\"chrome\",\n         \"request\":\"launch\",\n         \"name\":\"Launch Chrome against localhost\",\n         \"url\":\"http://localhost:4000\",\n         \"webRoot\":\"${workspaceFolder}/app\"\n      }\n   ]\n}\n```\n\n```text\n\"dev\": \"vite --port 4000\"\n```\n\n```text\nnpm run dev\n```\n\n```js\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n    base: `/my-web-app/`,\n    plugins: [react()],\n});\n```\n\n```text\nbase\n```\n\n```text\nvite.config.js\n```\n\n```text\n{\n    \"version\": \"0.2.0\",\n    \"configurations\": [\n        {\n            \"type\": \"chrome\",\n            \"request\": \"launch\",\n            \"name\": \"Debug App\",\n            \"url\": \"http://localhost:5173\",\n            \"webRoot\": \"${workspaceFolder}/src\",\n            \"sourceMapPathOverrides\": {\n                \"webpack:///./src/*\": \"${webRoot}/*\"\n            },\n            \"runtimeArgs\": [\n                \"--remote-debugging-port=9222\"\n            ],\n            \"sourceMaps\": true\n        }\n    ]\n}\n```\n\n```text\n\"scripts\": {\n    \"dev\": \"vite --port 5173 --host\",\n```\n\n```json\n{\n  \"preLaunchTask\": \"task: dev\",\n  \"name\": \"chrome\",\n  \"type\": \"chrome\",\n  \"request\": \"launch\",\n  \"url\": \"http://localhost:5173\",\n  \"enableContentValidation\": false,\n  \"webRoot\": \"${workspaceFolder}/src\",\n  \"pathMapping\": {\"url\": \"/src/\", \"path\": \"${webRoot}/\"}\n}\n```\n\n```text\nsrc/router/index.js\n```\n\n```text\nsrc/store/index.js\n```\n\n```text\nfalse\n```\n\n```text\nlaunch.json\n```\n\n```text\n{\n    \"version\": \"0.2.0\",\n    \"configurations\": [\n      {\n        ...\n        url: \"http://localhost:8085\"\n        ...\n      }\n    ]\n}\n```\n\n```text\nnpm run dev\n```\n\n```js\n{\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"type\": \"chrome\",\n      \"request\": \"launch\",\n      \"name\": \"Debug Web\",\n      \"url\": \"http://localhost:5173\",\n      \"webRoot\": \"${workspaceFolder}/src\",\n      \"sourceMaps\": true,\n      \"runtimeArgs\": [\n        \"--remote-debugging-port=9222\"\n      ],\n      \"preLaunchTask\": \"vite: dev\"\n    }\n  ]\n}\n```\n\n```js\n{\n    \"version\": \"2.0.0\",\n    \"tasks\": [\n        {\n            \"label\": \"vite: dev\",\n            \"type\": \"npm\",\n            \"script\": \"dev\",\n            \n            // Vite dev runs indefinitely in the background\n            // Since it never exits, VS Code waits indefinitely for it to finish\n            // This is a workaround to tell VS Code to not wait before launching the next task\n            \"isBackground\": true,\n            \"problemMatcher\": [\n                {\n                    \"pattern\": [\n                        {\n                            \"regexp\": \".\",\n                            \"file\": 1,\n                            \"location\": 2,\n                            \"message\": 3\n                        }\n                    ],\n                    \"background\": {\n                        \"activeOnStart\": true,\n                        \"beginsPattern\": \".\",\n                        \"endsPattern\": \".\"\n                    }\n                }\n            ]\n        }\n    ]\n}\n```\n\n```js\n\"scripts\": {\n    \"dev\": \"vite --port 5173 --host\"\n}\n```\n\n========================================\n\nComments:\n- I have a similar problem with Snowpack. Cannot figure out how to configure VSCode. stackoverflow.com/questions/66221405/&hellip;\n- I'll note that the start vite port is 5173 (\"vite\" in leetspeak), so the default URL is localhost:5173\n- If that doesn't work, try changing the webRoot to be the directory where your 'Vue.app' file is located. Or if that doesn't work, put the directory where your index.html file is located. One of these two should work.\n- then how to debug a vite plugin source code? this is not works\n- Am I correct that launching a Chrome session in this way (which is outdated) makes the Chrome Vue Devtools unavailable?\n- Apparently it should be possible to have two debuggers attached at the same time, however I'm not sure if it works with this setup. developer.chrome.com/blog/new-in-devtools-63/#multi-client\n- What is the \"Debug tab\"? I have the debug console, but there's nothing where one can click in order to generate a file.\n- This does not work at all. The correct type is `chrome` and the correct `url` is the URL of your app e.g. `http:&#47;&#47;localhost:5174`. Then, with `\"webRoot\": \"${workspaceFolder}\"`, it debugs correctly.\n- This does not work perfectly for me. During debugging, VS Code is showing files like `localhost:4000\\main.js?t=123456789` to me which are not associated with the original JS file and which are also not syntax-highlighted.\n- What's the difference between `\"pwa-chrome\"` and `\"chrome\"` for the `type` property?\n- @EMcGill I might be wrong but they seem to have deprecate pwa-chrome and pwa-edge but kept it for whatever reasons.\n- @Marc Yes, this is correct, just confirmed. Use localhost:5173 (at least for me, and don't know why react vite defaults to that port number?) webRoot, remove the /app and it works right away after pressing F5\n- `Vue.app` file 😀\n- This answer seems Vue specific. I can't see anything in the original question mentioning the use of Vue\n- The thing that worked for me: 1. Point `webRoot` to `&#47;src` which contains my app logic. 2. `\"dev\": \"vite --port 5173\"` in `package.json` which matches port of `\"url\"` in *launch.json*\n- the /app did it for me. I don't need to 'npm run dev' though and actually had to remove it as it was configured as a prelaunchTask.\n- Aaaaaand it's broken again\n- This doesn't seem like it actually debugs the app, the live variables and values don't show up in VS Code's debugger\n- the OP asked about lunching the VSCode debugger tool, telling them they don't need it is not a good answer\n- This works on my side. Finally! I've been searching for a while. Thanks for putting it together!\n- Thank you! Got this also working on Firefox, with `\"type\": \"firefox\"` in `launch.json`. The only issue was it complaining about an old Node version used within the Vite package (??), which went away by removing the `--host` part from the script.","metadata":{"transformedAt":"2026-08-18T18:33:46.387Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":290,"estimatedTokens":1977}}2{"id":"stack-71703933","source":"stackoverflow","questionId":71703933,"title":"What is the difference between \"vite\" and \"vite preview\"?","tags":["javascript","vue.js","vite"],"text":"Title: What is the difference between \"vite\" and \"vite preview\"?\nTags: javascript, vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI created a project template using Vite.\n\nUnder package.json, I saw this:\n\n```\n\"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vue-tsc --noEmit && vite build\",\n \"preview\": \"vite preview\"\n},\n```\n\nWhat's the difference between `vite` and `vite preview`? When should one use `vite` instead of `vite preview`?\n\n========================================\n\nTop Answer:\nAccordig to vite documentation itself:\n\n### `vite` #\n\nStart Vite dev server in the current directory. Will enter the watch\nmode in development environment and run mode in CI automatically.\n\n...\n\n### `vite preview`#\n\nLocally preview production build.\n\nIn short words, `vite` is for running a dev server on your computer, while `vite preview` is for running an already built app as a preview of the production build.\n\n========================================\n\nCode:\n```text\n\"scripts\": {\n  \"dev\": \"vite\",\n  \"build\": \"vue-tsc --noEmit && vite build\",\n  \"preview\": \"vite preview\"\n},\n```\n\n```text\nvite\n```\n\n```text\nvite preview\n```\n\n```text\nvite\n```\n\n```text\nvite preview\n```\n\n```text\nnpm run dev\n```\n\n```text\nvite\n```\n\n```text\nnpm run build\n```\n\n```text\nvite build\n```\n\n```text\n./dist\n```\n\n```text\nnpm run preview\n```\n\n```text\nvite preview\n```\n\n```text\n./dist\n```\n\n```text\nbuild\n```\n\n```text\npreview\n```\n\n```text\nPreview\n```\n\n```text\nvite\n```\n\n```text\nvite preview\n```\n\n```text\nvite\n```\n\n```text\nvite preview\n```\n\n```plaintext\nvite/4.3.8\n\nUsage:\n  $ vite [root]\n\nCommands:\n  [root]           start dev server\n  build [root]     build for production\n  optimize [root]  pre-bundle dependencies\n  preview [root]   locally preview production build\n\nFor more info, run any command with the `--help` flag:\n  $ vite --help\n  $ vite build --help\n  $ vite optimize --help\n  $ vite preview --help\n\nOptions:\n  --host [host]           [string] specify hostname\n  --port <port>           [number] specify port\n  --https                 [boolean] use TLS + HTTP/2\n  --open [path]           [boolean | string] open browser on startup\n  --cors                  [boolean] enable CORS\n  --strictPort            [boolean] exit if specified port is already in use\n  --force                 [boolean] force the optimizer to ignore the cache and re-bundle\n  -c, --config <file>     [string] use specified config file\n  --base <path>           [string] public base path (default: /)\n  -l, --logLevel <level>  [string] info | warn | error | silent\n  --clearScreen           [boolean] allow/disable clear screen when logging\n  -d, --debug [feat]      [string | boolean] show debug logs\n  -f, --filter <filter>   [string] filter debug logs\n  -m, --mode <mode>       [string] set env mode\n  -h, --help              Display this message\n  -v, --version           Display version number\n```\n\n```plaintext\nvite/4.3.8\n\nUsage:\n  $ vite build [root]\n\nOptions:\n  --target <target>             [string] transpile target (default: 'modules')\n  --outDir <dir>                [string] output directory (default: dist)\n  --assetsDir <dir>             [string] directory under outDir to place assets in (default: assets)\n  --assetsInlineLimit <number>  [number] static asset base64 inline threshold in bytes (default: 4096)\n  --ssr [entry]                 [string] build specified entry for server-side rendering\n  --sourcemap [output]          [boolean | \"inline\" | \"hidden\"] output source maps for build (default: false)\n  --minify [minifier]           [boolean | \"terser\" | \"esbuild\"] enable/disable minification, or specify minifier to use (default: esbuild)\n  --manifest [name]             [boolean | string] emit build manifest json\n  --ssrManifest [name]          [boolean | string] emit ssr manifest json\n  --force                       [boolean] force the optimizer to ignore the cache and re-bundle (experimental)\n  --emptyOutDir                 [boolean] force empty outDir when it's outside of root\n  -w, --watch                   [boolean] rebuilds when modules have changed on disk\n  -c, --config <file>           [string] use specified config file\n  --base <path>                 [string] public base path (default: /)\n  -l, --logLevel <level>        [string] info | warn | error | silent\n  --clearScreen                 [boolean] allow/disable clear screen when logging\n  -d, --debug [feat]            [string | boolean] show debug logs\n  -f, --filter <filter>         [string] filter debug logs\n  -m, --mode <mode>             [string] set env mode\n  -h, --help                    Display this message\n```\n\n```plaintext\nvite/4.3.8\n\nUsage:\n  $ vite optimize [root]\n\nOptions:\n  --force                 [boolean] force the optimizer to ignore the cache and re-bundle\n  -c, --config <file>     [string] use specified config file\n  --base <path>           [string] public base path (default: /)\n  -l, --logLevel <level>  [string] info | warn | error | silent\n  --clearScreen           [boolean] allow/disable clear screen when logging\n  -d, --debug [feat]      [string | boolean] show debug logs\n  -f, --filter <filter>   [string] filter debug logs\n  -m, --mode <mode>       [string] set env mode\n  -h, --help              Display this message\n```\n\n```plaintext\nvite/4.3.8\n\nUsage:\n  $ vite preview [root]\n\nOptions:\n  --host [host]           [string] specify hostname\n  --port <port>           [number] specify port\n  --strictPort            [boolean] exit if specified port is already in use\n  --https                 [boolean] use TLS + HTTP/2\n  --open [path]           [boolean | string] open browser on startup\n  --outDir <dir>          [string] output directory (default: dist)\n  -c, --config <file>     [string] use specified config file\n  --base <path>           [string] public base path (default: /)\n  -l, --logLevel <level>  [string] info | warn | error | silent\n  --clearScreen           [boolean] allow/disable clear screen when logging\n  -d, --debug [feat]      [string | boolean] show debug logs\n  -f, --filter <filter>   [string] filter debug logs\n  -m, --mode <mode>       [string] set env mode\n  -h, --help              Display this message\n```\n\n```text\nvite --help\n```\n\n```text\nvite --help\n```\n\n```text\nvite build --help\n```\n\n```text\nvite optimize --help\n```\n\n```text\nvite preview --help\n```\n\n========================================\n\nComments:\n- `vite preview` does not build for you\n- Got it. So you should run `npm run build` before `npm run preview`\n- @MichaelS yes. Otherwise you will preview the last build","metadata":{"transformedAt":"2026-08-18T18:33:46.387Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":257,"estimatedTokens":1620}}3{"id":"stack-66389043","source":"stackoverflow","questionId":66389043,"title":"How can I use Vite env variables in vite.config.js?","tags":["javascript","vuejs3","vite"],"text":"Title: How can I use Vite env variables in vite.config.js?\nTags: javascript, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nWith the following `.env` in my Vite project:\n\n```\n# To prevent accidentally leaking env variables to the client, only\n# variables prefixed with VITE_ are exposed to your Vite-processed code\n\nVITE_NAME=Wheatgrass\nVITE_PORT=8080\n```\n\nHow can I use `VITE_PORT` in my `vite.config.js`?\n\n========================================\n\nTop Answer:\nI had exactly the same issue and found a solution.\n\n```\nimport { defineConfig, loadEnv } from 'vite';\n\nexport default defineConfig(({ mode }) => {\n const env = loadEnv(mode, process.cwd());\n\n const API_URL = `${env.VITE_API_URL ?? 'http://localhost:3000'}`;\n const PORT = `${env.VITE_PORT ?? '3000'}`;\n\n return {\n server: {\n proxy: {\n '/api': API_URL,\n },\n port: PORT,\n },\n build: {\n outDir: 'public',\n },\n plugins: [react()],\n };\n});\n```\n\nIn .env\n\n```\nVITE_API_URL='https://yourapiurl.com'\nVITE_PORT=3000\n```\n\n========================================\n\nCode:\n```sh\n# To prevent accidentally leaking env variables to the client, only\n# variables prefixed with VITE_ are exposed to your Vite-processed code\n\nVITE_NAME=Wheatgrass\nVITE_PORT=8080\n```\n\n```text\n.env\n```\n\n```text\nVITE_PORT\n```\n\n```text\nvite.config.js\n```\n\n```js\nimport { defineConfig, loadEnv } from 'vite';\nimport vue from '@vitejs/plugin-vue';\n\n\nexport default ({ mode }) => {\n    process.env = {...process.env, ...loadEnv(mode, process.cwd())};\n\n    // import.meta.env.VITE_NAME available here with: process.env.VITE_NAME\n    // import.meta.env.VITE_PORT available here with: process.env.VITE_PORT\n\n    return defineConfig({\n        plugins: [vue()],\n\n        server: {\n            port: parseInt(process.env.VITE_PORT),\n        },\n    });\n}\n```\n\n```text\napp level\n```\n\n```text\nNode level\n```\n\n```text\nimport { defineConfig, loadEnv } from 'vite';\nimport vue from '@vitejs/plugin-vue';\n\nexport default defineConfig(({ mode }) => {\n\nconst env = loadEnv(\n  'mock', \n  process.cwd(),\n  '' \n)\n  const processEnvValues = {\n    'process.env': Object.entries(env).reduce(\n      (prev, [key, val]) => {\n        return {\n          ...prev,\n          [key]: val,\n        }\n      },\n      {},\n    )\n  }\n\n  return {\n    plugins: [vue()],\n    define: processEnvValues\n  }\n}\n```\n\n```text\nimport { defineConfig, loadEnv } from 'vite';\nimport vue from '@vitejs/plugin-vue';\n\n\nexport default ({ mode }) => {\n    process.env = Object.assign(process.env, loadEnv(mode, process.cwd(), ''));\n\n    return defineConfig({\n        plugins: [vue()],\n    });\n}\n```\n\n```text\nvite.config.ts\n```\n\n```text\nvite.config.js\n```\n\n```text\nimport { defineConfig, loadEnv } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\n// export default defineConfig({\n//   plugins: [react()],\n// })\n\nexport default defineConfig(({ mode }) => {\n  const env = loadEnv(\"mock\", process.cwd(), \"\");\n  const processEnvValues = {\n    \"process.env\": Object.entries(env).reduce((prev, [key, val]) => {\n      console.log(key, val);\n      return {\n        ...prev,\n        [key]: val,\n      };\n    }, {}),\n  };\n\n  return {\n    plugins: [react()],\n    define: processEnvValues,\n  };\n});\n```\n\n```text\nREACT_APP_MAILCHIMP_URL=\"https://gmail.xxxx.com/subscribe/post\"\nREACT_APP_MAILCHIMP_U=\"xxxxxxxxxxxxxxxxx\"\nREACT_APP_MAILCHIMP_ID=\"YYYYYYYYYYYY\"\n```\n\n```text\nexport const Test = () => {\n  console.log(import.meta.env.REACT_APP_MAILCHIMP_URL); \n  console.log(import.meta.env.REACT_APP_MAILCHIMP_U); \n  console.log(import.meta.env.REACT_APP_MAILCHIMP_ID); \n\n  const a_var = `${process.env.REACT_APP_MAILCHIMP_URL}`;\n  console.log(a_var);\n\n  return (\n\n    <div>\n      <small> You are running this application in mode.: \n      <b>{process.env.NODE_ENV}</b>\n      </small>\n\n      <div>\n        <small> REACT_APP_NOT_SECRET_CODE:  \n        <b> {process.env.REACT_APP_MAILCHIMP_URL}</b>\n        </small>\n      </div>\n    </div>\n  );\n};\n```\n\n```text\nimport \"./App.css\";\n\nimport { Test } from \"./components/Test\";\n\nfunction App() {\n  return (\n    <div className=\"App\">\n      <Test />\n    </div>\n  );\n}\n\nexport default App;\n```\n\n```text\nimport dotenv from 'dotenv'\n\ndotenv.config()\n\nprocess.env.YOUR_ENV_VAR\n```\n\n```text\nvite.config.js\n```\n\n```js\nimport { defineConfig, loadEnv } from 'vite';\n\nconst env = loadEnv(\n    'all',\n    process.cwd()\n);\n\nlet port = env.VITE_PORT;\n```\n\n```js\nfunction loadEnv(\n  mode: string,\n  envDir: string,\n  prefixes: string | string[] = 'VITE_',\n): Record<string, string>\n```\n\n```text\nloadEnv\n```\n\n```text\nVITE_\n```\n\n```text\nprefixes\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { resolve } from 'path';\nimport dotenv from 'dotenv';\nimport fs from 'fs';\n\nexport default defineConfig(() => {\n  // Decide which .env file to load based on the mode\n\n  const envFile = process.env.NODE_ENV === 'production' ? 'env.yourapp-prod' :'.env.yourapp-dev';\n  // Load the environment variables using dotenv and assign to process.env\n  const envConfig = dotenv.parse(fs.readFileSync(envFile));\n  process.env = { ...process.env, ...envConfig };\n\n  // Convert environment variables for Vite's define option\n  const envVarsForDefine = Object.fromEntries(\n    Object.entries(process.env).map(([key, value]) => [`process.env.${key}`, JSON.stringify(value)])\n  );\n\n\n  return {\n    plugins: [sveltekit()],\n    test: {\n      include: ['src/**/*.{test,spec}.{js,ts}']\n    },\n    resolve: {\n      alias: {\n        $src: resolve('./src'),\n        $stores: resolve('./src/lib/stores'),\n        $assets: resolve('./src/assets'),\n        $icon: resolve('./node_modules/svelte-bootstrap-icons/lib')\n      }\n    },\n    define: envVarsForDefine\n  };\n});\n```\n\n```text\nNODE_ENV=staging firebase deploy\n```\n\n```text\nNODE_ENV=production firebase deploy\n```\n\n```text\nimport { defineConfig, loadEnv } from 'vite';\n\nexport default defineConfig(({ mode }) => {\n  const env = loadEnv(mode, process.cwd());\n\n  const API_URL = `${env.VITE_API_URL ?? 'http://localhost:3000'}`;\n  const PORT = `${env.VITE_PORT ?? '3000'}`;\n\n  return {\n    server: {\n      proxy: {\n        '/api': API_URL,\n      },\n      port: PORT,\n    },\n    build: {\n      outDir: 'public',\n    },\n    plugins: [react()],\n  };\n});\n```\n\n```text\nVITE_API_URL='https://yourapiurl.com'\nVITE_PORT=3000\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport dotenv from 'dotenv';\nimport react from '@vitejs/plugin-react'\n\ndotenv.config();\n\nconsole.log(\"hello\", process.env.VITE_HOMEPAGE_URL) //when you run the frontend using yarn dev you will be able to see this on you cmd to know this works! :D\n\nexport default defineConfig({\n  base: process.env.VITE_HOMEPAGE_URL,\n  plugins: [react()],\n})\n```\n\n```text\nVITE_HOMEPAGE_URL=https://abc.something.com/home/\n```\n\n```text\nmodule.exports = {\n  env: { browser: true, es2020: true, node: true },\n  //...other settings\n}\n```\n\n```text\nprocess.env = { ...process.env, ...loadEnv(mode, process.cwd()) };\n```\n\n```text\ndotenv\n```\n\n```text\nyarn add dotenv\n```\n\n```text\nvite.config.js\n```\n\n```text\n.env\n```\n\n```text\nprocess is not defined\n```\n\n```text\n.eslintrc.cjs\n```\n\n```text\nnode: true\n```\n\n```text\nenv\n```\n\n```text\nexport default defineConfig(({ mode }) => {\n  const env = loadEnv(mode, \"../\", \"\");\n  return {\n    plugins: [react()],\n    envDir: \"../\",\n    server: {\n      port: env.VITE_CLIENT_PORT),\n    },\n  };\n});\n```\n\n========================================\n\nComments:\n- You need to use VITE_APP_Name to define the variables in the ENV file.\n- Here's the documentation for that: vitejs.dev/config/#using-environment-variables-in-config\n- If the above does not work for you (e.g. you want to import a variable that is not prefixed with `VITE_`. Try this: `process.env = { ...process.env, ...loadEnv(mode, process.cwd(), '') };` The prefx (3rd argument) does make the difference here.\n- Regarding the `server.port` assignment, my `vite.config.ts` gives me the error \"Type 'string' is not assignable to type 'number'\". How do I fix that?\n- @BrentArias Environment variables are always strings, but the type definitions for Vite expect a number there. Use parseInt.\n- CAUTION: Better use `Object.assign(process.env, loadEnv(mode, process.cwd()))` instead of destructuring `process.env`! When I added the env variables like that, the keys lost their case-insensitivity somehow (running on Windows). To be specific, running `npx vite` failed for me because `process.env.SYSTEMROOT` is undefined, while `process.env.SystemRoot` IS defined. This does not happen anymore when I use `Object.assign` instead.\n- CAUTION: setting vars in process.env seems to prevent the build process from setting them from their respective .env file (like .env.production) when the Vite build process runs after the fact. If there's name collision, the variable is not replaced, i.e: API_URL was being set to localhost when building for prod. My personal solution was to used a different variable to hold the loaded env, like `tmp_env` instead of `process.env`\n- @Matt - Thanks for the solutions. It works like a champ\n- Where can I place a console.log in order to see the values behind 'define'?\n- It should work after `processEnvVales` , if it not possible , I will check once\n- A console.log after does not print out any logs on the terminal nor in the webdeveloper console.\n- @ShadowGames you need to add it before the return statement.\n- Was going to write the same thing by myself, but here you are my friend, thank you.\n- It worked for me! great! but... vite filters out most variables not starting with `VITE_APP_` for security. While dotenv just loads all the environment vars. Does this have any security implications. Is the full environment available for the rest of the build process? Edit: Just answering myself: `process.env` already has all the environment vars. Vite filters from that. So this works perfectly. Thanks.\n- This one worked for me. Thanks 🙂","metadata":{"transformedAt":"2026-08-18T18:33:46.387Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":40,"totalLines":445,"estimatedTokens":2473}}4{"id":"stack-69417788","source":"stackoverflow","questionId":69417788,"title":"Vite https on localhost","tags":["ssl","https","vite"],"text":"Title: Vite https on localhost\nTags: ssl, https, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get https working on my localhost environment for Vite. Chrome shows an invalid certificate error.\n\nI've set up my vite.config.js file like this:\n\n```\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport fs from 'fs';\n\nexport default defineConfig({\n resolve: { alias: { '@': '/src' } },\n plugins: [vue()],\n https: {\n key: fs.readFileSync('RootCA-key.pem'),\n cert: fs.readFileSync('RootCA.pem')\n }\n})\n```\n\nand when I run `npm run dev -- --https` it works as expected, I don't get any issues from Vite. However, Chrome shows an invalid certificate.\n\nI used openssl to create the cert files, which gave me .crt, .pem, and .key files. None of them are binary, so I renamed the .key file as RootCA-key.pem. I've tried using the RootCA.pem file as the cert, as well as renaming the RootCA.crt file to RootCA-cert.pem and using that as the cert.\n\nAs a temporary work-around, I've enabled insecure localhost in Chrome (chrome://flags/#allow-insecure-localhost), which at least gets rid of the warning.\n\n========================================\n\nTop Answer:\nEasiest way is to use the vite-plugin-mkcert package.\n\n```\nnpm i vite-plugin-mkcert -D\n```\n\nvite.config.js\n\n```\nimport { defineConfig } from 'vite'\nimport mkcert from 'vite-plugin-mkcert'\n\nexport default defineConfig({\n plugins: [ mkcert() ]\n})\n```\n\nWhen you run the local vite dev server you may be prompted for your password the first time. It will then install a local certificate onto your system and to a number of installed browsers.\n\nEasy!\n\n========================================\n\nCode:\n```js\nimport { defineConfig  } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport fs from 'fs';\n\nexport default defineConfig({\n  resolve: { alias: { '@': '/src' } },\n  plugins: [vue()],\n  https: {\n    key: fs.readFileSync('RootCA-key.pem'),\n    cert: fs.readFileSync('RootCA.pem')\n  }\n})\n```\n\n```text\nnpm run dev -- --https\n```\n\n```text\nnpm install -D @vitejs/plugin-basic-ssl\n```\n\n```js\nimport basicSsl from '@vitejs/plugin-basic-ssl'\n\nexport default {\n  plugins: [\n    basicSsl()\n  ]\n}\n```\n\n```text\nvite.config.ts\n```\n\n```sh\n# Step: 1\n# Install mkcert tool - macOS; you can see the mkcert repo for details\nbrew install mkcert\n\n# Step: 2\n# Install nss (only needed if you use Firefox)\nbrew install nss\n\n# Step: 3\n# Setup mkcert on your machine (creates a CA)\nmkcert -install\n\n# Step: 4 (Final)\n# at the project root directory run the following command\nmkdir -p .cert && mkcert -key-file ./.cert/key.pem -cert-file ./.cert/cert.pem 'localhost'\n```\n\n```js\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport fs from 'fs';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  server: {\n    https: {\n      key: fs.readFileSync('./.cert/key.pem'),\n      cert: fs.readFileSync('./.cert/cert.pem'),\n    },\n  },\n  plugins: [react()],\n});\n```\n\n```js\n// in package.json\n\"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"tsc && vite build\",\n    \"serve\": \"vite preview\",\n\n    \"cert\": \"rm -rf .cert && mkdir -p .cert && mkcert -key-file ./.cert/key.pem -cert-file ./.cert/cert.pem 'localhost'\"\n\n  },\n```\n\n```text\nvite.config.js\n```\n\n```text\nyarn dev\n```\n\n```text\nserver: {\n    https: true\n  }\n```\n\n```text\nvite --https\n```\n\n```text\nnpm run dev -- --https\n```\n\n```bash\nnpm i vite-plugin-mkcert -D\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport mkcert from 'vite-plugin-mkcert'\n\nexport default defineConfig({\n  plugins: [ mkcert() ]\n})\n```\n\n```js\nimport { fileURLToPath, URL } from 'node:url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport vueJsx from '@vitejs/plugin-vue-jsx'\nimport fs from 'fs';\n// https://vitejs.dev/config/\nexport default defineConfig({\n  server: {\n    https: {\n            key:  fs.readFileSync(\"../localhost+2-key.pem\"),\n            cert: fs.readFileSync(\"../localhost+2.pem\"),\n            ca: fs.readFileSync(\"../.local/share/mkcert/rootCA.pem\")\n\n        },\n      port: 8080\n},\n  plugins: [vue(), vueJsx()],\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url))\n    }\n  }\n})\n```\n\n```js\n// vite.config.js\nimport { fileURLToPath, URL } from \"node:url\";\n\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  server: {\n    https: {\n      key: '/path/to/some_folder/ssl/SSLforMyHosts-key.pem',\n      cert: '/path/to/some_folder/ssl/SSLforMyHosts-certificate.pem',\n    }\n  },\n  plugins: [\n    vue(),\n  ],\n  resolve: {\n    alias: {\n      \"@\": fileURLToPath(new URL(\"./src\", import.meta.url)),\n    },\n  },\n});\n```\n\n```bash\ncd /Users/your_name/some_folder/ssl\nmkcert \\\n  -cert-file SSLforMyHosts-certificate.pem -key-file SSLforMyHosts-key.pem \\\n  localhost 127.0.0.1 ::1 \\\n  some-other-local-dev-site.localhost \\\n  example.localhost\n```\n\n```text\nmkcert\n```\n\n```js\nimport {defineConfig} from'vite'\nimport mkcert from'vite-plugin-mkcert'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  server: {\n    https: true\n  },\n  plugins: [mkcert()]\n})\n```\n\n```text\nlocalhost\n```\n\n```text\nlocal IPs\n```\n\n```text\nrootCA.pem\n```\n\n```text\nmkcert\n```\n\n```text\nmkcert -CAROOT\n```\n\n```text\nAndroid\n```\n\n```text\nSettings\n```\n\n```text\nCertificate\n```\n\n```text\nrootCA.pem\n```\n\n```text\niPhone\n```\n\n```js\n// file vite.config.js - you may change \"whatever\"\nimport { defineConfig } from 'vite';\nimport backloopHttpsOptions from 'backloop.dev';\n\nexport default defineConfig({\n  server: {\n    port: 4443,\n    host: 'whatever.backloop.dev',\n    https: backloopHttpsOptions\n  },\n  // ... //\n});\n```\n\n```js\n// file vite.config.js - you may change \"myComputer\"\nimport { defineConfig } from 'vite';\nimport backloop from 'vite-plugin-backloop.dev';\n\nexport default defineConfig({\n  plugins: [\n    // ..\n    backloop('myComputer')\n  ],\n  // ..\n});\n```\n\n========================================\n\nComments:\n- Self-signed certs are invalid by default. You'll have to manually trust the certificate.\n- Unless you create and trust your own root CA in the local Browsers. And that is exactly where one wants vite to serve ones own self signed certs so that Chrome and co do not come up with the security question.\n- @hyphen: The example you provide has a mistake you might want to fix (at least for vite 3): the 'https' options under the keys 'server' or 'preview'.\n- Because I overlooked this for quite a while: Make sure you don't accidentally use vite's basicSsl() at the same time. In that case vite will never serve your own certificates and always generate an adhoc cert. After I got rid of that my openssl 3.x certs worked fine with vite.\n- this worked for me as of June 8th 2023 :) even in brave\n- note that if you use a custom server this won't work.\n- Works for Windows too. Install mkcert with chocolatey. A little tweaking to the mkcert command to avoid issues with slashes and localhost needs to be in double quotes. `mkdir .cert && cd .cert && mkcert -key-file key.pem -cert-file cert.pem \"localhost\"`\n- Clean, dependency free (other than having mkcert) solution for vice.\n- This should be the selected answer. The other solutions are shortcuts, while this one is actually encouraging the developer to actually read a real cert and key file.\n- step 3 gives: `error: unknown option '-install'`\n- this works till now which is version 3.2.5, please do not miss lead!\n- In support for @azgooon, v3.vitejs.dev/config/server-options.html#server-https\n- I'm using this in combination with laravel sail, but my container won't start anymore due to network failures\n- Thanks, solved my problem. Spent 12hrs+ trying to troubleshoot `ERR_SSL_PROTOCOL_ERROR` error before I came across this.\n- It also blocks the hosting of the vue application to your local network.npm run dev -- --host is not making application anymore accessible.\n- I don't recommend this solution as it asks for sudo permission and download files from external (coding.net) server.\n- I used this and worked for me. Thanks\n- Always check the creator of a package (and It's origin)\n- I was having issues with Visual Studio 2022, where suddenly having ssl issues, this solved dev issues for me.\n- it can work, but at first run , need to wait for 10 minutes until the \"install cert\" window popup\n- This worked perfectly for me. I tried the official package (@vitejs/plugin-basic-ssl) as well, but Chrome didn't work with it, so I switched back to this solution. Thanks\n- @MosesMachua sorry to hear about it\n- Chrome says certificate is not valid when using this\n- @JulienReszka It's a local certificate, so yes, chrome can't verify it, and you need to manually approve it. Click on \"Advanced parameters\" on the error page, then \"Continue toward 127.0.0.1\".\n- This should be the accepted answer, as it works perfectly for a dev environment and it's actually suggested by the documentation. Production - wise, it's another story.\n- They actually DON'T recommend doing this. They recommend using your own certificate, according to the linked page.\n- @TimKeating I added a small warning. This solution is of course only for testing purpose in dev environment. Anyway, I'm not sure anyone uses Vite in production, since the main point of Vite is hot-reload... You don't use Vite to serve generated files AFAIK.\n- SvelteKit's current model is Vite 100% of the time... although arguably, that means Rollup in production.\n- Using plugin-basic-ssl this approach I get a warning about SSL which I cannot skip (\"You cannot visit localhost right now because the website uses HSTS.\") We're better off signing our own certificate.\n- Mac users: for Chrome you can type 'thisisunsafe' to bypass, Safari, you need to paste the URL of the Vite server into the main window then use the options Safari gives you to bypass the security warnings. Note that while **@vitejs/plugin-basic-ssl** worked, **vite-plugin-mkcert** didn't.\n- I added this so it runs only on dev: ...(process.env.NODE_ENV === \"development\" ? [basicSsl()] : []),\n- This doesn't seem to work. I have accepted the warning and I still get net::ERR_CERT_AUTHORITY_INVALID errors for my vite client.\n- This does not work for service workers - so be vary of that. Mkcert variant provided below does.\n- @JulienReszka Have look at npmjs.com/package/@idleberg/vite-plugin-devcert maybe?\n- where does backloop come from? is it a package or a specific setup? I'm new to react and vite, so this answer is not very clear..\n- it works. but... i don't think it's secure. even with hosts file...\n- @BorisMaslennikov What security vulnerability have you identified? It might be fixed or documented.\n- I didn't identified any. I don't trust your dns. eventually A and AAAA could be changed... and I can't keep in mind that I need to update hosts file.\n- Me neither, this is why I recommend for security sensitive dev to also add entries to /etc/hosts\n- hosts solution does not work for me. anyway. your solution works just perfect.","metadata":{"transformedAt":"2026-08-18T18:33:46.387Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":32,"totalLines":367,"estimatedTokens":2747}}5{"id":"stack-69300341","source":"stackoverflow","questionId":69300341,"title":"\"TypeError: Failed to fetch dynamically imported module\" on Vue/Vite vanilla setup","tags":["javascript","typescript","vue.js","webpack","vite"],"text":"Title: \"TypeError: Failed to fetch dynamically imported module\" on Vue/Vite vanilla setup\nTags: javascript, typescript, vue.js, webpack, vite\nSource: Stack Overflow\n\nQuestion:\nWe have a vanilla Vue/Vite setup and I'm receiving `TypeError: Failed to fetch dynamically imported module` on sentry logs.\n\nIt seems like the errors are correlated in time with new deployment to prod, although I don't have enough data to confirm. It doesn't happen on local and appears only on deployed code.\n\nI've seen some similar questions for react's setups, but none with a satisfactory response.\n\nI've also found a similar question regarding dynamically imported svgs, but our errors happen for full components.\n\nThe only place where we use dynamic imported components is on routing:\n\n```\nexport const router = createRouter({\n history: routerHistory,\n strict: true,\n routes: [\n {\n path: '/',\n name: routes.homepage.name,\n component: () => import('@/views/Home.vue'),\n children: [\n {\n path: '/overview',\n name: routes.overview.name,\n component: () => import('@/views/Overview.vue'),\n },\n // other similar routes\n ],\n },\n ],\n});\n```\n\nOur deps versions:\n\n```\n\"vue\": \"^3.0.9\",\n \"vue-router\": \"^4.0.5\",\n \"vite\": \"^2.0.5\",\n```\n\nAny additional information on this issue and how to debug it would be much appreciated!\n\n========================================\n\nTop Answer:\nThe accepted answer correctly explains when this error is triggered but does not really provide a good solution.\n\nThe way I fixed this is by using an error handler on the router. This error handler makes sure that when this error occurs (so thus when a new version of the app is deployed), the next route change triggers a hard reload of the page instead of dynamically loading the modules. The code looks like this:\n\n```\nrouter.onError((error, to) => {\n if (error.message.includes('Failed to fetch dynamically imported module') || error.message.includes(\"Importing a module script failed\")) {\n window.location = to.fullPath\n }\n})\n```\n\nWhere `router` is your vue-router instance.\n\n========================================\n\nCode:\n```js\nexport const router = createRouter({\n  history: routerHistory,\n  strict: true,\n  routes: [\n    {\n      path: '/',\n      name: routes.homepage.name,\n      component: () => import('@/views/Home.vue'),\n      children: [\n        {\n          path: '/overview',\n          name: routes.overview.name,\n          component: () => import('@/views/Overview.vue'),\n        },\n        // other similar routes\n      ],\n    },\n  ],\n});\n```\n\n```js\n\"vue\": \"^3.0.9\",\n    \"vue-router\": \"^4.0.5\",\n    \"vite\": \"^2.0.5\",\n```\n\n```text\nTypeError: Failed to fetch dynamically imported module\n```\n\n```text\nOverview.abc123.js\n```\n\n```text\nOverview.32ab1c.js\n```\n\n```text\n/overview\n```\n\n```text\nOverview.abc123.js\n```\n\n```text\nOverview.32ab1c.js\n```\n\n```text\n/overview\n```\n\n```text\nFailed to fetch dynamically imported module\n```\n\n```text\nOverview.abc123.js\n```\n\n```text\nimport MyComponent from 'components/MyComponent'\n```\n\n```text\nimport MyComponent from 'components/MyComponent.vue'\n```\n\n```text\n.vue\n```\n\n```text\nimport IndexPage from '../pages/IndexPage.vue';\nimport TestPage from '../pages/TestPage.vue';\n```\n\n```text\nconst routes: RouteRecordRaw[] = [\n  {\n    path: '/',\n    component: () => import('layouts/MainLayout.vue'),\n    children: [\n      { path: 'test', component: () => TestPage },\n      { path: '', component: () => IndexPage }\n  ],\n  },\n  // Always leave this as last one,\n  // but you can also remove it\n  {\n    path: '/:catchAll(.*)*',\n    component: () => import('pages/ErrorNotFound.vue'),\n  },\n];\n```\n\n```text\nimport('../pages/page.vue');\n```\n\n```text\nimport('../pages/TestPage.vue')\n```\n\n```text\nimport TestPage from '../pages/TestPage.vue'\n```\n\n```text\nroutes.ts\n```\n\n```text\nrouter.onError((error, to) => {\n  if (error.message.includes('Failed to fetch dynamically imported module') || error.message.includes(\"Importing a module script failed\")) {\n    window.location = to.fullPath\n  }\n})\n```\n\n```text\nrouter\n```\n\n```text\nrouter.onError((error, to) => {\n  if (error.message.includes('Failed to fetch dynamically imported module')) {\n    window.location = to.href\n  }\n})\n```\n\n```text\nimport NonexistingComp from '/components/NonExistingComp.vue';\n```\n\n```text\nrouter.onError((error, to) => {\n  if (\n    error.message.includes('Failed to fetch dynamically imported module') ||\n    error.message.includes('Importing a module script failed')\n  ) {\n    if (!to?.fullPath) {\n      window.location.reload();\n    } else {\n      window.location = to.fullPath;\n    }\n  }\n```\n\n```text\n.jsx\n```\n\n```text\n.jsx\n```\n\n```text\nInboxScreen.stories.js\n```\n\n```text\nInboxScreen.stories.jsx\n```\n\n```bash\n# kill your dev server then\nrm -rf node_modules/.cache node_modules/.vite;\n# relaunch your server\nnpm run dev\n```\n\n```js\nrouter.onError((error) => {\n  console.error('router.onError', error)\n\n  const isDeployError =\n    error.message.includes('Failed to fetch dynamically imported module') ||\n    error.message.includes('Importing a module script failed')\n\n  if (isDeployError) errorReload(`Error during page load, ${error.message}`)\n})\n```\n\n```js\nexport const errorReload = (error: string, retries = 1) => {\n  // Get the current URL\n  const urlString = window.location.href\n\n  // Create a URL object\n  const url = new URL(urlString)\n  const errRetries = parseInt(url.searchParams.get('errRetries') || '0')\n  if (errRetries >= retries) {\n    window.history.replaceState(null, '', url.pathname)\n    // useSnackbarStore().add(error, { reload: true })\n    return\n  }\n\n  // Update or add the query parameter\n  url.searchParams.set('errRetries', String(errRetries + 1))\n\n  // Reload the page with the updated URL\n  window.location.href = url.toString()\n}\n```\n\n```text\nerrorReload\n```\n\n```js\nwindow.addEventListener('vite:preloadError', (event) => {\n  window.location.reload() // for example, refresh the page\n})\n```\n\n```text\n// vite.config.js\nimport { defineConfig } from 'vite';\nimport vue from '@vitejs/plugin-vue';\n\nexport default defineConfig({\n  plugins: [vue()],\n  build: {\n    //  ...other configurations\n    rollupOptions: {\n      // ...other options\n      output: {\n        assetFileNames: '[name].[ext]', // Preserve original file names\n      }\n    }\n  }\n});\n```\n\n```bash\nGET\nhttp://localhost:8080/@id/__x00__plugin-vuetify:components/VSkeletonLoader/VSkeletonLoader.sass\nNS_BINDING_ABORTED\n\nLoading failed for the module with source “http://localhost:8080/@id/__x00__plugin-vuetify:components/VSkeletonLoader/VSkeletonLoader.sass”.\n\nFailed to load Dashboard view--------- TypeError: error loading dynamically imported module: http://localhost:8080/src/views/Dashboard/index.vue\n\n[Vue Router warn]: uncaught error during route navigation:\n\nError: Couldn't resolve component \"default\" at \"/dashboard\"\n\nUncaught (in promise) Error: Couldn't resolve component \"default\" at \"/dashboard\"\n```\n\n```js\noptimizeDeps: {\n  exclude: ['vuetify']\n}\n```\n\n```text\nVSkeletonLoader\n```\n\n========================================\n\nComments:\n- Can you make a reproducible project available ?\n- Did you try using vanillaJS path references? `@&#47;smth&#47;smth` is VueMagic and might cause problems\n- Putting this here, If by chance helps anyone. I've seen similar error in our app. We're on Vue 3 + Vite with dynamic imports. Problem only occurred when using browser with uOrigin AdBlocker. Issue was we named one file `tracking-type.ts` which was then blocked by AdBlocker (duh, because of the name). Fix was simple rename to something that has no `tracking` in it :)\n- did you figure this out? I'm getting the same error: `Failed to fetch dynamically imported module: https:&#47;&#47;mywebsite&#47;assets&#47;HomePage.694cb716.js` . The file in question doesn't exist so can it be related to some sort of caching by the browser requesting an old chunk that doesn't exist anymore?\n- im getting this error just importing JavaScript: Uncaught (in promise) TypeError: Failed to fetch dynamically imported module: localhost:4173/i18n/en.js\n- @zigomir Thanks, mate. That was the issue in my Vue 3 + Vite project! You saved my day!\n- @zigomir thanks for that, ublock was blocking my file called analytics.vue so apparently it's not just tracking.\n- Thank you. I definitely would have spent a lot longer banging my head against a wall if I hadn't seen this.\n- Had the exact same problem when i added a new npm package. Restarting the dev server fixed it for me.. Thanks!\n- This answer is misleading. You can definitely get this error locally, and in that case restarting the dev server is a good fix, but the error is most likely not caused by lazy loaded routes. the original question asks about this error in the context of *production* and *lazy loaded routes*.\n- This answer is for local environment and not production.\n- works for my case also, Thanks!\n- Hey llyich, thanks for the reply. I'm afraid it is not the case here as we're using the extension as shown in the `require` statements in the example. We use it everywhere.\n- I needed `.svelte` for my project, I feel dumb, was checking the file name and everything lol\n- Yes! I reached this conclusion a while ago. I should have updated it in here, my bad. Although, I haven't found a good solution too. We're just ignoring the error for now. :(\n- This is an excellent explanation of the problem. For now, we, too, are ignoring the errors and asking users to \"refresh and try again\". But that's frustrating for both our team as well as the users. I wish the Vite team does something about this problem. With Vue 2 and webpack, this problem never occurred.\n- @Preetesh But I assume this error will not occur if the deployed application stays the same? Or in other words: Does this error only occur when the developer has recently redeployed the webapp and the browser clients have outdated caches?\n- @ShadowGames Mostly yes, it should not occur if the application stays the same. As other comments noted, it can happen if there's a typo, or the imported file does not exist, or the file extension is missing in the import path.\n- Thanks for this explanation. Like @Preetesh, we need to ask our users to refresh the page. Not a good solution right now, and it is frustrating because it is specific to Vite (with Webpack, no problem). I will implement the Wouter Sioen's solution temporarily.\n- I couldn't find a bug for this, so have logged it github.com/vitejs/vite/issues/11804\n- @Preetesh This is not magic. If you configured Webpack to bundle everything into a few big bundles, of course this would not happen. Are you sure you made the EXACT same setup using webpack? This will happen in ANY bundler that creates a bazillion different bundles to load, webpack not excluded. This is expected.\n- I've made a change inside a lazy-loaded component but I visited a different screen after deployment and still encountered the error. The screen where the error was caught does not import the modified component\n- Thank's for this answer, this is an excellent explanation of the problem. For now, we, too, are ignoring the errors\n- A bit surprised as `router.onError` expects a callback function of type `ErrorHandler` which expects only an error. There is no `to` parameter. (using vue-router 3.x)\n- Your errors may be browser specific. For example Firefox and Safari: `error loading a dynamically imported module` `Importing a module script failed`\n- The spec dictates that module caching is to happen even if it fails. Chrome will still serve you the cached failure, even if you refresh, which means you need to employ cache busting. Have a look here for one such approach (framework agnostic): stackoverflow.com/a/76200536/200987\n- Should be `window.location.href` instead of `window.location`, shouldn't it?\n- @L&#233;oCoco any idea on how to access 'to' route param?\n- This works (tested), but you should use window.location.href to avoid TypeScript errors\n- This worked for me, coupled with the explanation in domnantas response you have a good answer.\n- This probably works for a dev environment but not for production.\n- absolutely, not meant for prod, updated answer\n- Can you tell me where this code should be put?\n- Totally depends on your code, but you'll need to put it before the dynamic import request is made, so that the event listener is registered and it's callback invoked when Vite raises this event. In my React app, it's one of the first lines of JS that gets run by the browser.\n- Thanks man. I put it in my main.jsx file before ReactDOM.createRoot and its working fine\n- Can be useful to do `event.preventDefault()` in there as well to avoid alerts, if you have them setup.\n- Downvoted because this is a dangerous solution; the file names are changing for a good reason: this bypasses cache. If you don’t rename files when their content change, there’s the risk that clients continue to use outdated code, which *will* generate a lot of obscure errors.\n- The caching part of this answer has nothing to do with the question (and may even introduce more issues)\n- Actually, the caching part is really important to fix because the reloading part already triggered the error and showed the user the error, interrupting their workflow. However, caching preloads the JavaScript and only loads from the cache, then tries to load the new JavaScript if it exists.","metadata":{"transformedAt":"2026-08-18T18:33:46.387Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":38,"totalLines":375,"estimatedTokens":3320}}6{"id":"stack-68241263","source":"stackoverflow","questionId":68241263,"title":"Absolute path not working in Vite project React TS","tags":["reactjs","typescript","vite"],"text":"Title: Absolute path not working in Vite project React TS\nTags: reactjs, typescript, vite\nSource: Stack Overflow\n\nQuestion:\nI'm struggling to get absolute path to work in a **Vite react-ts** project.\n\nHere's how I created the project\n\n```\nnpm init @vitejs/app\nnpx: installed 6 in 1.883s\n√ Project name: ... test-vite\n√ Select a framework: » react\n√ Select a variant: » react-ts\n```\n\nThen I added **baseUrl** to **tsconfig.json**\nbased on the TS official doc:\n\n```\n{\n \"compilerOptions\": {\n \"baseUrl\": \"./src\",\n ...\n```\n\nfollowed by adding a simple component (T:\\test-vite\\src\\components\\Test.tsx)\n\n```\nimport React from \"react\";\n\nconst Test = () => \n\n### This is a Test.\n\n;\n\nexport default Test;\n```\n\nFinally I import the **Test** component in **App.tsx**\n\nbut it won't let me use absolute path:\n\n```\nimport Test from \"components/Test\";\n```\n\nI get this error\nhttps://i.sstatic.net/FRg69.png\n\nwhereas if I use relative path, the app works in **dev** & **build** mode without any error:\n\n```\nimport Test from \"./components/Test\";\n```\n\nHow can I make absolute path work in the project?\n\n========================================\n\nTop Answer:\nI came here through search results, I was looking for something different, namely, how to do a simple absolute import like `import { foo } from 'src/lib/foo.ts'`\n\nSo if you have a /src directory that contains all code and want to use an absolute import path.\n\nvite.config.ts\n\n```\nexport default defineConfig({\n ...\n resolve: {\n alias: {\n src: path.resolve('src/'),\n },\n }\n})\n```\n\ntsconfig.json\n\n```\n{\n \"compilerOptions\": {\n ...\n \"baseUrl\": \"./\"\n }\n}\n```\n\nNote that this is a trick: src is an alias, so it appears like the path is absolute in Vite. If you have another directory in the root dir, adjacent to /src, you will need to add another alias for that directory.\n\n========================================\n\nCode:\n```text\nnpm init @vitejs/app\nnpx: installed 6 in 1.883s\n√ Project name: ... test-vite\n√ Select a framework: » react\n√ Select a variant: » react-ts\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"baseUrl\": \"./src\",\n    ...\n```\n\n```text\nimport React from \"react\";\n\nconst Test = () => <h1>This is a Test.</h1>;\n\nexport default Test;\n```\n\n```text\nimport Test from \"components/Test\";\n```\n\n```text\nimport Test from \"./components/Test\";\n```\n\n```text\n// vite.config.ts\n{\n  resolve: {\n    alias: [\n      { find: '@', replacement: path.resolve(__dirname, 'src') },\n    ],\n  },\n  // ...\n}\n```\n\n```text\nimport Test from \"@/components/Test\";\nimport bar from \"@/foo/bar\"\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport tsconfigPaths from 'vite-tsconfig-paths'\n\nexport default defineConfig({\n  plugins: [tsconfigPaths()],\n})\n```\n\n```text\n./src\n```\n\n```text\nvite-tsconfig-paths\n```\n\n```text\nresolve.alias\n```\n\n```text\nvite-tsconfig-paths\n```\n\n```text\nvite-tsconfig-paths\n```\n\n```js\n// tsconfig.json\n{\n  \"paths\": {\n      \"@/*\": [\"src/*\"]\n    }\n  // ...\n}\n\n\n// vite.config.ts\n{\n  resolve: {\n   alias: [{ find: '@', replacement: '/src' }],\n  },\n  // ...\n}\n```\n\n```js\nimport Header from '@/components/Header.svelte\n```\n\n```text\nsrc\n```\n\n```text\nexport default defineConfig({\n  ...\n  resolve: {\n    alias: {\n      src: path.resolve('src/'),\n    },\n  }\n})\n```\n\n```json\n{\n  \"compilerOptions\": {\n    ...\n    \"baseUrl\": \"./\"\n  }\n}\n```\n\n```text\nimport { foo } from 'src/lib/foo.ts'\n```\n\n```text\nexport default defineConfig({\n  ...\n  resolve: {\n    alias: {\n      src: \"/src\",\n    },\n  },\n  ...\n})\n```\n\n```text\n{\n  \"compilerOptions\": {\n    ...\n    \"baseUrl\": \"./\",\n    \"paths\": {\n      \"src/*\": [\n        \"./src/*\"\n      ]\n    }\n  }\n}\n```\n\n```text\nimport {...} from \"src/foo/bar\";\n```\n\n```text\n@\n```\n\n```text\npath.resolve\n```\n\n```text\npath\n```\n\n```text\nvite.config.ts\n```\n\n```text\n/src\n```\n\n```text\nsrc\n```\n\n```text\ntsconfig.json\n```\n\n```text\nsrc\n```\n\n```json\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport path from \"path\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  resolve: {\n    alias: [{ find: \"@\", replacement: path.resolve(__dirname, \"src\") }],\n  },\n  plugins: [react()],\n});\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"paths\": {\n      \"@/*\": [\"./src/*\"]\n    }\n  }\n}\n```\n\n```text\nimport \"@/something-in-src\"\n```\n\n```text\n@types/node\n```\n\n```text\n\"path\"\n```\n\n```text\n__dirname\n```\n\n```text\n\"baseUrl\": \"./\",\n        \"paths\": {\n            \"@/*\": [\"src/*\"]\n        }\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport path from 'path';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n    resolve: {\n        alias: { '@': path.resolve(__dirname, './src') },\n    },\n    plugins: [react()],\n});\n```\n\n```text\nexport default defineConfig({ plugins: [react(), tsconfigPaths()] });\n```\n\n```bash\nnpm i path\nyarn add path\n\nnpm i @types/node\nyarn add @types/node\n\nnpm i vite-tsconfig-paths\nyarn add vite-tsconfig-paths\n```\n\n```text\nimport { defineConfig } from 'vite';\n    import react from '@vitejs/plugin-react';\n    import tsconfigPaths from 'vite-tsconfig-paths';\n    import path from 'path';\n\n    export default defineConfig({\n      base: './',\n      resolve: {\n        alias: {\n          Components: path.resolve(__dirname, './src/components'),\n          Assets: path.resolve(__dirname, './src/assets'),\n        },\n      },\n      plugins: [react(), tsconfigPaths()],\n    });\n```\n\n```text\n{\n      \"compilerOptions\": {\n        ...,\n        \"baseUrl\": \"./\",\n        \"paths\": {\n          \"src/*\": [ \"./src/*\" ],\n          // We define this path for all files/folders inside \n          // components folder:\n          \"Components/*\": [ \"./src/components/*\" ],\n          // We define this path for the index.ts file inside the \n          // components folder:\n          \"Components\": [ \"./src/components\" ],\n          \"Assets/*\": [ \"./src/assets/*\" ],\n          \"Assets\": [ \"./src/assets\" ]\n        }\n      },\n      ...\n    }\n```\n\n```text\nimport Test from \"components/Test\";\n```\n\n```text\nimport tsconfigPaths from \"vite-tsconfig-paths\"\n```\n\n```text\ndefineConfig({ ...,  plugins: [..., tsconfigPaths()] })\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport tsconfigPaths from 'vite-tsconfig-paths';\nimport react from '@vitejs/plugin-react';\n\nexport default defineConfig({\n  plugins: [react(),tsconfigPaths()],\n});\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"target\": \"esnext\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"esModuleInterop\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\",\n    \"baseUrl\": \"./src\",\n    \"paths\": {\n      \"@assets/*\": [\"./assets/*\"],\n      \"@components/*\": [\"./components/*\"],\n      \"@config/*\": [\"./config/*\"],\n      \"@hooks/*\": [\"./hooks/*\"],\n      \"@ioc/*\": [\"./ioc/*\"],\n      \"@pages/*\": [\"./pages/*\"],\n      \"@utils/*\": [\"./utils/*\"]\n    },\n    \"typeRoots\": [\"node_modules/@types\", \"./types\"]\n  },\n  \"include\": [\"src/**/*.ts\", \"src/**/*.tsx\", \"src/**/*.js\", \"src/**/*.jsx\", \"tests/**/*.ts\", \"tests/**/*.tsx\"],\n  \"exclude\": [\"node_modules\", \"dist\"],\n  \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\n```text\nimport React from 'react';\nimport HeaderCustom from '@components/header';\n\ninterface Props {\n   children?: React.ReactNode;\n}\n\nconst Component: React.FC<Props> = ({ children, ...props }) => {\n   return (\n      <>\n         <HeaderCustom></HeaderCustom>\n      </>\n   )\n}\n\nexport default Component;\n```\n\n```bash\nnpm install --save-dev rollup-plugin-includepaths\n```\n\n```js\nimport includePaths from \"rollup-plugin-includepaths\";\n\nexport default defineConfig({\n  plugins: [\n    react(),\n    includePaths({ paths: [\"./\"] })\n  ]\n})\n```\n\n```text\nimport MyModule from \"src/components/MyModule\";\n```\n\n```text\nincludePaths({ paths: [\"./src\"] })\n```\n\n```text\nimport MyModule from \"components/MyModule\"\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"paths\": {\n      \"@/*\": [\"./src/*\"] // ==> dot before '/' is important \n    },\n  },\n}\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport path from \"path\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  resolve: {\n    alias: {\n      \"@\": path.resolve(__dirname, \"./src\"),\n    },\n  },\n});\n```\n\n```text\nyarn add -D @types/node\n```\n\n```text\ntsconfig.json\n```\n\n```text\ncompilerOptions\n```\n\n```text\ntsconfig.app.json\n```\n\n```text\nvite.config.ts\n```\n\n```text\n__dirname\n```\n\n```text\n@types/node\n```\n\n```text\n\"vite\": \"^5.4.0\"\n```\n\n```js\nresolve: {\n    alias: {\n      src: \"/src\",\n    },\n  },\n```\n\n```js\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\nexport default defineConfig({\n  plugins: [react()],\n  resolve: {\n    alias: {\n      // here add the absolute paths that you wanna add\n      src: \"/src\",\n    },\n  },\n});\n```\n\n```js\nimport Button from \"src/components/Button/Button\"\n```\n\n```js\n{\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"src/*\": [\"./src/*\"],\n    }\n  }\n}\n```\n\n```text\nvite.config.js\n```\n\n```text\nimport { defineConfig } from \"vite\"\nimport path from \"path\"\nimport react from \"@vitejs/plugin-react\"\nimport federation from \"@originjs/vite-plugin-federation\"\n\nexport default defineConfig({\n  base: \"/\",\n  resolve: {\n    alias: {\n      src: path.resolve(__dirname, \"./src\"),\n    },\n  },\n  plugins: [\n    react(),\n    federation({\n      name: \"project name\",\n      filename: \"your main tsx file name\",\n      exposes: {\n        \"./App\": \"your main tsx file path\",\n      },\n      shared: [\n        \"react\",\n        \"react-dom\",\n        \"react-router-dom\",\n        \"@reduxjs/toolkit\",\n        \"react-error-boundary\",\n        \"react-redux\",\n        \"react-tooltip\",\n      ],\n    }),\n  ],\n  build: {\n    target: \"esnext\",\n    sourcemap: process.env.NODE_ENV === \"production\" ? false : true,\n    minify: process.env.NODE_ENV === \"production\" ? true : false,\n    emptyOutDir: true,\n  },\n})\n```\n\n```text\n\"paths\": {\n  \"src/*\": [\n    \"./src/*\"\n  ],\n}\n```\n\n```text\nresolve: {\n  alias: {\n    src: '/src',\n  },\n},\n```\n\n```text\npaths\n```\n\n```text\ntsconfig.app.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\nvite.config.ts\n```\n\n========================================\n\nComments:\n- Thank you @theprimone. The plugin is surely an easy way to make it work. I ended up with this simple vite.config.ts ``` import { defineConfig } from \"vite\"; import reactRefresh from \"@vitejs/plugin-react-refresh\"; import tsconfigPaths from \"vite-tsconfig-paths\"; // vitejs.dev/config export default defineConfig({ plugins: [reactRefresh(), tsconfigPaths()], }); ``` It means I can simply reference the component with relative path without the @ prefix. `import Test from \"components&#47;Test\";`\n- +1 for using `vite-tsconfig-paths` over a manual alias. I had a similar situation but wasn't using @ imports, and the suggested plugin fixed it.\n- I got \"Cannot find name '__dirname'.\" when using this solution. Changed the file name's extension from .ts to .cjs and it worked.\n- @RobinWieruch Try dev-installing `@types&#47;node` and explicitly import `path` like `import path from \"path\";`. The latest vite+react+typescript project I initialized didn't have that package installed.\n- An addition to @yuns, using the plugin (vite-tsconfig-paths) means that you set your paths in tsconfig.json without having to duplicate them in vite.config.ts (.i.e you don't have to manually configure resolve.alias)\n- You need to set the correct baseURL in tsconfig.json \"baseUrl\": \".\",\n- @V.Rubinetti You save my life .. thanks\n- this is worked with Vite 4.3.9. thank you\n- For vite-react-ts project, I used this in tsconfig -> \"paths\": { \"@/*\": [ \"./src/*\" ] }\n- There's also an npm package 'vite-tsconfig-paths' written by one of Vite's maintainers, however, it's better to not add extra 14 dependencies if it's possible.\n- Thanks! This helped me, but I wasn't able to get the usage of `path` working because `path` had no reference in the file. Not sure where it comes from, so I tweaked your approach and put together an alternative answer here for anyone else who has the same problem.\n- Used a lot different configurations I found to try to make this work and this finally did the trick, when the others did not. Thanks very much! To the person above you should be good to just `import path from 'path'`.\n- Great idea! On vscode I had to add this to settings.json so the linter will correctly import variables: \"typescript.preferences.importModuleSpecifier\": \"non-relative\", \"javascript.preferences.importModuleSpecifier\": \"non-relative\",\n- Here is the solution guys!!!\n- Thanks, this worked for me, but I had to make the aliases and paths lowercase (`assets` instead of `Assets`) for the import as you specified it to work.\n- Thanks. There must be a better way of doing both subfiles and index..\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- For a full breakdown of individual paths for the subfolders, you can just add more custom paths: medium.com/@pushplaybang/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:46.388Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":75,"totalLines":699,"estimatedTokens":3337}}7{"id":"stack-78997907","source":"stackoverflow","questionId":78997907,"title":"The legacy JS API is deprecated and will be removed in Dart Sass 2.0.0","tags":["vite","create-react-app","dart-sass"],"text":"Title: The legacy JS API is deprecated and will be removed in Dart Sass 2.0.0\nTags: vite, create-react-app, dart-sass\nSource: Stack Overflow\n\nQuestion:\nI was using create-react-app before and now I switched the same project to vite and everything working fine except I am getting a warning log as follows\n\nDeprecation [legacy-js-api]: The legacy JS API is deprecated and will be removed in Dart Sass 2.0.0.\n\nI want to get rid of these warnings from log while development and build the application. Following are my dependencies\n\n```\n{\n \"dependencies\": {\n \"@heroicons/react\": \"^2.1.5\",\n \"@tanstack/react-table\": \"^8.17.3\",\n \"i18next\": \"^23.12.1\",\n \"i18next-browser-languagedetector\": \"^8.0.0\",\n \"react\": \"^18.3.1\",\n \"react-dom\": \"^18.3.1\",\n \"react-i18next\": \"^14.1.3\",\n \"react-indiana-drag-scroll\": \"^2.2.0\",\n \"react-toastify\": \"^10.0.5\",\n \"recharts\": \"^2.13.0-alpha.4\",\n \"recoil\": \"^0.7.7\",\n \"sass\": \"^1.79.1\",\n \"uuid\": \"^10.0.0\"\n }\n}\n```\n\nNode version is v22.7.0\n\n========================================\n\nTop Answer:\nAdded following lines in the vite config fixes the issue, I missed it on the sass documentation (changelog). This will hide the warning message from console. Thanks @Family for pointing this out.\nPlease find sass changelog\n\n```\n//vite.config.ts\nexport default defineConfig({\n //..other config\n css: {\n preprocessorOptions: {\n scss: {\n silenceDeprecations: [\"legacy-js-api\"],\n },\n },\n },\n})\n```\n\n========================================\n\nCode:\n```json\n{\n  \"dependencies\": {\n    \"@heroicons/react\": \"^2.1.5\",\n    \"@tanstack/react-table\": \"^8.17.3\",\n    \"i18next\": \"^23.12.1\",\n    \"i18next-browser-languagedetector\": \"^8.0.0\",\n    \"react\": \"^18.3.1\",\n    \"react-dom\": \"^18.3.1\",\n    \"react-i18next\": \"^14.1.3\",\n    \"react-indiana-drag-scroll\": \"^2.2.0\",\n    \"react-toastify\": \"^10.0.5\",\n    \"recharts\": \"^2.13.0-alpha.4\",\n    \"recoil\": \"^0.7.7\",\n    \"sass\": \"^1.79.1\",\n    \"uuid\": \"^10.0.0\"\n  }\n}\n```\n\n```js\nexport default defineConfig({\n  css: {\n    preprocessorOptions: {\n      scss: {\n        api: 'modern-compiler' // or \"modern\"\n      }\n    }\n  }\n})\n```\n\n```text\nlegacy\n```\n\n```text\nvite.config.[js/ts]\n```\n\n```text\n//vite.config.ts\nexport default defineConfig({\n  //..other config\n  css: {\n    preprocessorOptions: {\n      scss: {\n        silenceDeprecations: [\"legacy-js-api\"],\n      },\n    },\n  },\n})\n```\n\n```text\ndart-sass\n```\n\n```text\nnode-sass\n```\n\n```text\ndart-sass\n```\n\n```text\nsass.render()\n```\n\n```text\nsass.compile()\n```\n\n```text\nsass.compileString()\n```\n\n```text\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n    css: {\n    preprocessorOptions: {\n        scss: {\n        api: 'modern-compiler' // or \"modern\"\n        }\n    }\n    } })\n```\n\n```text\nvite.config.ts\n```\n\n```text\nexport default defineNuxtConfig({\n  vite: {\n    css: {\n      preprocessorOptions: {\n        sass: {\n          api: 'modern',\n        },\n      },\n    },\n  }\n});\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n      css: {\n        preprocessorOptions: {\n          scss: {\n            api: 'modern-compiler', // or \"modern\", \"legacy\"\n            // silenceDeprecations: [\"legacy-js-api\"]\n          },\n        },\n      }\n    })\n```\n\n```text\nimport 'quasar/src/css/index.sass'\n```\n\n```text\nimport 'quasar/dist/quasar.css'\n```\n\n```text\nvite.config.js\n```\n\n```text\nmain.js\n```\n\n```text\nvite: {\n  css: {\n    preprocessorOptions: {\n      scss: {\n        api: \"modern-compiler\", // Using the modern Sass API\n      }\n    }  \n  }  \n},\n```\n\n```text\nnpm install -g sass-migrator\n```\n\n```bash\nfind . -type f -name \"*.scss\" -exec sass-migrator module --migrate-deps {}\n```\n\n```text\ncss: {\n  preprocessorOptions: {\n    scss: {\n      api: \"modern-compiler\", // Using the modern Sass API`  \n      additionalData: `@use \"@/styles/variables.scss\" as *;`, // Global\n      variables\n    }\n  }\n},\nresolve: {\n  alias: {\n    '@': '/src', // Alias for the src folder\n   },\n},\n```\n\n```text\nnpm install sass@latest vite@latest --save-dev\n```\n\n```text\nvite/config.dev.mjs\n```\n\n```text\nvite/config.prod.mjs\n```\n\n```text\n/src\n```\n\n```text\n@import\n```\n\n```text\n@use\n```\n\n========================================\n\nComments:\n- github.com/sass/dart-sass/blob/main/CHANGELOG.md#js-api\n- But how to properly fix it and not just silence the warning?\n- please refer the accepted answer of this question, instead of silenceDeprecations, you can use api: 'modern-compiler'\n- I tried it, but still getting the warning. I'm using svelte-kit, which uses vite.\n- Try using key as ‘sass’ instead of ‘scss’ inside preprocessorOptions object if you are using svelte-kit.\n- I use SASS in Nuxt, so I copied your solution to my nuxt.config.ts, and replaced \"scss\" with \"sass\". Thanks!\n- @AlphaHuang can u the piece of code here which you have added in nuxt.config.ts ? TIA\n- So, big question: how do we know when we can remove this workaround and Vite's default is set to use the modern compiler?\n- @Hashan94 I added an answer to this thread.\n- Didn't work for me, still receiving the same warnings. :(\n- on scss node,you need add a new child : `silenceDeprecations: [\"legacy-js-api\"],`\n- from the sass documentation: sass-lang.com/documentation/breaking-changes/legacy-js-api\n- I'm using Astro; in that case you have to wrap the 'css'-property in a 'vite' property: `export default defineConfig({ vite: { css: { ... } } })`\n- In case someone runs into the problem of seemingly not being able to resolve it. My config was using scss: `css: {` `. preprocessorOptions: {` `. scss: {` `. api: 'modern-compiler',` `. additionalData: '@use \"@&#47;scss&#47;variables.scss\" as *;',` `. },` `. },` `. },` So I was surprised I got the warnings. However adding the same for sass (despite not using it in my setup) resolved the issue: Add this under `preprocessorOptions`: `sass: { api: 'modern-compiler', },`\n- Working, but: Just make sure to update your project to match `scss` or `sass` instead.\n- Thanks @AdrianoCahete you saved my day! This should be part of the answer.\n- Could you please fix formatting of your answer so that only code remains formatted as code, with remaining part being formatted as plain text?","metadata":{"transformedAt":"2026-08-18T18:33:46.388Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":281,"estimatedTokens":1537}}8{"id":"stack-72146352","source":"stackoverflow","questionId":72146352,"title":"Vitest defineConfig, 'test' does not exist in type 'UserConfigExport'","tags":["typescript","vite","vitest"],"text":"Title: Vitest defineConfig, 'test' does not exist in type 'UserConfigExport'\nTags: typescript, vite, vitest\nSource: Stack Overflow\n\nQuestion:\nTrying to setup vitest on an already existing vite (vue 3, typescript) project.\n\nMy vite.config.ts looks like this:\n\n```\nimport { defineConfig } from 'vite';\nimport vue from '@vitejs/plugin-vue';\n\nexport default defineConfig({\n test: {\n globals: true,\n environment: 'jsdom',\n },\n plugins: [vue()],\n});\n```\n\nBut in VS code it complains:\n\nhttps://i.sstatic.net/1vQHh.png\n\nOn hover I see:\n\nArgument of type '{ test: { globals: boolean; environment: string; }; plugins: Plugin[]; }' is not assignable to parameter of type 'UserConfigExport'.\nObject literal may only specify known properties, and 'test' does not exist in type 'UserConfigExport'.ts(2345)\n\nI can make it go away if I change this line:\n\n```\nimport { defineConfig } from 'vite';\n```\n\nTo:\n\n```\nimport { defineConfig } from 'vitest/config';\n```\n\nBut why? What's up with this? Why should I have to import defineConfig from vitest in order to get it to support the test property?\n\n========================================\n\nTop Answer:\nI separated the files because i got the from this question and if i changed the import to vitest i got another error in the plugin react line.\n\n- vite.config.ts\n\n- vitest.config.ts\n\nvitest:\n\n```\nimport { defineConfig } from 'vitest/config';\n\n export default defineConfig({\n test: {\n globals: true,\n environment: 'jsdom'\n },\n })\n```\n\nvite:\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\nexport default defineConfig({\n plugins: [react()],\n server: {\n port: 3000,\n },\n})\n```\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite';\nimport vue from '@vitejs/plugin-vue';\n\nexport default defineConfig({\n  test: {\n    globals: true,\n    environment: 'jsdom',\n  },\n  plugins: [vue()],\n});\n```\n\n```text\nimport { defineConfig } from 'vite';\n```\n\n```text\nimport { defineConfig } from 'vitest/config';\n```\n\n```js\nimport { defineConfig } from 'vite';\n```\n\n```js\nimport { defineConfig } from 'vitest/config';\n```\n\n```js\n/// <reference types=\"vitest/config\" />\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  test: {\n    // ...\n  },\n})\n```\n\n```ts\n/// <reference types=\"vitest\" />\n```\n\n```js\n/// <reference types=\"vitest\" />\nimport { defineConfig } from 'vite';\nimport type { UserConfig as VitestUserConfigInterface } from 'vitest/config';\n\nconst vitestConfig: VitestUserConfigInterface = {\n  test: {\n    // vitest config, with helpful vitest typing :)\n  }\n};\n\nexport default defineConfig({\n  test: vitestConfig.test,\n  // and now: just vite config\n});\n```\n\n```text\n...\nimport type { InlineConfig } from 'vitest';\nimport type { UserConfig } from 'vite';\n\ninterface VitestConfigExport extends UserConfig {\n  test: InlineConfig;\n}\n...\n```\n\n```text\nexport default defineConfig({\n  plugins: [solidPlugin()],\n  server: {\n    port: 3000,\n  },\n  test: {\n    environment: 'jsdom',\n    globals: true,\n    transformMode: {\n      web: [/\\.[jt]sx?$/],\n    },\n    setupFiles: './setupVitest.ts',\n  },\n  build: {\n    target: 'esnext',\n  },\n} as VitestConfigExport);\n```\n\n```text\nUserConfig\n```\n\n```text\nconfig\n```\n\n```text\ntest\n```\n\n```text\n/// <reference types=\"vitest\" />\n```\n\n```text\nimport { defineConfig } from 'vitest/config';\n\n    export default defineConfig({\n        test: {\n          globals: true,\n          environment: 'jsdom'\n        },\n      })\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\nexport default defineConfig({\n  plugins: [react()],\n  server: {\n    port: 3000,\n  },\n})\n```\n\n```text\nimport type { InlineConfig } from 'vitest';\nimport type { UserConfig } from 'vite';\n\ntype ViteConfig = UserConfig & { test: InlineConfig };\nconst config: ViteConfig = {\n  // other config\n  test: {\n    environment: 'jsdom',\n  },\n};\nexport default defineConfig(config);\n```\n\n```text\nas VitestConfigExport\n```\n\n```text\n/// <reference types=\"vitest\" />\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n  ...\n  test: {\n   ...\n  },\n});\n```\n\n```text\n/// <reference types=\"vitest\" />\n```\n\n```html\n/// <reference types=\"vitest\" />\nimport { defineConfig } from 'vite';\nimport vue from '@vitejs/plugin-vue';\nimport vueJsx from '@vitejs/plugin-vue-jsx'; // 支持jsx语法\n\n// https://vitejs.dev/config/\nexport default defineConfig(() => {\n  return {\n    plugins: [vue(), vueJsx()],\n    test: {\n      globals: true,\n      environment: 'jsdom',\n      transformMode: { web: [/.[tj]sx$/] },\n    },\n  };\n});\n```\n\n```text\nimport { defineConfig as defineViteConfig, mergeConfig } from 'vite';\nimport { defineConfig as defineVitestConfig } from 'vitest/config';\nimport react from '@vitejs/plugin-react';\n\nconst viteConfig = defineViteConfig({\n  plugins: [react()],\n});\n\nconst vitestConfig = defineVitestConfig({\n  test: {\n    // ...\n  },\n});\n\nexport default mergeConfig(viteConfig, vitestConfig);\n```\n\n```text\nmergeConfig\n```\n\n```text\nvite\n```\n\n```text\nvitest/config\n```\n\n```text\nimport type { UserConfig as VitestUserConfig } from 'vitest/config';\nimport { defineConfig } from 'vite';\n\ndeclare module 'vite' {\n  export interface UserConfig {\n    test: VitestUserConfig['test'];\n  }\n}\n\nexport default defineConfig({\n  // add your vite configuration here\n\n  test: {\n    // add your vitest configuration here\n  },\n});\n```\n\n```text\nexport default defineConfig(() => ({\n  build: {\n    // ...\n  },\n  test: {\n    // ...\n  },\n}));\n```\n\n```bash\nyarn install -D vitest vite\n```\n\n```text\nimport {defineConfig} from \"vite\";\nimport \"vitest/config\" // <-- just dummy import\n\nexport default defineConfig({\n  test: {\n    // your stuff here\n  }\n})\n```\n\n```text\nimport { defineConfig, UserConfig } from 'vite'\n\nexport default defineConfig({\n    // your vite config\n    test: {\n        environment: 'jsdom',\n        setupFiles: 'src/setup-tests.tsx',\n        coverage: {...},\n    },\n} as UserConfig)\n```\n\n```text\ndeclare module 'vite' { interface UserConfig... }\n```\n\n```text\nObject literal may only specify known properties, and test does not exist in type 'UserConfigExport'\n```\n\n```text\ndeclare function defineConfig(config: UserConfig): UserConfig;\ndeclare function defineConfig(config: Promise<UserConfig>): Promise<UserConfig>;\ndeclare function defineConfig(config: UserConfigFnObject): UserConfigFnObject;\ndeclare function defineConfig(config: UserConfigExport): UserConfigExport;\n```\n\n```text\nUserConfig\n```\n\n```text\nUserConfig\n```\n\n```text\nUserConfig\n```\n\n```text\nUserConfigExport\n```\n\n```text\ndefineConfig\n```\n\n```text\nUserConfig\n```\n\n```text\nUserConfig\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport type { UserConfig } from 'vitest/config';\nimport react from '@vitejs/plugin-react';\n\nconst config: UserConfig = {\n  plugins: [react()],\n  test: {\n    globals: true,\n    environment: 'jsdom',\n  },\n};\n\n// https://vitejs.dev/config/\nexport default defineConfig(config);\n```\n\n```json\n{\n   \"compilerOptions\": {\n      \"types\": [\n         \"vitest\"\n     ],  \n  },\n  \"include\": [\n    \"src\",\n    \"vite.config.ts\"\n  ]\n}\n```\n\n```none\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n  ...\n  test: {\n     ...\n  },\n});\n```\n\n```text\ntsconfig.json\n```\n\n```text\nvite.config.ts\n```\n\n```none\nimport type { UserConfig } from 'vite'\nimport type { UserConfig as VitestConfig } from 'vitest/node'\n\nexport default {\n    // ...vite config...\n    test: {\n        // ...vitest config...\n    }\n} as UserConfig & { test: VitestConfig }\n```\n\n```text\nUserConfig\n```\n\n```text\nUserConfig\n```\n\n```text\nnpm ls vite\n```\n\n```js\nimport { defineConfig as testConfig } from \"vitest/config\";\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\";\n\n// Vite configuration\nconst config = defineConfig({\n  plugins: [vue()],\n});\n\n// Vitest configuration\nconst tstConfig = testConfig({\n  test: {\n    environment: \"jsdom\",\n  },\n});\n\n// Merge configurations\nexport default {\n  ...config,\n  ...tstConfig,\n};\n```\n\n```text\nvite\n```\n\n```text\nvitest\n```\n\n```text\nvite.config.ts\n```\n\n```text\ndefineConfig\n```\n\n```text\nvite\n```\n\n```text\nvitest/config\n```\n\n```text\nvite\n```\n\n```text\nvitest\n```\n\n```text\nvite\n```\n\n```text\nvitest\n```\n\n```text\nimport { defineConfig } from \"vitest/config\"\nimport tsConfigPaths from \"vitest-tsconfig-paths\"\n\nexport default defineConfig({\n  plugins: [tsConfigPaths()],\n  test: {\n    globals: true,\n  },\n})\n```\n\n```text\n{\n  \"baseUrl\": \"./\",\n  \"paths\": {\n    \"@/*\": [\"./src/*\"]\n  },\n  \"types\": [\"vitest/globals\"]\n}\n```\n\n========================================\n\nComments:\n- not working for me\n- Neither for me, but this answer did: stackoverflow.com/a/73106019/1408053\n- This worked for me after I upgraded vite to 4.0.4, and vitest to 0.26.3\n- I was already using the triple slash but didn't work. as @DavidHorm mentioned upgrading vite to 4.0.4 solved the issue for me :D\n- Added the /// reference and the error went away for me. Thanks\n- If it doesn't work, It's probably because vite and vitest are incompatible with each other. To verify this you can upgrade both libs to the latest version and see if the tsc error disappears. If that's the case you need to either upgrade vite or downgrade vitest\n- Didn't work for me but separating config by having vite.config.ts and vitest.config.ts helped me: stackoverflow.com/a/75020580/837165.\n- thanks @LorenzoRivosecchi i updated vite and it works with directive\n- Thanks a lot, also can be use in `tsconfig.node.json`, by add `\"types\": [\"vitest\"]` to it. :+1:\n- @mikoloism Well yes, this works for this use case but has probably unwanted (IMHO) effect that only Vitest types are visible. If you are using more plugins (with type definitions), all of them needs to be specified there. (See the docs).\n- Running yarn dedupe worked for me\n- Here's the new documentation link for Configuring Vitest config file (the one mentioned in the post is broken)\n- The docs seem to suggest that we should not be importing from vitest/config inside our vite.config.ts; and instead seem to favor the triple-slash directive\n- This fails for me with typescript 5.6.2, vite 4.2.0, vitest 2.1.1. Gives error on the test: vitestConfig.test line.\n- just use simple import stackoverflow.com/a/78202545/862567\n- works with nuxt3, thanks\n- Note that using `as` means that type-checking is entirely circumvented and you won't get type errors if anything in your object structure is incorrect. Ideally, use `satisfies`.\n- So the documentation saying to use `&#47;&#47;&#47; <reference ...` is wrong?\n- stackoverflow.com/a/77229505/179332 seems much cleaner to me and works beautifully.\n- This feels like the most elegant solution of the ones posted here.\n- Be aware that this means all options in your vite.config will be ignored by vitest.\n- I've tried this solution and besides the documentation says the vite.config options would be ignored everything is working properly here\n- In new version import the InlineConfig from 'vitest/node'\n- This comment brings no value. It's the same as what the previous post states as an alternative option, and it is apparent from the comments bellow it that for some it works and for some, it doesn't.\n- This works, makes sense, really wish we didn't have to do it, thanks for sharing!\n- This is the way, most elegant solution 👏\n- Thank you! This is indeed the most elegant approach.\n- If this is legit then why isn't it documented in vitest.dev/guide/#adding-vitest-to-your-project ?\n- It literally is `The will stop working in Vitest 3, but you can start migrating to vitest&#47;config in Vitest 2.1:`\n- No, I'm referring to the fact that the `import \"vitest&#47;config\"` dummy import is not mentioned anywhere in that guide.\n- Also I tried it, and it didn't work for me.\n- thats what I'm refering to `start migrating to vitest&#47;config`. If you post a question with your configuration I can help you make it work. Include TS version, Vite version and Vetest version too please\n- That's a very kind offer, thanks! But I already managed to get it working via stackoverflow.com/a/77229505/179332 which seems like the most elegant solution of all the ones I've seen so far. I just don't understand why it isn't in the official docs.\n- As I pointed it out it is in official docs. Also this is how all others packages works for importing types. Its not a magic, it is how typescript works elsewhere too.\n- Ah, I see that the `mergeConfig` approach is indeed in the official docs - I missed that before. But `import \"vitest&#47;config\"` isn't, and the `mergeConfig` trick is only mentioned as an afterthought inside a warning box at the end of the section. I do wonder why they don't make that the first recommendation instead as it seems to elegantly avoid all of the awkward typing issues.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- Fails for me with vite 4.2.0, vitest 2.1.1.\n- December 2024: with vite v6.0.1, vitest: v2.1.8, with TS. I can confirm that's working.\n- Vitest 2.1.7 reverted support for Vite 6: github.com/vitest-dev/vitest/releases/tag/v2.1.7. The first version of Vitest to support Vite 6 will be Vitest 3: github.com/vitest-dev/vitest/releases/tag/v3.0.0-beta.1\n- Ah yes good point. Though it does actually still work, at least in my case. Updating the answer, thanks.\n- this worked for me - the accepted answer did not","metadata":{"transformedAt":"2026-08-18T18:33:46.388Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":62,"totalLines":603,"estimatedTokens":3373}}9{"id":"stack-70709987","source":"stackoverflow","questionId":70709987,"title":"How to load environment variables from .env file using Vite","tags":["javascript","environment-variables","vite","env-file"],"text":"Title: How to load environment variables from .env file using Vite\nTags: javascript, environment-variables, vite, env-file\nSource: Stack Overflow\n\nQuestion:\nI want to load environment variables from the `.env` file using Vite\n\nI used the `import.meta.env` object as mentioned in Docs\n\n`.env` file:\n\n```\nTEST_VAR=123F\n```\n\nwhen trying to access this variable via the `import.meta.env` -> `import.meta.env.TEST_VAR` it returns undefined.\n\nso, how can I access them?\n\n========================================\n\nTop Answer:\nif you want to access your env variable TEST_VAR you should prefix it with `VITE_`\n\ntry something like\n\n```\nVITE_TEST_VAR=123f\n```\n\nyou can access it with\n\n```\nimport.meta.env.VITE_TEST_VAR\n```\n\n========================================\n\nCode:\n```text\nTEST_VAR=123F\n```\n\n```text\n.env\n```\n\n```text\nimport.meta.env\n```\n\n```text\n.env\n```\n\n```text\nimport.meta.env\n```\n\n```text\nimport.meta.env.TEST_VAR\n```\n\n```text\nimport { defineConfig, loadEnv } from 'vite';\n\nexport default ({ mode }) => {\n    // Load app-level env vars to node-level env vars.\n    process.env = {...process.env, ...loadEnv(mode, process.cwd())};\n\n    return defineConfig({\n      // To access env vars here use process.env.TEST_VAR\n    });\n}\n```\n\n```text\n// vite.config.js\n\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig, loadEnv } from 'vite';\n\n/** @type {import('vite').UserConfig} */\nexport default ({ mode }) => {\n    // Extends 'process.env.*' with VITE_*-variables from '.env.(mode=production|development)'\n    process.env = {...process.env, ...loadEnv(mode, process.cwd())};\n    return defineConfig({\n        plugins: [sveltekit()]\n    }); \n};\n```\n\n```text\nVITE_\n```\n\n```text\nvite.config.js\n```\n\n```text\nloadEnv()\n```\n\n```text\nVITE_TEST_VAR=123f\n```\n\n```text\nimport.meta.env.VITE_TEST_VAR\n```\n\n```text\nVITE_\n```\n\n```text\nsrc\n```\n\n```text\n.env\n```\n\n```text\n.env.development\n```\n\n```text\nnpm run dev\n```\n\n```text\nVITE_\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport dotenv from 'dotenv'\n\ndotenv.config() // load env vars from .env\n\nexport default defineConfig({\n  define: {\n    __VALUE__: `\"${process.env.VALUE}\"` // wrapping in \"\" since it's a string\n  },\n  //....\n}\n```\n\n```text\nVALUE='My env var value'\n```\n\n```text\ndotenv.config()\n```\n\n```text\nvite.config.js\n```\n\n```text\n.env\n```\n\n```text\nprocess.env\n```\n\n```text\n.env\n```\n\n```text\nexport default defineConfig({\n...\n  envPrefix: 'TEST_',\n...\n})\n```\n\n```text\nenvPrefix\n```\n\n```text\nenvPrefix\n```\n\n```text\nTEST_\n```\n\n```text\n''\n```\n\n```text\nenvPrefix\n```\n\n```text\n''\n```\n\n```text\n''\n```\n\n```text\npnpm add dot-env\npnpm add -S  dotenv-webpack.\n```\n\n```text\nVITE_\n```\n\n```text\nMAP_API_KEY\n```\n\n```text\nVITE_MAP_API_KEY\n```\n\n```text\n.env.local\n```\n\n```text\nimport.meta.env\n```\n\n```text\nconst App = () => {\n   return <div>{import.meta.env.VITE_MY_API}</div>\n}\n```\n\n```text\nVITE_\n```\n\n```text\nMY_API = xyz\n```\n\n```text\nVITE_MY_API = xyz\n```\n\n```text\nimport.meta.env.VITE_MY_API\n```\n\n```js\nTo load environment variables from.env file using Vite, you need to follow these steps:\n\n  Install the dotenv library with npm:\n  npm install dotenv\nCreate a.env file in the root directory of your project and add your environment variables to it.\nFor example: #contents of .env\nVITE_API_KEY = my - secret - api - key\nPrefix your environment variables with VITE_ to make them accessible to your Vite - processed code.For example:\n  VITE_API_KEY = my - secret - api - key\nImport the environment variables in your code using the\nimport.meta.env object.For example:\n  // import the environment variable\n  const apiKey =\n    import.meta.env.VITE_API_KEY;\n\n// use the environment variable\nconsole.log(apiKey); // prints my-secret-api-key\nRestart the server after making changes to the.env file.\nFor more information, you can refer to the official documentation: https: //vitejs.dev/guide/env-and-mode.html\n```\n\n```js\nconst env = await import.meta.env;\nexport const version = (env.VITE_APP_VERSION);\nexport const buildDate = (env.VITE_APP_BUILD_TIME);\n```\n\n```text\n.env\n```\n\n```text\nawait\n```\n\n```text\n.env.development\n```\n\n```text\nVITE_APP_VERSION=development vite\n```\n\n```text\nnpm install dotenv --save\n```\n\n```js\nimport { defineConfig, loadEnv } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\nexport default defineConfig(({ command, mode }) => {\n  // Load env file based on `mode` in the current working directory.\n  // Set the third parameter to '' to load all env regardless of the `VITE_` prefix.\n  const env = loadEnv(mode, process.cwd(), '')\n\n  return {\n    plugins: [react()],\n    // vite config\n    define: {\n      ...Object.keys(env).reduce((prev, key) => {\n        const sanitizedKey = key.replace(/[^a-zA-Z0-9_]/g, \"_\");\n\n        prev[`process.env.${sanitizedKey}`] = JSON.stringify(env[key]);\n\n        return prev;\n      }, {}),\n    },\n  }\n})\n```\n\n```text\nprocess.env.VARIALBE_NAME\n```\n\n```text\nif (import.meta.env.DEV) {\n        // side effect necessary to have env. variables ready when running `npm run dev`.\n        (async () => await import.meta.env)();\n    }\n```\n\n```text\n/**\n     * Convenient method that gets the value of environment variables\n     * @param {string} name name of the env. var\n     * @returns {string} value of the env. var\n     */\n   const getEnvVar = name => import.meta?.env?.[name];\n```\n\n```text\nVITE_\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run build\n```\n\n```text\nimport { defineConfig, loadEnv } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\nexport default ({ mode }) => {\n  // Load app-level env vars to node-level env vars. !!! BUT DON'T REASSIGN it to process.env (notice `const loadedEnv =`) !!!\n  const loadedEnv = { ...process.env, ...loadEnv(mode, process.cwd()) };\n\n  return defineConfig({\n    // To access env vars here use loadedEnv.TEST_VAR\n  });\n};\n```\n\n```text\nloadedEnv\n```\n\n```text\nprocess.env\n```\n\n```text\nMY_VAR=${MY_ACTUAL_EN_VAR}\n```\n\n```text\nMY_VAR=${MY_ACTUAL_VAR:-a_fallback_value_123}\n```\n\n```text\nMY_ACTUAL_VAR\n```\n\n```text\nMY_VAR\n```\n\n```text\nimport.meta.env.MY_VAR\n```\n\n```js\nimport { defineConfig, loadEnv } from \"vite\";\n\n// https://vite.dev/config/\n\nexport default defineConfig(({ mode }) => {\n    // If you want to use the environment variables without prefix VITE_\n    // EX: process.env.API_KEY\n    const updatedEnv = Object.fromEntries(\n        Object.entries(loadEnv(mode, process.cwd())).map(([key, val]) => [\n            key.replace(/^VITE_/, \"\"),\n            val,\n        ])\n    );\n\n    // If you want to use the environment variables with prefix VITE_\n    // EX: process.env.VITE_API_KEY\n    // const updatedEnv = loadEnv(mode, process.cwd(), 'VITE_');\n    return {\n        define: {\n          'process.env': updatedEnv\n        },\n        // other configs like plugins, ...etc\n    };\n});\n```\n\n```text\nVITE_\n```\n\n```text\n.env\n```\n\n```text\nvite.config.js\n```\n\n```text\nprocess.env.{variableName}\n```\n\n```text\nVITE\n```\n\n========================================\n\nComments:\n- Only those with VITE_ prefix will be visible inside your JS / Vue code. Check their documentation vitejs.dev/guide/env-and-mode.html\n- You need to use VITE_APP_xxxxxx to define the variables in the ENV file.\n- Does this answer your question? How can I use Vite env variables in vite.config.js?\n- The .env file should be in the root folder\n- but with import.meta.env I get an error that the meta name is not found\n- I do not know why it throws an error, but `&#47;&#47; @ts-ignore` on the line above helps 🤫\n- vitejs.dev/guide/env-and-mode.html#intellisense-for-typescri&zwnj;&#8203;pt\n- In `Node.js` you can access it regularly with `process.env.VITE_TEST_VAR`\n- @EliZatlawy no you can't\n- Yeah, it was work.\n- i'm here just cause, in fact, does not work\n- Thanks for the example, I'm using Vite with Svelte (not svelteKit) to generate code for browsers and obviously I misinterpreted the Vite documentation, I expected that .env was always included automatically, since it doesn't work and adding loadEnv in the config works i would say that's not the case.\n- The linked docs (vitejs.dev/guide/env-and-mode.html#env-files) don't mention using `loadEnv` - they seem to imply that the presence of `.env` in the root will load `VITE_` env vars implicitly. `loadEnv` seems to be required, but I don't see it in the docs O.o. Vite version: 3.1.4\n- Good catch. The doc for `loadEnv` (vitejs.dev/guide/api-javascript.html#loadenv) permits to see that we can change the prefix: `process.env = {...process.env, ...loadEnv(mode, process.cwd(), \"VUE_\")};`\n- thank you, I just had to add `VITE_` at the beginning.\n- Does anyone know how to access production environment variables from a cloud deployment? I assume I'll need a conditional statement to seek them, but is there a particular reference for them? I.e. in python it's os.environ.\n- just remember to restart your server.. was stuck on that.\n- This works for DEV but how do you get env variable for production -- (npm run build). Do you have to add .env to GIT?.\n- This works but trying to access process.env.NODE_ENV doesn't appear to work.\n- This answer is outdated and hence misleading. The correct answer these days is the one below. See docs here.\n- Alternatively, setting `envDir` option in `vite.config.ts`: `typescript export default defineConfig({ plugins: [react()], envDir: '.&#47;src&#47;environments' })`\n- What tripped me up was not realizing I had created my `.env.development` file in the `src` folder instead of the root dir 🙈\n- Note that when the vite docs mention `root`, they mean the project root (i.e. where `index.html` is), and not the top-level project folder. These are not the same if you have set the `root` option. @bishop I presume you have `root: \".&#47;src\"` set.\n- I just wasted two hours because my env file was outside my project folder\n- Another gotcha: I had comments in my .env file so vite didn't load the .env file.\n- Having `.env[*]` in the `src` instead of the root always trips me up. I don't know how many times I've been \"gotcha\"d by that 🤦‍♂️ Thanks for the reminder, @James Lawruk.\n- I was missing a dot in the beginning of the filename.... Hope this can be helpful to anyone xd\n- How do you install \"dotenv\" in a Vite/React project? I tried `npm install dotenv` but still I get errors\n- Dont undestand how your import **VALUE**, there is no this variable\n- Vite uses dotenv under the hood. Wouldn't loadEnv achieve same goal?\n- Best answer ever! for CRA for instance, use `envPrefix: 'REACT_APP_'` and it will pick things up from your `.env` file.\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- Did you notice that the formatting in your question is completely broken? Please fix it\n- This works for DEV but how do you get env variable for production -- (npm run build). Do you have to add .env to GIT?.\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- This answer looks like it was generated by an AI (like ChatGPT), not by an actual human being. You should be aware that posting AI-generated output is officially **BANNED** on Stack Overflow. If this answer was indeed generated by an AI, then I strongly suggest you delete it before you get yourself into even bigger trouble: **WE TAKE PLAGIARISM SERIOUSLY HERE.** Please read: Why posting GPT and ChatGPT generated answers is not currently allowed.\n- Where do you configure this? In the vite config file?","metadata":{"transformedAt":"2026-08-18T18:33:46.388Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":73,"totalLines":492,"estimatedTokens":2925}}10{"id":"stack-69744253","source":"stackoverflow","questionId":69744253,"title":"vite build always using static paths","tags":["vite"],"text":"Title: vite build always using static paths\nTags: vite\nSource: Stack Overflow\n\nQuestion:\nI have a simple setup with an index.html, some js file and a sass file, building it with vite. I am using vite defaults without a config file.\n\nAfter running a build the index.html in the dist folder references everything as static paths:\n\n```\n\n \n \n\n```\n\nThe same happens to url() paths in css: They are turned into static paths as well.\nMy question is: Is there a configuration option to make vite output relative paths, so:\n\n```\n\n \n \n\n```\n\n========================================\n\nCode:\n```html\n<head>\n  <script type=\"module\" crossorigin src=\"/assets/index.b850bc1f.js\"></script>\n  <link rel=\"stylesheet\" href=\"/assets/index.04d1c13d.css\">\n</head>\n```\n\n```html\n<head>\n  <script type=\"module\" crossorigin src=\"assets/index.b850bc1f.js\"></script>\n  <link rel=\"stylesheet\" href=\"assets/index.04d1c13d.css\">\n</head>\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  base: '', 👈\n})\n```\n\n```text\nbase\n```\n\n```text\n/\n```\n\n```text\nbase\n```\n\n========================================\n\nComments:\n- Perfect! `base: '.&#47;'` works, too! I like to be explicit about relative paths and it also suggests what base is for to my future devs and myself (in case I need to CTRL-F).\n- For me, the static path don`t change.\n- For me that leads to Vite adding full path from drive to the result! That is, \"../../../../my_projects/my_project/assets/index-923869f3.js&zwnj;&#8203;\" Looks as complete nonsense.\n- @ArseniiFomin Had something similar happen to me with `base: '.&#47;',` in my vite.config.ts, though it only seems to occur when using `watch` on the command line. I'm currently using `vite build --watch --base=&#47;assets&#47;..\"` (which it resolves to `&#47;` in index.html, thankfully) to trick it into producing what I want. Weird.\n- @ruffin Your suggestion to make sure the --base attribute in vite build was using the static path --base=/assets/.. fixed the problem for me. When I refreshed a page and looked at the underlying html (CTRL-U), you could see that the .js file was being loaded from ./assets/file.js, not /assets/file.js. This gave me the clue that I needed. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:46.388Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":72,"estimatedTokens":554}}11{"id":"stack-64677212","source":"stackoverflow","questionId":64677212,"title":"How to configure proxy in Vite?","tags":["http-proxy","vuejs3","vite"],"text":"Title: How to configure proxy in Vite?\nTags: http-proxy, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI was trying to the docs and created `vite.config.js` like this:\n\n```\nconst config = {\n outDir: '../wwwroot/',\n proxy: {\n // string shorthand\n '/foo': 'http://localhost:4567',\n // with options\n '/api': {\n target: 'http://jsonplaceholder.typicode.com',\n changeOrigin: true,\n rewrite: path => path.replace(/^\\/api/, '')\n }\n }\n};\n\nexport default config;\n```\n\nAnd tried to test it with following calls:\n\n```\nfetch('/foo');\nfetch('/api/test/get');\n```\n\nI was expecting to have actual requests as `http://localhost:4567/foo` and `http://jsonplaceholder.typicode.com/test/get`\nBut both of them had my dev server as an origin like this: `http://localhost:3000/foo` and `http://localhost:3000/api/test/get`\n\nDid I misunderstand it? How proxies should work?\n\nI also created an issue in the Vite repo but it was closed and I did not understand the closing comment.\n\n========================================\n\nTop Answer:\nFor **debugging** I highly recommend to **add event listeners to the proxy**, so you can see how the requests are transformed, if they hit the target server, and what is returned.\n\n```\nexport default {\n server: {\n proxy: {\n '/api': {\n target: 'https://localhost:44305',\n changeOrigin: true,\n secure: false, \n ws: true,\n configure: (proxy, _options) => {\n proxy.on('error', (err, _req, _res) => {\n console.log('proxy error', err);\n });\n proxy.on('proxyReq', (proxyReq, req, _res) => {\n console.log('Sending Request to the Target:', req.method, req.url);\n });\n proxy.on('proxyRes', (proxyRes, req, _res) => {\n console.log('Received Response from the Target:', proxyRes.statusCode, req.url);\n });\n },\n }\n }\n }\n};\n```\n\n`proxy` will be an instance of 'http-proxy',\nPlease see for further info https://github.com/http-party/node-http-proxy#options\n\n========================================\n\nCode:\n```text\nconst config = {\n  outDir: '../wwwroot/',\n  proxy: {\n    // string shorthand\n    '/foo': 'http://localhost:4567',\n    // with options\n    '/api': {\n      target: 'http://jsonplaceholder.typicode.com',\n      changeOrigin: true,\n      rewrite: path => path.replace(/^\\/api/, '')\n    }\n  }\n};\n\nexport default config;\n```\n\n```text\nfetch('/foo');\nfetch('/api/test/get');\n```\n\n```text\nvite.config.js\n```\n\n```text\nhttp://localhost:4567/foo\n```\n\n```text\nhttp://jsonplaceholder.typicode.com/test/get\n```\n\n```text\nhttp://localhost:3000/foo\n```\n\n```text\nhttp://localhost:3000/api/test/get\n```\n\n```js\nproxy: {\n      '/api': {\n           target: 'https://localhost:44305',\n           changeOrigin: true,\n           secure: false,      \n           ws: true,\n       }\n  }\n```\n\n```js\nexport default defineConfig({\n  server: {\n    proxy: {\n      '/foo': 'http://localhost:4567',\n      '/api': {\n        target: 'http://jsonplaceholder.typicode.com',\n        changeOrigin: true,\n        secure: false,\n      },\n    },\n  },\n  // some other configuration\n})\n```\n\n```text\nsecure\n```\n\n```text\nexport default defineConfig({\n  server: {\n    proxy: {\n      \"/api\": {\n        target: \"https://your-remote-domain.com\",\n        changeOrigin: true,\n        secure: false,\n      },\n    },\n  },\n  // some other configuration\n})\n```\n\n```text\nserver -> proxy\n```\n\n```text\nvite.config.js\n```\n\n```text\nexport default {\n  server: {\n    proxy: {\n        '/api': {\n          target: 'https://localhost:44305',\n          changeOrigin: true,\n          secure: false,      \n          ws: true,\n          configure: (proxy, _options) => {\n            proxy.on('error', (err, _req, _res) => {\n              console.log('proxy error', err);\n            });\n            proxy.on('proxyReq', (proxyReq, req, _res) => {\n              console.log('Sending Request to the Target:', req.method, req.url);\n            });\n            proxy.on('proxyRes', (proxyRes, req, _res) => {\n              console.log('Received Response from the Target:', proxyRes.statusCode, req.url);\n            });\n          },\n        }\n      }\n  }\n};\n```\n\n```text\nproxy\n```\n\n```text\n'/api' : {target: 'https://localhost:44305'}\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\nexport default defineConfig({\n  server: {\n    proxy: {\n      '/api':'http://localhost:5000',\n    },\n  },\n  plugins: [react()],\n});\n```\n\n```text\nexport default defineConfig({\n  plugins: [vue()],\n  server: {\n   port: 8080,\n   proxy:{\n   '/posts': 'https://jsonplaceholder.typicode.com'\n   }\n  }\n```\n\n```text\n// App Axios: /foo/people\n// Response From: https://www.swapi.tech/api/people  \n\nserver: {\n      port: PORT,\n      proxy: {\n        \"/foo\": {\n          target: \"https://www.swapi.tech/api\",\n          changeOrigin: true,\n          secure: true,\n          rewrite: (path) => path.replace(/^\\/foo/, \"\"),\n        },\n      },\n    },\n```\n\n========================================\n\nComments:\n- The client (browser or whatever) always requests from localhost:3000, so all your fetches will go to localhost:3000. Then your server (which runs on localhost:3000) will delegate the calls of '/foo' and '/api/...' to the provided urls and delegate their answer to your client. From the point of view of the client, the request targets localhost:3000 and from that url it also receives the response.\n- Does this only work in development? What would be the alternative for achieving exactly the same behaviour but in production?\n- @FalconStakepool In production, have a proxy server like nginx or AWS ALB in front to handle serving some traffic to the frontend and other traffic elsewhere\n- The second route needs the path rewrite, otherwise nothing get's rendered (at least for me). From the docs: `rewrite: (path) => path.replace(&#47;^\\&#47;api&#47;, '')`\n- also see here: vite.dev/config/server-options#server-proxy\n- Where do I specify the logging and how?\n- Where do these logs actually go? I don't see anything in the console\n- The go into the standard console. Does the search path/regex in the first line (the '/api') match? Probably it doesn't so the whole block doesn't get called, hence no console message.\n- Thanks for the tip, was brilliant! On top of that, in this proxy can also override headers returned by the server, so you can skip ContentSecurePolicies, and force cookies \"set by the server\" by SetCookie, etc with `res.setHeader(key, value)`\n- @Marcosaurios I never thought about overriding headers this way, thanks for this awesome feedback!\n- @user2138149 if you are running in visual studio the logs will not print out in visual studios output console like i was expecting. I thought the logs were not working. Instead the logs will print out in the command window that VS launches and this window often launches behind visual studio. I did not see until 4 hours into troubleshooting this proxy and just thought the proxy was not working at all the entire time.\n- @user2138149 thanks for this useful hint! I'm running my applications usually in the console or in VSCode, there it's immediately visible.\n- That's why you use the rewrite field: rewrite: (path) => path.replace(/^\\/api/, ''), vite.dev/config/server-options.html#server-proxy\n- Restart your server with provided port number. if issues persists then reload the page\n- Thank you for your interest in contributing to the Stack Overflow community. This question already has a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? **If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient.** Can you kindly edit your answer to offer an explanation?\n- I reckon this works with the latest version of Vite. I used this while connecting to a NodeJS server. Thanks!\n- That's also working for me, thank you! When using the fetch API, if you perform a fetch('/foo/my/nice/endpoint/',{...}) from your component it calls the swapi.tech/api/my/nice/endpoint","metadata":{"transformedAt":"2026-08-18T18:33:46.389Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":268,"estimatedTokens":2000}}12{"id":"stack-67194082","source":"stackoverflow","questionId":67194082,"title":"How can I display the current app version from package.json to the user using Vite?","tags":["npm","package.json","vite"],"text":"Title: How can I display the current app version from package.json to the user using Vite?\nTags: npm, package.json, vite\nSource: Stack Overflow\n\nQuestion:\nWith create-react-app one could use `process.env.REACT_APP_VERSION` for this.\n\nIs there an equivalent in Vite?\n\n========================================\n\nTop Answer:\n### For React & TypeScript users:\n\nAdd a `define` to your `vite.config.ts`:\n\n```\nimport react from '@vitejs/plugin-react';\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n plugins: [react()],\n define: {\n APP_VERSION: JSON.stringify(process.env.npm_package_version),\n },\n});\n```\n\nIf you haven't got one already, define a `vite-env.d.ts` or `env.d.ts` and add a `declare`:\n\n```\ndeclare const APP_VERSION: string;\n```\n\nYou'll now be able to use the variable `APP_VERSION` anywhere in your code & Vite will substitute it at compile time.\n\n**Note:** You may need to restart your TS server for the declaration to be picked up by intellisense:\n\nVSCode MacOS: ⌘ + ⇧ + P `> Restart TS Server`\n\nVSCode Windows: ctrl + ⇧ + P `> Restart TS Server`\n\n========================================\n\nCode:\n```text\nprocess.env.REACT_APP_VERSION\n```\n\n```js\nexport default {\n    plugins: [vue()],\n    define: {\n        '__APP_VERSION__': JSON.stringify(process.env.npm_package_version),\n    }\n}\n```\n\n```html\n<script setup>\n// can't be used directly on the template\nconst version = __APP_VERSION__\n</script>\n<template>\n    <div>{{ version }}</div>\n</template>\n```\n\n```text\ndeclare const __APP_VERSION__: string\n```\n\n```text\ndefine\n```\n\n```text\nvite.config.js\n```\n\n```text\n'__APP_VERSION__'\n```\n\n```text\nenv.d.ts\n```\n\n```text\nvite-env.d.ts\n```\n\n```js\n// vite.config.js\nimport loadVersion from 'vite-plugin-package-version';\n\nexport default {\n  plugins: [loadVersion()],\n};\n```\n\n```text\ndefine\n```\n\n```js\nimport react from '@vitejs/plugin-react';\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n  plugins: [react()],\n  define: {\n    APP_VERSION: JSON.stringify(process.env.npm_package_version),\n  },\n});\n```\n\n```text\ndeclare const APP_VERSION: string;\n```\n\n```text\ndefine\n```\n\n```text\nvite.config.ts\n```\n\n```text\nvite-env.d.ts\n```\n\n```text\nenv.d.ts\n```\n\n```text\ndeclare\n```\n\n```text\nAPP_VERSION\n```\n\n```text\n> Restart TS Server\n```\n\n```text\n> Restart TS Server\n```\n\n```js\nimport { version } from '@/../package.json'\n```\n\n```text\nexport default defineConfig({\n  // ...\n  resolve: {\n    // ...\n    alias: {\n      '@': resolve(__dirname, 'src'),\n    },\n  },\n}\n```\n\n```js\nimport { defineConfig } from 'vite';\nconst increasePackageVersion = () => {\n    try {\n        const fs = require('fs');\n        const path = require('path');\n        const packageFilePath = path.join(__dirname, 'package.json');\n        const packageJson = JSON.parse(fs.readFileSync(packageFilePath, 'utf8'));\n        packageJson.version = packageJson.version.replace(/(\\d+)$/, (match, p1) => {\n            return parseInt(p1) + 1;\n        }\n        );\n        fs.writeFileSync(packageFilePath, JSON.stringify(packageJson, null, 2));\n        console.log('New version is', packageJson.version);\n    } catch (error) {\n        console.log('Error in increasePackageVersion', error);\n    }\n\n};\n\nexport default defineConfig({\n    build: {\n        lib: {\n            entry: 'src/main.js',\n            formats: ['es']\n        }\n    },\n    plugins: [\n    increasePackageVersion()],\n    define: {\n        '__APP_VERSION__': JSON.stringify(process.env.npm_package_version),\n    }\n});\n```\n\n```js\nconsole.log(__APP_VERSION__);\n```\n\n```text\npackage.json\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport packageJson from './package.json';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  define:  {\n    'import.meta.env.PACKAGE_VERSION': JSON.stringify(packageJson.version)\n  }\n})\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Node\",\n    \"allowSyntheticDefaultImports\": true,\n    \"resolveJsonModule\": true\n  },\n  \"include\": [\"vite.config.ts\", \"./package.json\"]\n}\n```\n\n```ts\ninterface ImportMetaEnv {\n    readonly PACKAGE_VERSION: string;\n    // more env variables...\n}\n  \ninterface ImportMeta {\n    readonly env: ImportMetaEnv\n}\n```\n\n```text\npackage.json\n```\n\n```text\nvite.config.ts\n```\n\n```text\nPACKAGE_VERSION\n```\n\n```text\n\"resolveJsonModule\": true\n```\n\n```text\ntsconfig.node.json\n```\n\n```text\n\"./package.json\"\n```\n\n```text\ntsconfig.node.json\n```\n\n```text\nPACKAGE_VERSION\n```\n\n```text\nvite-env.d.ts\n```\n\n```text\n{import.meta.env.PACKAGE_VERSION}\n```\n\n```text\n// .env\nVITE_REACT_APP_VERSION=$npm_package_version\n```\n\n```text\n// App.jsx\n...\nconsole.log('ver. ', import.meta.env.VITE_REACT_APP_VERSION)\n...\n```\n\n```js\nexport default defineConfig({\n  define: {\n    `config.version`: JSON.stringify('my-custom-name')\n  }\n})\n```\n\n```js\ndeclare var config: any;\n```\n\n```js\nconst { version } = config;\n```\n\n```text\nvite.config.ts\n```\n\n```text\nsrc/vite-env.d.ts\n```\n\n```text\nVITE_VERSION=${npm_package_version}\n```\n\n```text\nimport.meta.env.VITE_VERSION\n```\n\n```json\n{\n  \"name\": \"your-package-name\",\n  \"version\": \"0.1.0\",\n  ....\n  \"scripts\": {\n    ...\n    \"version\": \"echo $npm_package_version\",\n    \"dev\": \"VITE_APP_VERSION=$(yarn run version) vite --port=4000\",\n    \"build\": \"tsc && VITE_APP_VERSION=$(yarn run version) vite build\",\n    \"preview\": \"VITE_APP_VERSION=$(yarn run version) vite preview\",\n    ...\n  }\n}\n```\n\n```js\nconsole.log(import.meta.env.VITE_APP_VERSION)   // 0.1.0\n```\n\n```text\nVITE_VERSION=${npm_package_version}\n```\n\n```text\n.env\n```\n\n```text\n.env\n```\n\n```text\n.env\n```\n\n```text\npackage.json\n```\n\n```text\npackage.json\n```\n\n```text\nyarn\n```\n\n```text\npackage.json\n```\n\n```text\nscripts\n```\n\n```text\n\"version\"\n```\n\n```text\n\"echo $npm_package_version\"\n```\n\n```text\nscripts\n```\n\n```text\nvite\n```\n\n```text\nvite\n```\n\n```text\nVITE_\n```\n\n```text\nVITE_\n```\n\n```text\nversion\n```\n\n```text\n\"dev\": \"vite --port=4000\",\n```\n\n```text\n\"dev\": \"VITE_APP_VERSION=$(yarn run version) vite --port=4000\"\n```\n\n```text\nimport.meta.env.VITE_APP_VERSION\n```\n\n========================================\n\nComments:\n- This question is related to: stackoverflow.com/questions/67707813/&hellip;\n- Do you have an idea how to get this to run with React? I use `plugins: [reactRefresh()],`\n- ok got it, just Typescript arguing about unknown var.\n- @Obiwahn oh sorry, I didn't use react nor ts, my answer is purely for vite & vuejs. It might help others if you also post react version as an answer here. :D\n- This made more sense when I discovered that \"define\" adds properties to the global window object in the browser. So, in the above answer, you can use `window.__APP_VERSION__` in any JavaScript.\n- Works the same in react, just chang the plugin to the reactRefresh plugin\n- does it work after build on production?\n- @DanCZ Yes, I'm using it in all my webapps, using `npm run build`.\n- @ChristhoferNatalius I have tried and it works just on local. how can it work when package.json is not deployed? I am using Vue and Vite in my project.\n- @DanCZ package.json is not deployed. You just run `npm run build`, and deploy the output (by default it's the `dist` folder). Can you setup a reproduction repo so I can take a look?\n- I'm not even sure \"JSON.stringify\" is needed here, unless you're worried somebody might define npm_package_version in some very strange form. :)\n- @tekHedd so am I. I don't remember if I have tested it without json.stringify or not, but the official Vite docs use it, so I use it as well.\n- In the end the plugin is also using a define\n- This is no longer working for production build. Neither will the define way work.\n- @SworupShakya do you know why this won't work using define?\n- The documentation about the define option can be found on vitejs.dev/config/#define. It suggests to put the Typescript declaration into a file named `env.d.ts` or `vite-env.d.ts`\n- This works! Thanks for the fix. It's always tricky when a TS error hits you out of nowhere\n- Is this specific to React? It seems like this should work with other frameworks and JS too, since `process.env.npm_package_version` is part of npm.\n- Do you also include a timestamp? I was thinking where that could be read from\n- This might lead to security risk as stated stackoverflow.com/q/70298948/3671954 and stackoverflow.com/q/64993118/3671954\n- This doesn't work after application is built. It works only in `DEV` mode.\n- @ChristhoferNatalius Security risk is about `import * as packageInfo from '..&#47;..&#47;package.json'; version: packageInfo.version`, not about my answer.\n- @BranislavPopadič I does not use mode, but it worked for me at production environment after vite build.\n- Don't import your package.json, you will expose all content from your package.json file.\n- awesome, this is really the one i care about\n- do you know how i would only run this on yarn build? i notice it also runs for yarn serve\n- npm/yarn has cli commands that do exactly what your custom function: docs.npmjs.com/cli/v9/commands/npm-version classic.yarnpkg.com/lang/en/docs/cli/version\n- how do you access `__APP_VERSION__` in a vue file? `console.log(__APP_VERSION__)` gave `error TS2304: Cannot find name '__APP_VERSION__'.`\n- This step-by-step guide is 100% complete and worked for me in the first try. Love it.\n- This solution works in both development and after the build process. The other approaches only worked for me during local development, after the build PACKAGE_VERSION was undefined. Thank you.\n- Wow. It's a magic!\n- Nice, so apparently the `npm_package_*` environment variables are automatically generated by npm based on the values specified in your project's `package.json` file (for example `$npm_package_name`, `$npm_package_version`). However I didn't find any documentation about this. If someone has any resources, please add it here.\n- The variables are created by NPM when the \"scripts\" are run. See docs.npmjs.com/cli/v10/using-npm/scripts#packagejson-vars","metadata":{"transformedAt":"2026-08-18T18:33:46.389Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":70,"totalLines":470,"estimatedTokens":2494}}13{"id":"stack-75746767","source":"stackoverflow","questionId":75746767,"title":"Is there any bundle analyzer for vite?","tags":["vite"],"text":"Title: Is there any bundle analyzer for vite?\nTags: vite\nSource: Stack Overflow\n\nQuestion:\nWe developed an app in vite and I want to analyze the bundle of app, I found rollup-plugin-analyzer but it did not work for me.\n\n========================================\n\nTop Answer:\nAlternatively, you can use `vite-bundle-visualizer`, which uses `rollup-plugin-visualizer`:\n\n```\nnpx vite-bundle-visualizer\n```\n\n### Usage\n\n```\n# In your vite project's root\n$ npx vite-bundle-visualizer\n# Then open stats.html in browser\n```\n\n```\n$ npx vite-bundle-visualizer --help\n\nvite-bundle-visualizer\n\nUsage:\n $ vite-bundle-visualizer [options]\n\nOptions:\n --template -t Template to use, options are \"raw-data\" (JSON), \"treemap\", \"list\" (YAML), \"sunburst\" and \"network\" (default: treemap)\n --output -o Output file path, should be \"**/*.html\" or \"**/*.json\" (default: /Users/kuss/project/sides/oss/vite-bundle-visualizer/stats.html)\n --open Should open browser after generated, except when template is \"json\" (default: true)\n -h, --help Display this message\n```\n\n### Screenshots\n\n### Visualizer Templates\n\n### Treemap\n\n```\n$ npx vite-bundle-visualizer\n```\n\n### Sunburst\n\n```\n$ npx vite-bundle-visualizer -t sunburst\n```\n\n### Network\n\n```\n$ npx vite-bundle-visualizer -t network\n```\n\n### Raw data\n\nOutput raw data (JSON) of stats\n\n```\n# @deprecated vite-bundle-visualizer -t json\n$ npx vite-bundle-visualizer -t raw-data\n```\n\ndemo/stats.json\n\n========================================\n\nCode:\n```js\nimport { visualizer } from \"rollup-plugin-visualizer\";\n...\nexport default defineConfig({\n  ...\n  plugins: [\n    ...\n    visualizer({\n      template: \"treemap\", // or sunburst\n      open: true,\n      gzipSize: true,\n      brotliSize: true,\n      filename: \"analyse.html\", // will be saved in project's root\n    }) as PluginOption,\n    ...\n  ],\n  ...\n});\n```\n\n```text\nrollup-plugin-visualizer\n```\n\n```bash\nnpx vite-bundle-visualizer\n```\n\n```text\n# In your vite project's root\n$ npx vite-bundle-visualizer\n# Then open stats.html in browser\n```\n\n```text\n$ npx vite-bundle-visualizer --help\n\nvite-bundle-visualizer\n\nUsage:\n  $ vite-bundle-visualizer <command> [options]\n\nOptions:\n  --template -t <template>  Template to use, options are \"raw-data\" (JSON), \"treemap\", \"list\" (YAML), \"sunburst\" and \"network\" (default: treemap)\n  --output -o <filepath>    Output file path, should be \"**/*.html\" or \"**/*.json\" (default: /Users/kuss/project/sides/oss/vite-bundle-visualizer/stats.html)\n  --open <open>             Should open browser after generated, except when template is \"json\" (default: true)\n  -h, --help                Display this message\n```\n\n```text\n$ npx vite-bundle-visualizer\n```\n\n```text\n$ npx vite-bundle-visualizer -t sunburst\n```\n\n```text\n$ npx vite-bundle-visualizer -t network\n```\n\n```text\n# @deprecated vite-bundle-visualizer -t json\n$ npx vite-bundle-visualizer -t raw-data\n```\n\n```text\nvite-bundle-visualizer\n```\n\n```text\nrollup-plugin-visualizer\n```\n\n```bash\n# In your vite project's root\n$ npx vite-bundle-visualizer\n# Then open stats.html in browser\n\n# Use specified vite config file\n$ npx vite-bundle-visualizer -c your.config.js\n```\n\n========================================\n\nComments:\n- + `[yarn|npm run] build` to generate the output\n- The file sizes reported by this plugin are way off the final minified size, which is quite unhelpful. 😕\n- @simon-e You have to run the bundle command. Then the size is correct.\n- @DominicSeel What bundle command is that? Can't see that mentioned in the docs anywhere.\n- Downside of this tool is a horrible filters syntax. It takes like a dozen of slashes and stars mixed in incomprehensible ways to find or exclude a package from view.\n- you meant 'vite-bundle-visualizer' works out of the box for vite?\n- Unfortunately this plugin has the same issue with reported file sizes being way off the final minified file sizes.\n- I released version `0.23.0` yesterday to remove the confusing data. I think it should be simpler to use :)\n- Thank you for suggesting Sonda. This provides far more accurate numbers than the other options listed above. 😊👍\n- FWIW sonda wasn't working for me out of the box just now (June 2025), but vite-bundle-visualizer did work immediately. Looks like a cool project if you can get it up and running though\n- @DebugArnaut Have you enabled the `build.sourcemap` option in Vite? It's the only requirement to make Sonda work, as shown here: sonda.dev/bundlers/vite.html","metadata":{"transformedAt":"2026-08-18T18:33:46.389Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":172,"estimatedTokens":1106}}14{"id":"stack-72618944","source":"stackoverflow","questionId":72618944,"title":"Get error to build my project in Vite - Top-level await is not available in the configured target environment","tags":["typescript","vite"],"text":"Title: Get error to build my project in Vite - Top-level await is not available in the configured target environment\nTags: typescript, vite\nSource: Stack Overflow\n\nQuestion:\nI try to build my project in vite,\n\nmy project - https://github.com/yakovcohen4/starbucks-openlayers\n\nI run `npm run dev` and all work.\n\nbut when I run to build it I get an error.\n\nerror message:\n`Top-level await is not available in the configured target environment (\"chrome87\", \"edge88\", \"es2019\", \"firefox78\", \"safari13.1\")`\n\nI try to fetch a data and think here is the problem\nlink (line 22+23) - https://github.com/yakovcohen4/starbucks-openlayers/blob/main/starbucks-project/src/main.ts\n\n`const shopsData = await fetchStarbucksShops();`\n\nIf anyone encounters this curse I would be happy to help\n\n========================================\n\nTop Answer:\nTop-level-await is a new es feature which wouldn't run in old browsers. If you believe your users use relatively new versions and can handle top-level-await, you can set up vite.config like this:\n\n```\nexport default defineConfig({\n build: {\n target: 'esnext' //browsers can handle the latest ES features\n }\n})\n```\n\nor\n\n```\nexport default defineConfig({\n esbuild: {\n supported: {\n 'top-level-await': true //browsers can handle top-level-await features\n },\n }\n})\n```\n\n========================================\n\nCode:\n```text\nnpm run dev\n```\n\n```text\nTop-level await is not available in the configured target environment (\"chrome87\", \"edge88\", \"es2019\", \"firefox78\", \"safari13.1\")\n```\n\n```text\nconst shopsData = await fetchStarbucksShops();\n```\n\n```js\n// vite.config.js\nexport default defineConfig({\n  optimizeDeps: {\n    esbuildOptions: {\n      target: 'esnext'\n    }\n  },\n  build: {\n    target: 'esnext'\n  },\n  // more config options ...\n})\n```\n\n```text\n(async () => {\n    export const shopsData: shopType[] = await fetchStarbucksShops();\n    export const countryGeoData: countryGeoDataType = await fetchGeoJsonCountry();\n    .\n    .\n    .\n    .\n    .\n     })();\n```\n\n```text\nawait\n```\n\n```text\nawait\n```\n\n```text\nasync\n```\n\n```text\n.then()\n```\n\n```text\nexport default defineConfig({\n  build: {\n    target: 'esnext' //browsers can handle the latest ES features\n  }\n})\n```\n\n```text\nexport default defineConfig({\n  esbuild: {\n    supported: {\n      'top-level-await': true //browsers can handle top-level-await features\n    },\n  }\n})\n```\n\n```js\nexport default defineConfig({\n  esbuild: {\n    supported: {\n      'top-level-await': true\n    },\n  },\n});\n```\n\n```js\nexport default defineConfig({\n  optimizeDeps: {\n    include: [\"pdfjs-dist\"], // optionally specify dependency name\n    esbuildOptions: {\n      supported: {\n        \"top-level-await\": true\n      },\n    },\n  },\n});\n```\n\n```text\ntop-level await\n```\n\n```text\nvite.config.js\n```\n\n```text\nvite.config.ts\n```\n\n```text\nvite.config.js\n```\n\n```text\nvite.config.ts\n```\n\n```text\npdfjs-dist\n```\n\n```text\n{\n  build: {\n    target: \"es2022\"\n  },\n  esbuild: {\n    target: \"es2022\"\n  },\n  optimizeDeps:{\n    esbuildOptions: {\n      target: \"es2022\",\n    }\n  }\n}\n```\n\n========================================\n\nComments:\n- Hi. I hope one of the response answered your question. If it did, could you please mark it as the accepted answer? Thanks!\n- @ForcedFakeLaugh Hi, i marked the response that works for me. and this is my code `export default defineConfig({base: '.&#47;', build: { target: 'esnext'}, });`\n- Thank you very much, in the end, I saw this repo and it helps me ... (thank you for your answer)\n- I prefer setting `supported` features so that I can see other potential errors if they arise in future. `esnext` is not a fixed version. See my answer for how to target a specific dependency too.\n- Can someone help me understand why this worked please? I already had lib: { formats: 'esnext' }, but adding this option was the only thing that made it work. Is it because it asserts to esbuild to just use top level await, and the formats option does not?\n- I prefer to use `target: 'es2022'` as that's the oldest target that will work. Source: en.wikipedia.org/wiki/&hellip;\n- This solved the problem for me. \"@vitejs/plugin-vue\": \"^5.0.2\",\"vite\": \"^5.0.11\"\n- Adding `esbuildOptions: { target: 'esnext' }` to `optimizeDeps` was the fix for me. Tried other variations of `build` and `esbuild` target settings but it was this one that fixed it.\n- Same as above comments\n- If this is a new \"vite.config.js\" file you will probably need \"import { defineConfig } from 'vite'\" as your first line, otherwise you'll get \"ReferenceError: defineConfig is not defined\" when you run \"npx vite build\"","metadata":{"transformedAt":"2026-08-18T18:33:46.389Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":200,"estimatedTokens":1141}}15{"id":"stack-70309561","source":"stackoverflow","questionId":70309561,"title":"Unable to import SVG with Vite as ReactComponent","tags":["reactjs","typescript","vite"],"text":"Title: Unable to import SVG with Vite as ReactComponent\nTags: reactjs, typescript, vite\nSource: Stack Overflow\n\nQuestion:\nTried to use this library: vite-plugin-react-svg\n\nand had no success by importing it like:\n\n```\nimport { ExternalLink } from 'assets/svg/link-external.svg?component';\n```\n\nAre there any workarounds for this issue?\n\nThe error i got before was the following:\n\n```\nimport { ReactComponent as ExternalLink } from 'assets/svg/link-external.svg';\n\n//Uncaught SyntaxError: \n The requested module '/src/assets/svg/link-external.svg?import'\n does not provide an export named 'ReactComponent'\n```\n\n========================================\n\nTop Answer:\n### Update September 2025 - `vite-plugin-svgr` version ^4.0.0\n\nWhen importing your SVG file using `vite-plugin-svgr` (see below), make sure to use the newly added `?react` query suffix on your imported file, which allows you to use the default export and skip the `ReactComponent` aliasing:\n\n```\nimport ReactLogo from './assets/react.svg?react'\n\n```\n\nIf you're using TypeScript, you'll also need to add the following at the *very top* of your file (before the `import` statements):\n\n```\n/// \n```\n\n### \n\n### Instructions\n\n- Install `vite-plugin-svgr` to add `SVGR` to the project:\n\n```\nnpm install vite-plugin-svgr\nyarn add vite-plugin-svgr\n```\n\n- Register the plugin `SVGR` to vite in `vite.config.js`\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport svgr from 'vite-plugin-svgr' \n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n react(), \n svgr({ \n svgrOptions: {\n // svgr options\n },\n }),\n ], \n})\n```\n\n- **Prior 2023 - plugin ~v3.x**: In `App.tsx` import SVG as React Component :\n\n```\nimport { ReactComponent as ReactLogo } from './assets/react.svg'\n\n```\n\nNotes:\n\n- Tested on sept. 2025 on vite v7.x & plugin v.4.5.0\n\nReferences:\n\n- Learn more about **SVGR** at https://react-svgr.com/docs/ecosystem/#articles\n\n- plugin options\n\n- list of SVGR options that can be added to `svgrOptions:{}`:\n\nBonus:\n\n- Dynamic SVG component by *Amit Mondal*\n\n========================================\n\nCode:\n```text\nimport { ExternalLink } from 'assets/svg/link-external.svg?component';\n```\n\n```text\nimport { ReactComponent as ExternalLink } from 'assets/svg/link-external.svg';\n\n//Uncaught SyntaxError: \n  The requested module '/src/assets/svg/link-external.svg?import'\n  does not provide an export named 'ReactComponent'\n```\n\n```text\nimport { ReactComponent as Logo } from './logo.svg'\n```\n\n```js\nimport ReactLogo from './assets/react.svg?react'\n\n<ReactLogo />\n```\n\n```js\n/// <reference types=\"vite-plugin-svgr/client\" />\n```\n\n```bash\nnpm install vite-plugin-svgr\nyarn add vite-plugin-svgr\n```\n\n```ts\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport svgr from 'vite-plugin-svgr' \n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    react(), \n    svgr({ \n      svgrOptions: {\n        // svgr options\n      },\n    }),\n  ], \n})\n```\n\n```js\nimport { ReactComponent as ReactLogo } from './assets/react.svg'\n\n<ReactLogo />\n```\n\n```text\nvite-plugin-svgr\n```\n\n```text\nvite-plugin-svgr\n```\n\n```text\n?react\n```\n\n```text\nReactComponent\n```\n\n```text\nimport\n```\n\n```text\nvite-plugin-svgr\n```\n\n```text\nSVGR\n```\n\n```text\nSVGR\n```\n\n```text\nvite.config.js\n```\n\n```text\nApp.tsx\n```\n\n```text\nsvgrOptions:{}\n```\n\n```text\nimport logo from \"./logo-login.svg\"\n<img src={logo} className=\"w-24 inline-block\" alt=\"logo\" />\n```\n\n```text\n// vite.config.js\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport svgr from 'vite-plugin-svgr'; // make sure to import it\n\nexport default defineConfig({\n    plugins: [react(), svgr()],\n});\n\n// App.jsx\nimport {ReactComponent as ExternalLink} from './assets/svg/link-external.svg';\n\n<ExternalLink />\n```\n\n```text\nnpm i vite-plugin-svgr\n```\n\n```bash\nnpm install @svgr/rollup -D\n```\n\n```js\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport svgr from '@svgr/rollup';\n\nexport default defineConfig({\n  plugins: [react(), svgr()]\n});\n```\n\n```text\n@svgr/rollup\n```\n\n```text\nvite-plugin-svgr\n```\n\n```text\nvite-plugin-svgr\n```\n\n```text\nsvgo\n```\n\n```text\nesbuild\n```\n\n```text\nvite-plugin-svgr\n```\n\n```text\nsvgo\n```\n\n```text\n// vite.config.js\nimport svgr from 'vite-plugin-svgr'\n\nexport default {\n  plugins: [svgr()],\n}\n```\n\n```js\nimport { ReactComponent as Logo } from './logo.svg'\n```\n\n```js\nsvgr({\n  exportAsDefault: true\n})\n```\n\n```js\n// now you can import as default\nimport Logo from './logo.svg'\n```\n\n```js\n/// <reference types=\"vite-plugin-svgr/client\" />\n```\n\n```text\nyarn add -D vite-plugin-svgr\n```\n\n```text\nvite.config.js\n```\n\n```text\n\"types\": [\"vite/client\"],\n```\n\n```text\nnpm i @svgx/vite-plugin-react\n```\n\n```js\nimport { defineConfig } from \"vite\";\nimport svgx from \"@svgx/vite-plugin-react\";\n\nexport default defineConfig(async () => {\n  return {\n    plugins: [\n      svgx()\n    ],\n  };\n});\n```\n\n```js\nimport MyIcon from \"./icon.svg?component\";\n```\n\n```js\nimport importVars from \"@svgx-dir:/path/to/directory\";\n\nexport default function (props) {\n  const MyIcon = importVars(props.iconName);\n  return (\n    <div>\n      <MyIcon color=\"#FF5733\" />\n    </div>\n  );\n}\n```\n\n```text\n@svgx/vite-plugin-react\n```\n\n```js\n/// <reference types=\"vite/client\" />\n```\n\n```text\nsrc\n```\n\n```text\ndeclare module '*.svg?react' {\n    import React = require('react');\n    export const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;\n    const src: string;\n    export default src;\n}\n```\n\n```text\n\"include\": [\"src\", \"custom.d.ts\"],`\n```\n\n```text\nimport MyIcon from \"/src/components/icons/MyIcon.svg?react\";\n\n<MyIcon/>\n```\n\n```text\nvite-plugin-svgr\n```\n\n```text\nvite.config.js\n```\n\n```text\ncustom.d.ts\n```\n\n```text\ninclude\n```\n\n```text\ntsconfig.json\n```\n\n```text\nimport Logo from './logo.svg?react'\n```\n\n```text\n// vite.config.js\n\nimport svgr from \"vite-plugin-svgr\";\n\nexport default {\n\n  // ...\n\n  plugins: [svgr()],\n\n};\n```\n\n```text\n?react\n```\n\n```text\n{\n    ...\n    \"devDependencies\": {\n        ...\n        \"@vitejs/plugin-react\": \"^4.2.0\",\n        \"vite-plugin-svgr\": \"^4.2.0\"\n    }\n}\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport svgr from \"vite-plugin-svgr\";\n\n// https://vitejs.dev/config/\nexport default defineConfig(\n    {\n        ...\n        plugins: [\n            react(), \n            svgr()\n        ]\n    }\n)\n```\n\n```text\n/// <reference types=\"vite-plugin-svgr/client\" />\n```\n\n```text\nimport MyImage from \"../some/path/MyImage.svg?react\";\n```\n\n```text\n*.svg?react\n```\n\n```text\ntsc\n```\n\n```text\nimport\n```\n\n```text\ntsc\n```\n\n```text\ntsc\n```\n\n```text\n@types\n```\n\n```text\n<reference>\n```\n\n```text\n.tsx\n```\n\n```text\n?react\n```\n\n```text\n<MyImage />\n```\n\n```text\nvite-plugin-react-rich-svg\n```\n\n```text\n\"data:image/svg+xml;...\"\n```\n\n```text\nnpm i vite-plugin-svgr\n```\n\n```text\nimport AnyName from '../../assets/svgs/icon.svg?react';\n```\n\n```text\n<AnyName />\n```\n\n```text\nexport default defineConfig({\n  // ...\n  plugins: [\n    // ...\n    svgr({\n      svgrOptions: { exportType: 'named', ref: true, svgo: false, titleProp: true },\n      include: '**/*.svg',\n    }),\n    // ...\n  ],\n  // ...\n});\n```\n\n```text\nimport { makeStyles } from 'react-components-ts';\nimport Bg from '@assets/factoring/bg.svg';\nimport BgMobile from '@assets/factoring/bgMobile.svg';\n\nexport const useStyles = makeStyles()(({ spacing, breakpoints }) => ({\n  paper: {\n    height: '100%',\n    overflowX: 'hidden',\n    position: 'relative',\n  },\n  headerBackground: {\n    background: `url(\"${Bg}\") 100% 0% no-repeat`,\n    [breakpoints.down('xs')]: {\n      background: `url(\"${BgMobile}\") 100% 0% no-repeat`,\n    },\n  },\n  headerContainer: {\n    padding: spacing(3),\n  },\n  mainContainer: {\n    padding: spacing(3),\n    borderBottom: '1px solid #EDF0F2',\n  },\n  mainText: {\n    padding: spacing(3),\n    marginTop: spacing(5),\n    marginBottom: spacing(5),\n    [breakpoints.down('sm')]: {\n      marginTop: spacing(25),\n    },\n  },\n  mainTextMobile: {\n    [breakpoints.down('sm')]: {\n      fontSize: spacing(3),\n    },\n  },\n  title: {\n    color: '#262261',\n  },\n}));\n\nexport default useStyles;\n```\n\n```js\nimport ExternalLink from 'assets/svg/link-external.svg';\n```\n\n```bash\nnpm install vite-plugin-svgr\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport svgrPlugin from 'vite-plugin-svgr'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    react(),\n    svgrPlugin({\n      include: '**/*.svg',\n      svgrOptions: {\n        exportType: 'default',\n      },\n    }),\n  ],\n})\n```\n\n```text\n{ ReactComponent as ExternalLink }\n```\n\n```text\nExternalLink\n```\n\n```text\nvite.config.js\n```\n\n```text\nnpm install --save-dev vite-plugin-svgr\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport svgr from \"vite-plugin-svgr\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react(), svgr()],\n});\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"types\": [\"vite-plugin-svgr/client\"]\n  }\n}\n```\n\n```text\nimport Logo from \"assets/images/logo.svg?react\";\n\nfunction App() {\n  return (\n    <div>\n      <Logo color='red' />\n    </div>\n  );\n}\n\nexport default App;\n```\n\n```text\nvite-plugin-svgr\n```\n\n```text\nvite.config.ts\n```\n\n```text\ntsconfig.app.json\n```\n\n```text\n?react\n```\n\n```text\ndeclare module '*.svg' {   \n  const content: React.FC<React.SVGProps<SVGElement>>   \n  export default content \n}\n```\n\n```text\n/// <reference types=\"./vite-env-override.d.ts\" /> \n/// <reference types=\"vite/client\" />\n```\n\n```text\nimport Logo from \"/logo.svg\"\n\nconst Comp= () => (\n<div>\nas img\n\n  <img src={Logo} />\n\nor  as div (with ability to change stroke color with css)\n\n   <div style={{mask:`url(\"${Logo}\")`}} />\n\n</div>\n)\n```\n\n```js\n// App.tsx\nimport ExternalLink from 'assets/svg/link-external.svg?react';\n\nconst App: React.FC = () => {\n  return <ExternalLink />;\n};\n```\n\n```js\n//vite.config.ts\n\n/// <reference types=\"vite-plugin-svgr/client\" />\nimport react from '@vitejs/plugin-react';\nimport { defineConfig } from 'vite';\nimport svgr from 'vite-plugin-svgr';\n\nexport default defineConfig({\n  plugins: [react(), svgr()],\n});\n```\n\n```text\nimport { ReactComponent as ExternalLink } from 'assets/svg/link-external.svg';\n```\n\n========================================\n\nComments:\n- While the proposed specific plugin version didn't work me, this one did: `yarn add -D vite-plugin-svgr`, combined with this syntax: `import { ReactComponent as Happy } from '.&#47;assets&#47;svg&#47;happy.svg'`. This practically emulates how react-scripts does it, and might be useful for anyone migrating from react-scripts to vite.\n- @miek no luck with either, and my approach in the answer below\n- Careful of this above answer... the `@honkhonk` seems to be an archived fork. Best to take from the official source: npmjs.com/package/vite-plugin-svgr\n- I'm going to insist that people actually **run their code** before psoting here. The syntax `svgr({ svgrOptions({ &#47;&#47; svgr options }), })`, (here in one line) is worng! Not only `svgrOptions` is not a function, but also you can't just open `{}`s and dump stuff inside like it's a Python set, or something. What you wanted to say was `svgr({ svgrOptions: { &#47;&#47; svgr options }, })`.\n- I actually could not use this as the IDE complained about the `?react` part (and it seems ugly), so I just added the path to the include options: `svgr({ include: '**&#47;*.svg' })`\n- can also add ``` /// ``` to `vite-env.d.ts` file to get rid of the ts cannot find module error when using new `?react`\n- If you don't use ?react at the end and do a custom pattern like I did, then the type does not works. I had to change it back.\n- For me, it works with `svgr({include: '**&#47;*.svg', svgrOptions: {exportType: 'default'}})` for options\n- This may not work if you are testing nested components such that `vitest` needs to handle `ReactComponent` imports. In that case, use `exportType: 'named'` in your `svgrOptions`. Ideally, @flydev, we could add this to your answer.\n- Thanks. Best answer for working with SVGs in the same way as CRA. Worked like a charm with styled-components.\n- Why this is not the accepted answer is unexplainable. Please refer to my comment in the... *accepted* answer for why that's wrong and yours points into the right direction.\n- In my case the use of ReactComponent did not work. However when using the notation from the docs it worked without problems: vitejs.dev/guide/assets.html Might have been changed recently?\n- Thanks. I just the guide. `vite-plugin-svgr@^3.2.0` works for me but @4.xx doesn't work.\n- but then it's no React component so not at all helpful to answer OPs question\n- From the link you provided, it looks like it now *does* work with `svgo` ... you just \"also need to add @svgr/plugin-jsx\".\n- maybe, you can try it.\n- 2024 - With Storybook 8.0.8 this is what worked for me! ```` import { ReactComponent as LogoImage } from '../../assets/DefaultDefaultDefault.svg'; const StyledLogo = styled(LogoImage)` --color-1: var(--color-1, #28D2CF); --color-2: var(--color-2, #0F1533); `; ````\n- very helpful, thanks.\n- Woo, learning about `exportAsDefault` saved me after an hour of searching. Note that `exportAsDefault` only exists in `vite-plugin-svgr` version `3.x.x` or lower. I couldn't find any equivalent option for version `4.x.x`\n- It seems in 4.x you can just export the SVG directly without casting to a `ReactComponent`\n- Adding `types` to the config is slightly different in v4 of vite. Check the docs here.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- Thanks, Every other solution I tried wasn't working in an Astro project. The dynamic import is neat!\n- Thanks for your answer. i also been able to import SVG's in vite without using external packages, maybe they patched it.\n- Thanks, it helped to fix TS error 'Cannot find module...' while importing via {path}.svg?react\n- But TS started to throw errors that I'm adding className to because type is string. To fix this I removed the line: const src: string. And changed last line to export default ReactComponent\n- thank you! in my case I had to changed the exportType to \"default\"\n- Great answer! The only correct one!\n- This is the only way it worked for me with 4+ version.\n- If i want both named and default as exportType what we have to do?\n- This helped me out!\n- The problem is the `svgr()` or `svgrPlugin()` returns `Plugin`, resulting in `Unsafe call of an 'any' typed value`.\n- works for: \"vite-plugin-svgr\": \"^4.5.0\" \"vite\": \"^7.2.2\", \"typescript\": \"~5.9.3\", thank you\n- The question is about inlining the svg as a React component, not about using the assets pipeline.","metadata":{"transformedAt":"2026-08-18T18:33:46.389Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":98,"totalLines":753,"estimatedTokens":3735}}16{"id":"stack-77249074","source":"stackoverflow","questionId":77249074,"title":"How do I use Typescript path aliases in Vite?","tags":["typescript","vite"],"text":"Title: How do I use Typescript path aliases in Vite?\nTags: typescript, vite\nSource: Stack Overflow\n\nQuestion:\nHow do I set up and use typescript path aliases like `@/shared/types` in a Vite project? I'm getting this error: `Failed to resolve import \"@/shared/types\"`\n\nHere's a part of my `tsconfig.json`:\n\n```\n\"compilerOptions\": {\n \"baseUrl\": \"../\",\n \"paths\": {\n \"@/*\": [\"./*\"]\n }\n }\n```\n\n========================================\n\nTop Answer:\nThere's a plugin for that: `vite-tsconfig-paths`. You run\n\n```\nnpm install --save-dev vite-tsconfig-paths\n```\n\nand import it in your `vite.config`:\n\n```\n// ...\nimport tsconfigPaths from 'vite-tsconfig-paths';\n\nexport default defineConfig({\n plugins: [tsconfigPaths()],\n});\n```\n\nhttps://www.npmjs.com/package/vite-tsconfig-paths\n\n========================================\n\nCode:\n```text\n\"compilerOptions\": {\n    \"baseUrl\": \"../\",\n    \"paths\": {\n      \"@/*\": [\"./*\"]\n    }\n  }\n```\n\n```text\n@/shared/types\n```\n\n```text\nFailed to resolve import \"@/shared/types\"\n```\n\n```text\ntsconfig.json\n```\n\n```text\n\"compilerOptions\": {\n    \"baseUrl\": \"../\",\n    \"paths\": {\n      \"@/*\": [\"./*\"],\n      \"@server/*\": [\"./server/src/*\"]\n    },\n  }\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react-swc\";\nimport path from \"path\";\n\nexport default defineConfig({\n  resolve: {\n    alias: {\n      \"@\": path.resolve(__dirname, \"../\"),\n      \"@server\": path.resolve(__dirname, \"../server/src\"),\n    },\n  },\n  plugins: [react()],\n});\n```\n\n```text\nvite.config.ts\n```\n\n```text\ntsconfig.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\nvite.config.ts\n```\n\n```text\npath\n```\n\n```text\npath.resolve()\n```\n\n```text\ntsconfig.json\n```\n\n```text\nvite.config.ts\n```\n\n```text\n'@vitejs/plugin-react'\n```\n\n```text\nnpm install --save-dev vite-tsconfig-paths\n```\n\n```text\n// ...\nimport tsconfigPaths from 'vite-tsconfig-paths';\n\nexport default defineConfig({\n  plugins: [tsconfigPaths()],\n});\n```\n\n```text\nvite-tsconfig-paths\n```\n\n```text\nvite.config\n```\n\n```js\nimport * as node_fs from 'fs'\n\nfunction get_paths_from_tsconfig() {\n  const tsconfig_s = node_fs\n    .readFileSync('./tsconfig.json', 'utf-8')\n    .replace(/\\/\\/.*$/gm, '') // Removing comments\n  const tsconfig = JSON.parse(tsconfig_s)\n  const aliases = {}\n  for (const [key, value] of Object.entries(tsconfig.compilerOptions.paths)) {\n    aliases[key] = path.resolve(__dirname, value[0])\n  }\n  return aliases\n}\n\nexport default defineConfig({\n  resolve: {\n    alias: get_paths_from_tsconfig(),\n  },\n  build: {\n    target: 'esnext'\n  }\n})\n```\n\n```json\n// tsconfig\n    \"paths\": {\n      \"#src/*\": [\"./src/*\"],\n    }\n```\n\n```json\n// package.json\n  \"imports\": {\n    \"#src/*\": [\"./src/*\"]\n  },\n```\n\n```js\n// some tsx file somewhere\nimport { render } from 'solid-js/web';\n// `App` is located at `./src/App.tsx`\nimport App from '#src/App';\nrender(() => <App/>, document.getElementById(\"root\") as HTMLElement);\n```\n\n```text\nnode: v22.2.0\ntsserver: 4.3.3\nvite: \"^5.4.10\"\n```\n\n```text\ntsconfig\n```\n\n```text\npackage.json\n```\n\n```text\ntsconfig\n```\n\n```text\ntsserver\n```\n\n```text\npackage.json\n```\n\n```text\nvite\n```\n\n```js\nimport { parse } from 'jsonc-parser';\n\nexport default defineConfig({\n  ...\n  resolve: {\n    alias: getPathsFromTsConfig()\n  },\n  ...\n});\n\nfunction getPathsFromTsConfig() {\n  const tsconfig = parse(fs.readFileSync('./tsconfig.json', 'utf-8'));\n  const aliases = {};\n  for (const [key, value] of Object.entries(tsconfig.compilerOptions.paths)) {\n    const cleanKey = key.replace('/*', '');\n    const cleanValue = value[0].replace('/*', '');\n    const resolvedPath = path.resolve(__dirname, cleanValue);\n    aliases[cleanKey] = resolvedPath;\n  }\n  return aliases;\n}\n```\n\n```text\nUserConfig\n```\n\n```text\nvite-tsconfig-paths\n```\n\n```text\nnull\n```\n\n```text\nDEBUG=vite:resolve npm run YourStartScript\n```\n\n```text\nloose\n```\n\n```text\nallowJs\n```\n\n```text\ntsconfig.json + package.json\n```\n\n```text\nvite.config.ts\n```\n\n```text\nvite-tsconfig-paths\n```\n\n```text\n\"compilerOptions\": {\n    \"baseUrl\": \"../\",\n    \"paths\": {\n      \"@/*\": [\"./*\"],\n      \"@server/*\": [\"./server/src/*\"]\n    },\n  }\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react-swc\";\nimport path from \"path\";\n\nexport default defineConfig({\n  resolve: {\n    alias: {\n      \"@\": path.resolve(__dirname, \"../\"),\n      \"@server\": path.resolve(__dirname, \"../server/src\"),\n    },\n  },\n  plugins: [react()],\n});\n```\n\n```text\ntsconfig.json\n```\n\n```text\nvite.confing.ts\n```\n\n```text\ntsconfig.app.json\n```\n\n```text\ntsconfig.json\n```\n\n========================================\n\nComments:\n- This should be the accepted answer. Pulling an untrusted dependency just to save two lines in the vite config is not worth it.\n- I don't understand why vite doesn't typescript's own convention though. tsconfig's `compilerOptions.paths` has existed for ages, and is compatible with all the other frameworks I've used. (Obligatory note that I barely use JS, and I'm likely just out of the loop on how these systems work. I still find it dumb that it doesn't work with existing standards)\n- @Zoe-Savethedatadump github.com/vitejs/vite/issues/6828\n- Do you not get type errors in `vite.config.ts` with this? Specifically with the \"path\" import\n- Installing `@types&#47;node` solved the type errors I got. User @quikler led me to this solution, they have an answer at the bottom of this page (as of this comment)\n- How does vite use the aliases ? I don't get it\n- dev.to/tilly/aliasing-in-vite-w-typescript-1lfo Basically the same but this blog explains more details.\n- @Zoe-Savethedatadump Does webpack & other framework like rspack support this ootb?\n- The `\"baseUrl\": \"..&#47;\",` configuration is now deprecated in modern TS and can be left out.\n- As experienced by alex-craft, the plugin didn't work for me. (`\"paths\": {\"*\": [\"..&#47;*\", \"..&#47;..&#47;*\"]}`)\n- Got, \"The CJS build of Vite's Node API is deprecated.\" error with this.\n- @Zorayr when I wrote my answer, 4.x was the newest version of Vite, looks like there have been some breaking changes in 5. There are some threads here on SO re: this error, for example: stackoverflow.com/questions/77538589/&hellip;\n- Vite now ships with this, see: `resolve.tsconfigPaths`\n- Alex, thanks for the post. This worked for me with a small edit. I had to strip the /* on the key and replace the /* with / on the value `let a = replace(key, \"&#47;*\", \"\"); let v = replace(value[0], \"&#47;*\", \"&#47;\"); aliases[ a ] = path.resolve( __dirname, v );`\n- Maybe things have changed, but I had to update the code to get it to build and it still didn't work. As of today, I had to add includes for fs and path, and type the aliases const to AliasOptions (which I also had to import from vite) and value (`(value as string[])`). But even though it could then build, it still didn't work.\n- Do you not get type errors in `vite.config.ts` with this? Specifically with the \"path\" import\n- @MarkJohnson Yeah. I got one. You can suppress it in vscode. I did it with: `Ctrl + .` and vscode suggested me an option.\n- Ah yes. Installing `@types&#47;node` was suggested for me. I keep forgetting about these things.\n- you're not alone on this :)\n- The `tsconfig.app.json` also was the culprit for me. I needed all three files for the alias to work in my case.","metadata":{"transformedAt":"2026-08-18T18:33:46.390Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":46,"totalLines":349,"estimatedTokens":1814}}17{"id":"stack-71676111","source":"stackoverflow","questionId":71676111,"title":"vue component doesn't update after state changes in pinia store","tags":["javascript","vue.js","vite","pinia"],"text":"Title: vue component doesn't update after state changes in pinia store\nTags: javascript, vue.js, vite, pinia\nSource: Stack Overflow\n\nQuestion:\nI'm currently working on my first vue application, currently building the login logics.\nFor State management, pinia is being used. I created a Pinia Store to manage the \"isLoggedIn\" state globally.\n\n```\nimport { defineStore } from \"pinia\";\n\nexport const useLoginStatusStore = defineStore('loginStatus', {\n id: 'loginStatus',\n state: () => ({\n isLoggedIn: false\n }),\n actions: {\n logIn() {\n this.isLoggedIn = true\n console.log(\"Login\", this.isLoggedIn)\n },\n logOut() {\n this.isLoggedIn = false\n console.log(\"Logout\", this.isLoggedIn)\n }\n }\n})\n```\n\nSo far so good, its working, i can access the state and actions in the components and router file.\n\n```\n****\n\nimport { createRouter, createWebHistory } from 'vue-router'\nimport { createPinia } from 'pinia'\nimport { createApp, ref } from 'vue'\nimport { useLoginStatusStore } from '../stores/loginStatus.js'\n\nimport App from '../App.vue'\nimport WelcomeView from '../views/public/WelcomeView.vue'\nimport SplashView from '../views/public/SplashView.vue'\n\nconst pinia = createPinia()\nconst app = createApp(App)\napp.use(pinia)\n\nconst loginStatusStore = useLoginStatusStore()\nlet isLoggedIn = ref(loginStatusStore.isLoggedIn)\n\nconsole.log(\"isLoggedIn\", loginStatusStore.isLoggedIn)\n\nconst router = createRouter({\n history: createWebHistory(import.meta.env.BASE_URL),\n routes: [\n {\n path: '/',\n name: 'splash',\n component: SplashView\n },\n {\n path: '/welcome',\n name: 'welcome',\n component: WelcomeView\n },\n {\n path: '/login',\n name: 'login',\n component: () => import('../views/public/LoginView.vue')\n },\n {\n path: '/signup',\n name: 'signup',\n component: () => import('../views/public/SignUpView.vue')\n },\n {\n path: '/resetpassword',\n name: 'resetpassword',\n component: () => import('../views/public/ForgotPasswordView.vue')\n },\n {\n path: '/home',\n name: 'home',\n component: () => import('../views/protected/HomeView.vue'),\n meta: { requiresAuth: true }\n },\n {\n path: '/sounds',\n name: 'sounds',\n component: () => import('../views/protected/SoundsView.vue'),\n meta: { requiresAuth: true }\n },\n {\n path: '/player',\n name: 'soundPlayer',\n component: () => import('../views/protected/SoundPlayerView.vue'),\n meta: { requiresAuth: true }\n },\n {\n path: '/profile',\n name: 'profile',\n component: () => import('../views/protected/ProfileView.vue'),\n meta: { requiresAuth: true }\n },\n {\n path: '/meditation',\n name: 'meditation',\n component: () => import('../views/protected/MeditationView.vue'),\n meta: { requiresAuth: true }\n },\n {\n path: '/tools',\n name: 'tools',\n component: () => import('../views/protected/ToolsView.vue'),\n meta: { requiresAuth: true }\n }\n ]\n})\n\nrouter.beforeEach((to, from, next) => {\n if (to.meta.requiresAuth) {\n console.log(\"Router\", isLoggedIn.value)\n if (!isLoggedIn.value) {\n next({\n name: 'welcome'\n })\n } else {\n next()\n }\n } else {\n next()\n }\n})\n\nexport default router\n```\n\nIn the router it's being used for protected routes and in App.vue for conditional class rendering.\n\nThe Problem is, that when the state gets updated, it doesn't get updated in the components and the components themselves don't update either. I tried with the $subscribe method in pinia, but didnt manage to get it working. I know, whats needed is something that creates reactivity here. But no clue how to do that. I'm grateful for any help with this :)\n\nthanks for reading\n\n```\n**App.vue**\n\nimport { RouterView } from 'vue-router';\nimport DevNavItem from '@/components/header/DevNavItem.vue'\nimport HeaderItem from '@/components/header/HeaderItem.vue'\nimport FooterItem from '@/components/footer/FooterItem.vue'\nimport { useLoginStatusStore } from './stores/loginStatus.js';\n\nconst loginStatusStore = useLoginStatusStore()\nconst isLoggedIn = loginStatusStore.isLoggedIn\n\nconsole.log(\"App.vue\", loginStatusStore.isLoggedIn)\n\n \n \n \n \n\n/*FONT-IMPORT*/\n@import url(\"@/assets/font/alegreya_font.scss\");\n\n/* GENERAL STYLES */\n\n* {\n padding: 0;\n margin: 0;\n box-sizing: border-box;\n}\nheader {\n position: top;\n}\n.mainProtected {\n width: 100vw;\n height: 83vh;\n overflow: hidden;\n}\n.mainPublic {\n width: 100vw;\n height: 100vh;\n overflow: hidden;\n}\n\n/* GLOBAL CLASSES */\n\n.mainLogo {\n height: 350px;\n width: 350px;\n background: url(\"./img/icons/main.png\") center/cover no-repeat;\n}\n.leavesBackground {\n background-color: #253334;\n background-image: url(\"./src/img/images/background_partial.png\");\n background-repeat: no-repeat;\n background-position: bottom;\n background-size: contain;\n}\n.logoSmall {\n background: url(\"./img/icons/main.png\") center/contain no-repeat;\n height: 100px;\n width: 100px;\n}\n.buttonPublic {\n padding: 20px 0;\n text-align: center;\n background-color: #7c9a92;\n color: #fff;\n border-radius: 15px;\n width: 90%;\n text-decoration: none;\n font-size: 24px;\n border: none;\n}\n\n```\n\nI tried subscribing to the state with $subscribe, but it didn't work.\n\n========================================\n\nTop Answer:\none way is to create a method in store that returns the desired state.\n\n```\nfunction getDesiredState() {\n return desiredState;\n}\n```\n\nit is reactive without using storeToRefs.\n\n========================================\n\nCode:\n```text\nimport { defineStore } from \"pinia\";\n\nexport const useLoginStatusStore = defineStore('loginStatus', {\n    id: 'loginStatus',\n    state: () => ({\n        isLoggedIn: false\n    }),\n    actions: {\n        logIn() {\n            this.isLoggedIn = true\n            console.log(\"Login\", this.isLoggedIn)\n        },\n        logOut() {\n            this.isLoggedIn = false\n            console.log(\"Logout\", this.isLoggedIn)\n        }\n    }\n})\n```\n\n```text\n**<roouter.js>**\n\nimport { createRouter, createWebHistory } from 'vue-router'\nimport { createPinia } from 'pinia'\nimport { createApp, ref } from 'vue'\nimport { useLoginStatusStore } from '../stores/loginStatus.js'\n\nimport App from '../App.vue'\nimport WelcomeView from '../views/public/WelcomeView.vue'\nimport SplashView from '../views/public/SplashView.vue'\n\nconst pinia = createPinia()\nconst app = createApp(App)\napp.use(pinia)\n\nconst loginStatusStore = useLoginStatusStore()\nlet isLoggedIn = ref(loginStatusStore.isLoggedIn)\n\nconsole.log(\"isLoggedIn\", loginStatusStore.isLoggedIn)\n\n\nconst router = createRouter({\n  history: createWebHistory(import.meta.env.BASE_URL),\n  routes: [\n    {\n      path: '/',\n      name: 'splash',\n      component: SplashView\n    },\n    {\n      path: '/welcome',\n      name: 'welcome',\n      component: WelcomeView\n    },\n    {\n      path: '/login',\n      name: 'login',\n      component: () => import('../views/public/LoginView.vue')\n    },\n    {\n      path: '/signup',\n      name: 'signup',\n      component: () => import('../views/public/SignUpView.vue')\n    },\n    {\n      path: '/resetpassword',\n      name: 'resetpassword',\n      component: () => import('../views/public/ForgotPasswordView.vue')\n    },\n    {\n      path: '/home',\n      name: 'home',\n      component: () => import('../views/protected/HomeView.vue'),\n      meta: { requiresAuth: true }\n    },\n    {\n      path: '/sounds',\n      name: 'sounds',\n      component: () => import('../views/protected/SoundsView.vue'),\n      meta: { requiresAuth: true }\n    },\n    {\n      path: '/player',\n      name: 'soundPlayer',\n      component: () => import('../views/protected/SoundPlayerView.vue'),\n      meta: { requiresAuth: true }\n    },\n    {\n      path: '/profile',\n      name: 'profile',\n      component: () => import('../views/protected/ProfileView.vue'),\n      meta: { requiresAuth: true }\n    },\n    {\n      path: '/meditation',\n      name: 'meditation',\n      component: () => import('../views/protected/MeditationView.vue'),\n      meta: { requiresAuth: true }\n    },\n    {\n      path: '/tools',\n      name: 'tools',\n      component: () => import('../views/protected/ToolsView.vue'),\n      meta: { requiresAuth: true }\n    }\n  ]\n})\n\nrouter.beforeEach((to, from, next) => {\n  if (to.meta.requiresAuth) {\n    console.log(\"Router\", isLoggedIn.value)\n    if (!isLoggedIn.value) {\n      next({\n        name: 'welcome'\n      })\n    } else {\n      next()\n    }\n  } else {\n    next()\n  }\n})\n\nexport default router\n```\n\n```text\n**App.vue**\n\n<script setup>\nimport { RouterView } from 'vue-router';\nimport DevNavItem from '@/components/header/DevNavItem.vue'\nimport HeaderItem from '@/components/header/HeaderItem.vue'\nimport FooterItem from '@/components/footer/FooterItem.vue'\nimport { useLoginStatusStore } from './stores/loginStatus.js';\n\nconst loginStatusStore = useLoginStatusStore()\nconst isLoggedIn = loginStatusStore.isLoggedIn\n\nconsole.log(\"App.vue\", loginStatusStore.isLoggedIn)\n\n</script>\n\n<template>\n  <DevNavItem />\n  <HeaderItem v-if=\"isLoggedIn\" />\n  <RouterView :class=\"isLoggedIn ? 'mainProtected' : 'mainPublic'\" />\n  <FooterItem v-if=\"isLoggedIn\" />\n</template>\n\n<style>\n/*FONT-IMPORT*/\n@import url(\"@/assets/font/alegreya_font.scss\");\n\n/* GENERAL STYLES */\n\n* {\n  padding: 0;\n  margin: 0;\n  box-sizing: border-box;\n}\nheader {\n  position: top;\n}\n.mainProtected {\n  width: 100vw;\n  height: 83vh;\n  overflow: hidden;\n}\n.mainPublic {\n  width: 100vw;\n  height: 100vh;\n  overflow: hidden;\n}\n\n/* GLOBAL CLASSES */\n\n.mainLogo {\n  height: 350px;\n  width: 350px;\n  background: url(\"./img/icons/main.png\") center/cover no-repeat;\n}\n.leavesBackground {\n  background-color: #253334;\n  background-image: url(\"./src/img/images/background_partial.png\");\n  background-repeat: no-repeat;\n  background-position: bottom;\n  background-size: contain;\n}\n.logoSmall {\n  background: url(\"./img/icons/main.png\") center/contain no-repeat;\n  height: 100px;\n  width: 100px;\n}\n.buttonPublic {\n  padding: 20px 0;\n  text-align: center;\n  background-color: #7c9a92;\n  color: #fff;\n  border-radius: 15px;\n  width: 90%;\n  text-decoration: none;\n  font-size: 24px;\n  border: none;\n}\n</style>\n```\n\n```text\nimport { storeToRefs } from 'pinia'\nconst themeStore = useThemeStore();\nconst { isDark } = storeToRefs(themeStore);\n```\n\n```text\nimport { computed } from 'vue'\nconst themeStore = useThemeStore();\nconst isDark = computed(() => themeStore.isDark);\n```\n\n```text\nimport { useThemeStore } from \"./stores/theme.js\";\nconst themeStore = useThemeStore();\n\n// WRONG ways of extracting state from store\nlet isDark = themeStore.isDark; // not reactive\nlet isDark = ref(themeStore.isDark); // reactive, but will not be updated with the store\nlet { isDark } = themeStore; // not reactive, cannot destructure\n```\n\n```text\n...\nconst { increment } = store // actions can be destructured directly\n...\n```\n\n```text\nstoreToRefs()\n```\n\n```text\ncomputed\n```\n\n```text\nstoreToRefs()\n```\n\n```text\nactions\n```\n\n```text\nunique ID\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\nfunction getDesiredState() {\n return desiredState;\n}\n```\n\n========================================\n\nComments:\n- Did you try the computed property?\n- Are you sure this is working properly? Did you checked in the Vue devtools?\n- what do you mean \"this is working properly\" ? It's not working ;)\n- Any ideas how do I use storeToRefs property within another ref ? i.e. `const {price} = storeToRefs(store)` `const list = ref([{id: 1, price: price}])`\n- That will not work, the price will be reactive and will update but the `list` will not be updated when price changes. In this case, you have to make your `list` a computed property.\n- but why is it working sometimes?\n- In my Vue3 App with TS only the following approach worked: import { computed } from 'vue' const themeStore = useThemeStore(); const isDark = computed(() => themeStore.isDark);\n- Per Eduardo San Martin Morote himself \"Extra Tip: most of the time you don't need storeToRefs() (or toRef()) either. You can just use the store directly! Vue reactivity is really convenient \" source:: masteringpinia.com/blog/my-top-5-tips-for-using-pinia\n- Would be great if this worked... but does it? Not reactive for me.","metadata":{"transformedAt":"2026-08-18T18:33:46.390Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":521,"estimatedTokens":2965}}18{"id":"stack-72468249","source":"stackoverflow","questionId":72468249,"title":"Vitest - @ src folder alias not resolved in test files","tags":["typescript","vuejs3","vite","vitest"],"text":"Title: Vitest - @ src folder alias not resolved in test files\nTags: typescript, vuejs3, vite, vitest\nSource: Stack Overflow\n\nQuestion:\nI have a vue3 project using Vite/Vitest, as recommanded in Vue.js documentation.\n\nHere is the structure of the project:\n\n```\nsrc\n components\n // my Vue components here, potentially in sub-folders. For example:\n HelloWorld.vue \n router\n index.ts\n App.vue\n main.ts\nvitest\n components\n // My test specs. For example:\n HelloWorld.spec.ts\n// ...\ntsconfig.app.json\ntsconfig.json\ntsconfig.vite-config.json\ntsconfig.vitest.json\nvite.config.ts\n```\n\nThe `@/` alias for `src` folder is resolved properly in components files.\nHowever, in my test files, I get an error: cannot find module.\n\nFor example, in `HelloWorld.spec.ts`:\n\n```\nimport HelloWorld from '@/components/HelloWorld.vue'; // {\n it('should day hello', () => {\n // ...\n });\n});\n```\n\n**tsconfig.app.json**\n\n```\n{\n \"extends\": \"@vue/tsconfig/tsconfig.web.json\",\n \"include\": [\n \"env.d.ts\",\n \"src/**/*\",\n \"src/**/*.vue\"\n ],\n \"exclude\": [\n \"vitest/**/*\"\n ],\n \"compilerOptions\": {\n \"composite\": true,\n \"baseUrl\": \".\",\n \"paths\": {\n \"@/*\": [\n \"./src/*\"\n ]\n },\n \"strict\": true,\n \"experimentalDecorators\": true\n }\n}\n```\n\n**vite.config.js**\n\n```\nimport vue from '@vitejs/plugin-vue';\nimport { fileURLToPath, URL } from 'url';\nimport { defineConfig } from 'vite';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [vue()],\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url)),\n },\n },\n test: {\n include: ['./vitest/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],\n },\n});\n```\n\n========================================\n\nTop Answer:\nYou just have to specify the aliases in your `vitest.config.js` file:\n\n```\nimport path from 'path'\nimport vue from '@vitejs/plugin-vue'\n\nexport default {\n plugins: [vue()],\n test: {\n globals: true,\n environment: 'jsdom',\n },\n resolve: {\n alias: {\n '@': path.resolve(__dirname, './src')\n },\n },\n}\n```\n\n========================================\n\nCode:\n```text\nsrc\n  components\n    // my Vue components here, potentially in sub-folders. For example:\n    HelloWorld.vue \n  router\n    index.ts\n  App.vue\n  main.ts\nvitest\n  components\n    // My test specs. For example:\n    HelloWorld.spec.ts\n// ...\ntsconfig.app.json\ntsconfig.json\ntsconfig.vite-config.json\ntsconfig.vitest.json\nvite.config.ts\n```\n\n```js\nimport HelloWorld from '@/components/HelloWorld.vue'; // <-- error !\nimport { describe, it } from 'vitest';\n\ndescribe('HelloWorld', () => {\n  it('should day hello', () => {\n    // ...\n  });\n});\n```\n\n```json\n{\n  \"extends\": \"@vue/tsconfig/tsconfig.web.json\",\n  \"include\": [\n    \"env.d.ts\",\n    \"src/**/*\",\n    \"src/**/*.vue\"\n  ],\n  \"exclude\": [\n    \"vitest/**/*\"\n  ],\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@/*\": [\n        \"./src/*\"\n      ]\n    },\n    \"strict\": true,\n    \"experimentalDecorators\": true\n  }\n}\n```\n\n```js\nimport vue from '@vitejs/plugin-vue';\nimport { fileURLToPath, URL } from 'url';\nimport { defineConfig } from 'vite';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue()],\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url)),\n    },\n  },\n  test: {\n    include: ['./vitest/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],\n  },\n});\n```\n\n```text\n@/\n```\n\n```text\nsrc\n```\n\n```text\nHelloWorld.spec.ts\n```\n\n```json\n{\n  \"extends\": \"@vue/tsconfig/tsconfig.web.json\",\n  \"include\": [\n    \"env.d.ts\",\n    \"src/**/*\",\n    \"src/**/*.vue\"\n  ],\n  \"exclude\": [\n    \"vitest/**/*\"\n  ],\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@/*\": [\n        \"./src/*\"\n      ]\n    },\n    \"strict\": true,\n    \"experimentalDecorators\": true\n  }\n}\n```\n\n```json\n{\n  \"extends\": \"./tsconfig.app.json\",\n  \"include\": [\n    \"vitest/**/*\",\n  ],\n  \"exclude\": [],\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"lib\": [],\n    \"types\": [\n      \"node\",\n      \"jsdom\"\n    ],\n  }\n}\n```\n\n```text\ntsconfig.vitest.json\n```\n\n```text\nimport path from 'path'\nimport vue from '@vitejs/plugin-vue'\n\nexport default {\n  plugins: [vue()],\n  test: {\n    globals: true,\n    environment: 'jsdom',\n  },\n  resolve: {\n    alias: {\n      '@': path.resolve(__dirname, './src')\n    },\n  },\n}\n```\n\n```text\nvitest.config.js\n```\n\n```text\nimport { defineConfig } from 'vitest/config';\nimport { svelte } from '@sveltejs/vite-plugin-svelte';\nimport path from 'path';\n\nexport default defineConfig({\n  plugins: [svelte({ hot: !process.env.VITEST })],\n  test: {\n    globals: true,\n    environment: 'jsdom',\n  },\n  resolve: {\n    alias: {\n      $lib: path.resolve(__dirname, './src/lib'),\n    },\n  },\n});\n```\n\n```text\n$lib\n```\n\n```text\nvitest.config.js\n```\n\n```text\nvite-tsconfig-paths\n```\n\n```json\n// web/tests/jsconfig.json\n// Helps VSCode detect typescript path aliases in test files\n{\n  \"extends\": \"../tsconfig.json\",\n  \"include\": [\"./**/*.test.ts\"]\n}\n```\n\n```text\nweb/tests/jsconfig.json\n```\n\n```js\n// vitest.config.ts\n\nimport { defineConfig } from \"vitest/config\";\nimport tsconfigPaths from 'vite-tsconfig-paths'; // <—- import this\n\nexport default defineConfig({\n  test: {\n    setupFiles: \"./tests.setup.ts\",\n    globals: true,\n    environment: \"happy-dom\",\n    include: [\"./app/**/*.{test,spec}.{ts,tsx}\"],\n  },\n  plugins: [\n    tsconfigPaths() // <—- Add here\n  ]\n});\n```\n\n```text\nvite.config.ts\n```\n\n```text\ntest\n```\n\n```text\nvitest.config.ts\n```\n\n```text\ntsconfigPaths()\n```\n\n```text\n@vitest/coverage-v8\n```\n\n```ts\nimport { defineVitestConfig } from '@nuxt/test-utils/config';\nimport { fileURLToPath } from 'node:url';\n\nexport default defineVitestConfig({\n  test: {\n    environment: 'nuxt',\n    // you can optionally set Nuxt-specific environment options\n    // environmentOptions: {\n    //   nuxt: {\n    //     rootDir: fileURLToPath(new URL('./playground', import.meta.url)),\n    //     domEnvironment: 'happy-dom', // 'happy-dom' (default) or 'jsdom'\n    //     overrides: {\n    //       // other Nuxt config you want to pass\n    //     }\n    //   }\n    // }\n    globals: true,\n    reporters: ['default', 'github-actions'],\n    coverage: {\n      provider: 'v8', // provider\n      reporter: ['text', 'json', 'json-summary', 'html'], // report format\n      reportOnFailure: true, // report coverage even if fails\n      include: ['app/**'],\n      exclude: ['**/assets/**', '**/types/**'],\n    },\n  },\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./app', import.meta.url)),\n    },\n  },\n});\n```\n\n========================================\n\nComments:\n- You could first try with a more standarized way to build aliases in **vite.config.js**: `alias: { \"@\": \".&#47;src\" }` . If it's not working, or if you want to keep the same config, I suggest you to publish a **reproducible project**.\n- The alias config came as-is with the initialization of the project, using `npm init vue@latest`. But I tried other configs and none is working.\n- Yes - then you should give us a reproducible project, i suspect a typescript config issue or it could be also possible that you hit a recent issue which require the project to be built at least one time before setting the `test.include`.\n- Do you also use a vitest.config.js file?\n- no, I don't use a specific config file for vitest\n- Any idea why we should exclude test files in `tsconfig.app.json`? Because including this files instead of excluding them solves the problem.\n- The reason is to avoid these files being compiled. You can be more \"precise\" about what you want to do with these files by using the typescript `configurations` option.\n- why is it a problem if the tests files are compiled?\n- same prob for me also. I tried to configure the `resolve.alias` vite config property but it still not working\n- @AdriHM, look at my comment of June 13. It may help.\n- I guess it should be `'@': path.resolve(__dirname, '.&#47;src'),`\n- oh yes you're right\n- This resolve option is not listed in their official documentation vitest.dev/config Where do you find it ? ^^\n- I went to module sources lol, but I think it's here vitest.dev/config/#alias\n- It doesn't work. And it breaks half my existing unit tests.\n- Yep, worked for me as well, like include=[...., \"test\"] in the regular tsconfing.app.json\n- This did the trick for me. Thx!\n- [ERROR] \"vite-tsconfig-paths\" resolved to an ESM file. ESM file cannot be loaded by `require`. See vite.dev/guide/troubleshooting.html#this-package-is-esm-only for more details. [plugin externalize-deps]","metadata":{"transformedAt":"2026-08-18T18:33:46.390Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":413,"estimatedTokens":2112}}19{"id":"stack-70883903","source":"stackoverflow","questionId":70883903,"title":"loading env variables in react app using vite","tags":["javascript","reactjs","environment-variables","vite"],"text":"Title: loading env variables in react app using vite\nTags: javascript, reactjs, environment-variables, vite\nSource: Stack Overflow\n\nQuestion:\nI´ve been through all the docs from vite, react.js and dev blogs, but I'm not getting it to work\n\nI have a .env file which contains the following\n\n```\nVITE_API_KEY = XXX\n```\n\ninside my firebase.js file I'm loading it like :\n\n```\nconst firebaseConfig = {\n apiKey: import.meta.env.API_KEY,\n .....\n .....\n}\n// Initialize Firebase\nconst app = initializeApp(firebaseConfig);\n```\n\nbut it appears as **null**, I've restarted the dev server, reinstalled node_modules (just in case) changed var prefixes to REACT_APP_XX, tried using process.env.XX global object, basically gone through all different ways to read vars from a .env file in react\n\nI´ve also tried to clog it from a component but it has the same result\n\nany suggestions/methods to solve this problem?\n\n========================================\n\nTop Answer:\nThe environment variable name used in code must match the name set in the `.env` file:\n\n```\n// .env\nVITE_API_KEY=abcd1234\n 👆\n```\n\n```\n// firebase.js\nconst firebaseConfig = { 👇\n apiKey: import.meta.env.VITE_API_KEY,\n ⋮\n}\n```\n\ndemo\n\nRelevant documentation can be found in the Vite Env variables docs\n\n========================================\n\nCode:\n```text\nVITE_API_KEY = XXX\n```\n\n```text\nconst firebaseConfig = {\n  apiKey: import.meta.env.API_KEY,\n   .....\n   .....\n}\n// Initialize Firebase\nconst app = initializeApp(firebaseConfig);\n```\n\n```text\nimport.meta.env.VITE_XX\n```\n\n```text\nif(import.meta.env.MODE === \"development\"){\n//use dev keys\n}\nelse{\n//use .env variables\n}\n```\n\n```text\nimport.meta.env.VITE_XX\n```\n\n```js\n// .env\nVITE_API_KEY=abcd1234\n   👆\n```\n\n```text\n// firebase.js\nconst firebaseConfig = {      👇\n  apiKey: import.meta.env.VITE_API_KEY,\n  ⋮\n}\n```\n\n```text\n.env\n```\n\n```text\nexport default defineConfig({\n    plugins: [react()],\n    envDir: './src/envs',\n```\n\n```text\nimport { defineConfig, loadEnv } from 'vite';\n\nexport default ({ mode }) => {\n  const env = loadEnv(mode, process.cwd(), '');\n\n  return defineConfig({\n    base: env.VITE_ROUTER_BASE_URL || '/',\n    define: {\n      'process.env': env,\n    },\n}\n```\n\n```text\nAPI_KEY=\"your_api_key\"\nAPI_KEY=your_api_key\n```\n\n```text\n.env\n```\n\n```text\n.env\n.env.qa\n.env.prod  \n.\n..etc\n```\n\n```text\nVITE_API_KEY=DEV-XXX\n```\n\n```text\nVITE_API_KEY=QA-YYY\n```\n\n```text\nconst API_KEY = import.meta.env.VITE_API_KEY;\n```\n\n```text\n\"build:dev\": \"tsc && vite build --mode dev\",\n\"build:qa\": \"tsc && vite build --mode qa\"\n```\n\n```text\nVITE_\n```\n\n```text\n.env.dev\n```\n\n```text\n.env.qa\n```\n\n```text\npackage.json\n```\n\n```text\nscripts\n```\n\n```text\n--mode qa\n```\n\n```text\n.env.qa\n```\n\n```text\n--mode dev\n```\n\n```text\n.env.dev\n```\n\n```text\nVITE_SERVER_URL=http://localhost:8000\n```\n\n```text\n.env\n```\n\n```text\npackage.json\n```\n\n```text\n.env\n```\n\n```text\nVITE_\n```\n\n```text\nimport.meta.env.VITE_SERVER_URL\n```\n\n========================================\n\nComments:\n- I was facing this exact issue with integrating the pokeapi for a vite react project with react redux toolkit while fetching data from the baseUrl dynamically loading the apiurl from the .env file, when I renamed my environment variable from \"POKEAPI_URL\" to \"VITE_POKEAPI_URL\" and then used this updated name in the baseurl, it started working for me and I was able to load the pokemon data from that API. Hope this helps someone!\n- Where did you put this please ?\n- @AbdulhameedMustapha you can define your env variables in a **.env** file then you can grab their values as described above\n- This works for me\n- \"To prevent accidentally leaking env variables to the client, only variables prefixed with VITE_ are exposed to your Vite-processed code. e.g. for the following env variables\" vitejs.dev/guide/env-and-mode\n- thanks, this was frustrating but turned out to be my issue. ⭐ to you\n- Thanks, moving my .env from my src/ folder to the root fixed it for me.","metadata":{"transformedAt":"2026-08-18T18:33:46.390Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":32,"totalLines":230,"estimatedTokens":983}}20{"id":"stack-71982849","source":"stackoverflow","questionId":71982849,"title":"How do I add types to a Vite library build?","tags":["javascript","typescript","vue.js","rollup","vite"],"text":"Title: How do I add types to a Vite library build?\nTags: javascript, typescript, vue.js, rollup, vite\nSource: Stack Overflow\n\nQuestion:\nI followed the vite documentation for using library mode and I am able to produce a working component library.\n\nI created the project with the **vue-ts** preset and in my component I have defined props with their types, and used some interfaces. But when I build the library, there are no types included.\n\nHow do I add types for the final build, either inferred from components automatically or manually with definition files?\n\n**More information**\nHere is some more information on my files:\n\n`tsconfig.json`\n\n```\n{\n \"name\": \"@mneelansh/test-lib\",\n \"private\": false,\n \"version\": \"0.0.2\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vue-tsc --noEmit && vite build\",\n \"preview\": \"vite preview\"\n },\n \"emitDeclarationOnly\": true, // testing\n \"declaration\": true, // testing\n \"main\": \"./dist/lib.umd.js\",\n \"module\": \"./dist/lib.es.js\",\n \"types\": \"./dist/main.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": \"./dist/lib.es.js\",\n \"require\": \"./dist/lib.umd.js\"\n },\n \"./dist/style.css\": \"./dist/style.css\"\n },\n \"files\": [\n \"dist\"\n ],\n \"dependencies\": {\n \"@types/node\": \"^17.0.25\",\n \"vue\": \"^3.2.25\"\n },\n \"devDependencies\": {\n \"@vitejs/plugin-vue\": \"^2.3.1\",\n \"typescript\": \"^4.5.4\",\n \"vite\": \"^2.9.5\",\n \"vue-tsc\": \"^0.34.7\"\n }\n}\n```\n\nI added the `emitDeclarationOnly` and `declaration` properties but that didn't help.\n\nMy `vite.config.ts`:\n\n```\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\";\n\nconst path = require(\"path\");\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n build: {\n lib: {\n entry: path.resolve(__dirname, \"src/index.ts\"),\n name: \"Button\",\n fileName: (format) => `lib.${format}.js`,\n },\n rollupOptions: {\n external: [\"vue\"],\n output: {\n globals: {\n vue: \"Vue\",\n },\n },\n },\n },\n plugins: [vue()],\n});\n```\n\n========================================\n\nTop Answer:\nYou could write your own Vite plugin to leverage `tsc` at the `buildEnd` step to accomplish this. As other answers have suggested, you can use the flag `emitDeclarationOnly`.\n\nSee this simple example:\n\n```\nimport { type Plugin } from 'vite';\nimport { exec } from 'child_process';\n\nconst dts: Plugin = {\n name: 'dts-generator',\n buildEnd: (error?: Error) => {\n if (!error) {\n return new Promise((res, rej) => {\n exec('tsc --emitDeclarationOnly', (err) => (err ? rej(err) : res()));\n });\n }\n },\n};\n```\n\nThen add to your `plugins` field of your vite config\n\n========================================\n\nCode:\n```json\n{\n  \"name\": \"@mneelansh/test-lib\",\n  \"private\": false,\n  \"version\": \"0.0.2\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vue-tsc --noEmit && vite build\",\n    \"preview\": \"vite preview\"\n  },\n  \"emitDeclarationOnly\": true, // testing\n  \"declaration\": true, // testing\n  \"main\": \"./dist/lib.umd.js\",\n  \"module\": \"./dist/lib.es.js\",\n  \"types\": \"./dist/main.d.ts\",\n  \"exports\": {\n    \".\": {\n      \"import\": \"./dist/lib.es.js\",\n      \"require\": \"./dist/lib.umd.js\"\n    },\n    \"./dist/style.css\": \"./dist/style.css\"\n  },\n  \"files\": [\n    \"dist\"\n  ],\n  \"dependencies\": {\n    \"@types/node\": \"^17.0.25\",\n    \"vue\": \"^3.2.25\"\n  },\n  \"devDependencies\": {\n    \"@vitejs/plugin-vue\": \"^2.3.1\",\n    \"typescript\": \"^4.5.4\",\n    \"vite\": \"^2.9.5\",\n    \"vue-tsc\": \"^0.34.7\"\n  }\n}\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\";\n\nconst path = require(\"path\");\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  build: {\n    lib: {\n      entry: path.resolve(__dirname, \"src/index.ts\"),\n      name: \"Button\",\n      fileName: (format) => `lib.${format}.js`,\n    },\n    rollupOptions: {\n      external: [\"vue\"],\n      output: {\n        globals: {\n          vue: \"Vue\",\n        },\n      },\n    },\n  },\n  plugins: [vue()],\n});\n```\n\n```text\ntsconfig.json\n```\n\n```text\nemitDeclarationOnly\n```\n\n```text\ndeclaration\n```\n\n```text\nvite.config.ts\n```\n\n```js\nimport dts from \"vite-plugin-dts\";\n\nexport default defineConfig({\n  plugins: [\n    dts({\n      insertTypesEntry: true,\n    }),\n  ],\n```\n\n```text\nvite-plugin-dts\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport Vue from '@vitejs/plugin-vue2';\nimport dts from 'vite-plugin-dts';\nimport rollupTs from 'rollup-plugin-typescript2';\n\nexport default defineConfig({\n    plugins: [\n        Vue(),\n        dts({ insertTypesEntry: true }),\n        // only for type checking\n        {\n            ...rollupTs({\n                check: true,\n                tsconfig: './tsconfig.json',\n                tsconfigOverride: {\n                    noEmits: true,\n                },\n            }),\n            // run before build\n            enforce: 'pre',\n        },\n    ],\n    build: {\n        sourcemap: true,\n        lib: {\n            entry: './src/index.ts',\n            fileName: 'index',\n        },\n        rollupOptions: {\n            // make sure to externalize deps that shouldn't be bundled\n            // into your library\n            external: [\n                'vue',\n                'vue-class-component',\n                'vue-property-decorator',\n                'vuex',\n                'vuex-class',\n            ],\n            output: {\n                // Provide global variables to use in the UMD build\n                // for externalized deps\n                globals: {\n                    vue: 'Vue',\n                },\n            },\n        },\n    },\n});\n```\n\n```text\nvite-plugin-dts\n```\n\n```text\nrollup-plugin-typescript2\n```\n\n```text\nvite.config.js\n```\n\n```text\nvue-tsc --declaration --emitDeclarationOnly\n```\n\n```text\nimport { type Plugin } from 'vite';\nimport { exec } from 'child_process';\n\nconst dts: Plugin = {\n  name: 'dts-generator',\n  buildEnd: (error?: Error) => {\n    if (!error) {\n      return new Promise((res, rej) => {\n        exec('tsc --emitDeclarationOnly', (err) => (err ? rej(err) : res()));\n      });\n    }\n  },\n};\n```\n\n```text\ntsc\n```\n\n```text\nbuildEnd\n```\n\n```text\nemitDeclarationOnly\n```\n\n```text\nplugins\n```\n\n========================================\n\nComments:\n- Show what you have tried. What are you running. What does your tsconfig look like?\n- By default, Vite strips out the types, it's meant to speed up the processing pipeline. But what about using `tsc` with the `--emitDeclarationOnly` flag?\n- Try this `npm install vite @vitejs&#47;plugin-vue --save-dev`\n- @tauzN Please look at the tsconfig and vite config, I've added that in the question now\n- see also Type definitions are not generated for library mode build #2049\n- note, this is slow. build is faster with `rollup` and `rollup-plugin-typescript2`, about 4x faster in my case. there is also vite-dts but its broken. alternative: `npx tsup src&#47;index.ts --format cjs,esm --dts` - faster than rollup, 80% of time is needed for dts\n- The way this plugin handles types is different from `vue-tsc`, so it may report some strange bugs....\n- vite-plugin-dts has issue as of now. it doesn't generate types in dev mode and deletes types on every alternative run.\n- Thanks for the input. Vite-plugin-dts actually works very nicely. Have to try vue-tsc with Vite to see how well it would work\n- @NeelanshMathur does vite-plugin-dts show typescript errors for you? I see it has some advantages but even if i put something like `const a:number = \"string\"` in my code, it wouldn't show any error. ....which was a problem.\n- The plugin purely produces declaration files. Errors depend on your environment. If you need an example, you can see my published library github.com/neelansh15/vue-connect-wallet","metadata":{"transformedAt":"2026-08-18T18:33:46.390Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":322,"estimatedTokens":1880}}21{"id":"stack-68180648","source":"stackoverflow","questionId":68180648,"title":"String replacements in index.html in vite","tags":["javascript","vuejs3","rollupjs","vite"],"text":"Title: String replacements in index.html in vite\nTags: javascript, vuejs3, rollupjs, vite\nSource: Stack Overflow\n\nQuestion:\nI am trying to inject some strings into the index.html of a Vite app (using vue3 template). In a vue-cli project for example we would have\n\n```\nfavicon.ico\">\n```\n\nWhat is the Vite way to do that? (I know that BASE_URL is just '/' in this case. I am asking for the general solution) I would be fine with a solution that covers environment variables only, but it would be great to know an even more general solution that can use JS code as in\n\n```\n\n```\n\nAnd I would really appreciate a solution that doesn't require installing an npm package\n\n========================================\n\nTop Answer:\n### Update 2023-03-20:\n\nVite supports HTML Env replacement out of the box starting with version 4.2! So if that's all you're looking for, you should be set.\n\nOlder answer:\n\nWanted to do the same for a project. Used `vite-plugin-html` for a bit, but I ran into an issue with the plugin and the author of the plugin seems to have stopped maintaining it, so I had to look into an alternative solution.\n\nLuckily this is easy enough, as Vite has a hook for it.\n\nSo I ended up writing this tiny plugin (just remove the TypeScript if you don't use that):\n\n```\nconst transformHtmlPlugin = (data: Record): Plugin => ({\n name: 'transform-html',\n transformIndexHtml: {\n order: 'pre',\n handler(html: string) {\n return html.replace(\n //gi,\n (match, p1) => data[p1] || ''\n );\n }\n }\n});\n```\n\n*(Updated for Vite 5 on 2025-01-11)*\n\nIn the Vite config, just add it to the plugins array and pass it key/value pairs of things you'd like to be replaced in the HTML:\n\n```\nplugins: [transformHtmlPlugin({ key: 'value' })]\n```\n\nThen in your `index.html`, add the tags like in the original question: ``, and they will be replaced by whatever you passed into the plugin.\n\nIf you wanted to pass in all of your env variables, get them using `loadEnv` (example is in v-moe's post) and just unpack the object: `transformHtmlPlugin({ ...env })`.\n\nSo that's how I solved my issue. Maybe it's useful to someone out there!\n\n========================================\n\nCode:\n```html\n<link rel=\"icon\" href=\"<%= BASE_URL %>favicon.ico\">\n```\n\n```html\n<title><%= htmlWebpackPlugin.options.title %></title>\n```\n\n```text\n// vite.config.js\nimport vue from '@vitejs/plugin-vue'\n\nimport { loadEnv } from 'vite'\nimport { createHtmlPlugin } from 'vite-plugin-html'\n\nexport default ({ mode }) => {\n  const env = loadEnv(mode, process.cwd())\n  return {\n    plugins: [\n      vue(),\n      createHtmlPlugin({\n        minify: true,\n        inject: {\n          data: {\n            title: env.VITE_MY_FOO,\n          }\n        }\n      }),\n    ],\n  }\n}\n```\n\n```text\nVITE_MY_FOO=\"Hello vite ejs\"\n```\n\n```text\n<title><%= title %></title>\n```\n\n```text\nconst transformHtmlPlugin = (data: Record<string, string>): Plugin => ({\n    name: 'transform-html',\n    transformIndexHtml: {\n        order: 'pre',\n        handler(html: string) {\n            return html.replace(\n                /<%=\\s*(\\w+)\\s*%>/gi,\n                (match, p1) => data[p1] || ''\n            );\n        }\n    }\n});\n```\n\n```text\nplugins: [transformHtmlPlugin({ key: 'value' })]\n```\n\n```text\nvite-plugin-html\n```\n\n```text\nindex.html\n```\n\n```text\n<%= key %>\n```\n\n```text\nloadEnv\n```\n\n```text\ntransformHtmlPlugin({ ...env })\n```\n\n```text\nerror during build:\nURIError: URI malformed\n```\n\n```text\n<link ref=\"_k_VITE_PUBLIC_URL_k_\"\" />\n```\n\n```text\nimport { defineConfig, loadEnv } from \"vite\";\nimport { visualizer } from \"rollup-plugin-visualizer\";\n\nexport default defineConfig(({ mode }) => {\n    process.env = {...process.env, ...loadEnv(mode, process.cwd())};\n    // import.meta.env.VITE_NAME available here with: process.env.VITE_NAME\n\n    const htmlPlugin = () => {\n        return {\n            name: \"html-transform\",\n            transformIndexHtml(html: string) {\n                // notice the regex pattern below\n                return html.replace(/_k_(.*?)_k_/g, function (match, p1) {\n                    return process.env[p1] ?? '';\n                });\n            },\n        };\n    };\n\n    return {\n        plugins: [\n            htmlPlugin(),\n            visualizer(),\n        ],\n    };\n});\n```\n\n```text\nVITE_PUBLIC_URL = \"http://your-url.com\"\n```\n\n```text\n<title>%VITE_APP_TITLE%</title>\n```\n\n========================================\n\nComments:\n- Can't affirm but on the Vite website it says: \" URLs inside index.html are automatically rebased so there's no need for special %PUBLIC_URL% placeholders.\" vitejs.dev/guide\n- Surprised to see that Vite doesn't have this pretty basic feature that its competitors (Create React App, Vue CLI, etc.) all have.\n- `createHtmlPlugin({ inject: { data: env } })` also works as a terser syntax if you want to have access to all your env variables (I usually do).\n- For those coming along in 2025, this still mostly works. Enforce and transform are deprecated in vite5, but you can swap out enforce for order and transform for handle and everything will work as intended\n- @ohshazbot Thanks! Added an updated version of the code.\n- It seems Vite still lacks nice conditionals? So if `%TRACKING_SCRIPT_ID%` isn't defined, I'd get an empty script tag, instead of being able to wrap the script tag with an if, checking for that var?","metadata":{"transformedAt":"2026-08-18T18:33:46.390Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":201,"estimatedTokens":1326}}22{"id":"stack-74597732","source":"stackoverflow","questionId":74597732,"title":"Uncaught SyntaxError: Export 'import_react3' is not defined in module (at chunk-ALR5B6M7.js?v=aa4e0109:17143:3)","tags":["reactjs","typescript","vite"],"text":"Title: Uncaught SyntaxError: Export 'import_react3' is not defined in module (at chunk-ALR5B6M7.js?v=aa4e0109:17143:3)\nTags: reactjs, typescript, vite\nSource: Stack Overflow\n\nQuestion:\nI have a project created with `create-react-app` with `Typescript`. And I am using `yarn 3.3.0` as the package manager.\n\nNow I am trying to shift from `cra`s `webpack` to `vite`. I have bootstrapped a project with the `yarn create vite` command. And simply copy and paste the components from previous project to the new one.\n\nWhen I run on the command line `yarn tsc` I am facing no error.\n\nAlso running `yarn dev` is okay in the terminal and the server starts successfully.\n\nHowever, in the browser I am facing an weird error on the terminal which says:\n\n```\nUncaught SyntaxError: Export 'import_react3' is not defined in module (at chunk-ALR5B6M7.js?v=aa4e0109:17143:3)\n```\n\nhttps://i.sstatic.net/EhI4f.png\n\n========================================\n\nTop Answer:\nThis is for those who are using **MUI** install the following\n\n**npm install --save @emotion/react**\n\n**npm install --save @emotion/styled**\n\nafter installing **re-run** your project\n\n========================================\n\nCode:\n```text\nUncaught SyntaxError: Export 'import_react3' is not defined in module (at chunk-ALR5B6M7.js?v=aa4e0109:17143:3)\n```\n\n```text\ncreate-react-app\n```\n\n```text\nTypescript\n```\n\n```text\nyarn 3.3.0\n```\n\n```text\ncra\n```\n\n```text\nwebpack\n```\n\n```text\nvite\n```\n\n```text\nyarn create vite\n```\n\n```text\nyarn tsc\n```\n\n```text\nyarn dev\n```\n\n```bash\nnpm i @emotion/react @emotion/styled\n\nor\n\nyarn add @emotion/react @emotion/styled\n```\n\n```text\n@emotion/react\n```\n\n```text\n@emotion/styled\n```\n\n```text\nnpm install @mui/material @emotion/react @emotion/styled --force\n```\n\n```text\nimport { defineConfig } from 'vite'\nexport default defineConfig({\n\n// Other stuff\n\nresolve: {\n    alias: {\n      '@mui/styled-engine': '@mui/styled-engine-sc',\n    },\n},\n\n})\n```\n\n========================================\n\nComments:\n- Yeah the MUI docs are a bit misleading for Installation. It says default installation and emotion styles like you have it, and then right below, \"With Styled Components...\" one would assume separate from Emotion if you're not going to use it...BUT also required.\n- Issue is still not solving\n- github.com/mui/material-ui/blob/master/examples/&hellip; This package setup in the examples seems to be saying that it is possible to not haave emotion while having styled components. Also, this doc: mui.com/material-ui/guides/styled-engine Defines that you should resolve one module by another in the resolution. Using vite, I haave not find how to yet...\n- Just found that if you use MUI icons, they rely on emotion: mui.com/material-ui/material-icons\n- installing these packages resolved the issue\n- Simple buttons without any styled components in the whole (very small) app and still got the error. This action solved it (got my upvote), but on April 6th 2024, MUI's docs are still not addressing this. \"Assume makes an ass of u and me\".\n- To make it work, I needed to delete the `node_modules` folder\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- Unless you have the emotion libraries installed (as in the accepted answer), this will not solve your problem.","metadata":{"transformedAt":"2026-08-18T18:33:46.390Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":122,"estimatedTokens":869}}23{"id":"stack-70012970","source":"stackoverflow","questionId":70012970,"title":"running a vite dev server inside a docker container","tags":["docker","vue.js","vite"],"text":"Title: running a vite dev server inside a docker container\nTags: docker, vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI have a Vue-cli app that I'm trying to convert to vite. I am using Docker to run the server. I looked at a couple tutorials and got vite to run in development mode without errors. However, the browser can't access the port. That is, when I'm on my macbook's command line (outside of Docker) I can't `curl` it:\n\n```\n$ curl localhost:8080\ncurl: (52) Empty reply from server\n```\n\nIf I try localhost:8081 I get `Failed to connect`. In addition, if I run the webpack dev server it works normally so I know that my container's port is exposed.\n\nAlso, if I run curl in the same virtual machine that is running the vite server it works, so I know that vite is working.\n\nHere are the details:\n\nIn package.json:\n\n```\n...\n\"dev\": \"vue-cli-service serve\",\n\"vite\": \"vite\",\n...\n```\n\nThe entire vite.config.ts file:\n\n```\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n resolve: { alias: { '@': '/src' } },\n plugins: [vue()],\n server: {\n port: 8080\n }\n})\n```\n\nThe command that starts the container:\n\n```\ndocker-compose run --publish 8080:8080 --rm app bash\n```\n\nThe docker-compose.yml file:\n\n```\nversion: '3.7'\n\nservices:\n app:\n image: myapp\n build: .\n container_name: myapp\n ports:\n - \"8080:8080\"\n```\n\nThe Dockerfile:\n\n```\nFROM node:16.10.0\n\nRUN npm install -g npm@8.1.3\nRUN npm install -g @vue/cli@4.5.15\n\nRUN mkdir /srv/app && chown node:node /srv/app\n\nUSER node\n\nWORKDIR /srv/app\n```\n\nThe command that I run inside the docker container for vite:\n\n```\nnpm run vite\n```\n\nThe command that I run inside the docker container for vue-cli:\n\n```\nnpm run dev\n```\n\nSo, to summarize: my setup works when running the vue-cli dev server but doesn't work when using the vite dev server.\n\n========================================\n\nTop Answer:\nYou can also start your vite server with:\n\n```\n$ npm run dev -- --host\n```\n\nThis passes the --host flag to the vite command line.\n\nYou will see output like:\n\n```\nvite v2.7.9 dev server running at:\n\n > Local: http://localhost:3000/\n > Network: http://192.168.4.68:3000/\n\n ready in 237ms.\n```\n\n(I'm running a VirtualBox VM - but I think this applies here as well.)\n\n========================================\n\nCode:\n```text\n$ curl localhost:8080\ncurl: (52) Empty reply from server\n```\n\n```text\n...\n\"dev\": \"vue-cli-service serve\",\n\"vite\": \"vite\",\n...\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n    resolve: { alias: { '@': '/src' } },\n    plugins: [vue()],\n    server: {\n        port: 8080\n    }\n})\n```\n\n```text\ndocker-compose run --publish 8080:8080 --rm app bash\n```\n\n```text\nversion: '3.7'\n\nservices:\n  app:\n    image: myapp\n    build: .\n    container_name: myapp\n    ports:\n      - \"8080:8080\"\n```\n\n```text\nFROM node:16.10.0\n\nRUN npm install -g npm@8.1.3\nRUN npm install -g @vue/cli@4.5.15\n\nRUN mkdir /srv/app && chown node:node /srv/app\n\nUSER node\n\nWORKDIR /srv/app\n```\n\n```text\nnpm run vite\n```\n\n```text\nnpm run dev\n```\n\n```text\ncurl\n```\n\n```text\nFailed to connect\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n    resolve: { alias: { '@': '/src' } },\n    plugins: [vue()],\n    server: {\n        host: true,\n        port: 8080\n    }\n})\n```\n\n```text\n$ npm run dev -- --host\n```\n\n```text\nvite v2.7.9 dev server running at:\n\n  > Local:    http://localhost:3000/\n  > Network:  http://192.168.4.68:3000/\n\n  ready in 237ms.\n```\n\n```text\nexport default defineConfig({\nserver: {\n    host: '0.0.0.0',\n    watch: {\n        usePolling: true\n    }\n},})\n```\n\n```text\n0.0.0.0\n```\n\n```text\nserver: {\n    host: '127.0.0.1'\n}\n```\n\n```text\ncompile-frontend-task:\n      image: node:20\n      env_file: .env\n      command: /bin/sh -c 'npm ci && npm run dev'\n      working_dir: /var/www/html\n      entrypoint: ''\n      volumes:\n          - ./:/var/www/html\n      ports:\n          - 5173:5173\n```\n\n```text\nserver: {\n        host: '0.0.0.0',\n        port: 5173,\n        hmr: {\n            host: 'localhost',\n            port: 5173,\n        },\n    }\n```\n\n========================================\n\nComments:\n- what is port `8080` stands for ? frontend listening port or API server listening port?\n- When I browse to `http:&#47;&#47;localhost:8080` then I get the website that I'm developing.\n- port here represents the Vite server port. If you use the same port as your web server, Vite will use the next available port (8081 in your case).\n- That one info was very important! Any idea why --host not works if running via `npm run dev`?\n- Same here, thanks for the hint. Helped me alot.\n- You're my hero for today\n- @Bent, it will if you add -- first. npm docs\n- Thank you. Because nobody else mentioned that and been racking my brain for an hour.\n- Don't forget about `strictPort: 'true'` to force the port you specify. Then under `hmr` there's `port: 5173` and `clientPort: 8080`.\n- It does. Tried it standard devcontainer setup in vscode.\n- According to the docs, \"Set this to `0.0.0.0` or `true` to listen on all addresses, including LAN and public addresses.\" and \"This can be set via the CLI using `--host 0.0.0.0` or `--host`\" vite.dev/config/server-options#server-host\n- (This surprises me, because I'd expect this to be the value you *wouldn't* want it set to? In Docker \"listen on 127.0.0.1\" usually means the server will be unreachable from outside its own container, and you almost always want 0.0.0.0 as in the other answers.)","metadata":{"transformedAt":"2026-08-18T18:33:46.390Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":277,"estimatedTokens":1411}}24{"id":"stack-68131954","source":"stackoverflow","questionId":68131954,"title":"how to use sass using in vuejs3/vite","tags":["vuejs3","vite"],"text":"Title: how to use sass using in vuejs3/vite\nTags: vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI starting with vite / vuejs 3\n\nafter installing sass with npm install -D sass I tried to add my _variables.js file this to vite.config.js\n\n```\ncss: {preprocessorOptions: {scss: {additionalData: `@import\" ./src/css/_variables.scss \";`,},},},\n```\n\ndin't work!\n\nit also worked in vue.config\n\n```\ncss: {\n loaderOptions: {\n sass: {\n sassOptions: {\n prependData: `@import\" @ / css / _variables.scss \";`,\n }\n }\n }\n },\n```\n\nafter this tried to import the file in main.js import \"./css/_variables.scss\"\n\nUnfortunately, my components cannot find the variables, where is the error\n\n========================================\n\nTop Answer:\nVite is a litte bit different\n\n```\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n css: {\n preprocessorOptions: {\n scss: {\n additionalData: `\n @import \"./src/styles/_animations.scss\";\n @import \"./src/styles/_variables.scss\";\n @import \"./src/styles/_mixins.scss\";\n @import \"./src/styles/_helpers.scss\";\n `\n }\n }\n }\n})\n```\n\n========================================\n\nCode:\n```text\ncss: {preprocessorOptions: {scss: {additionalData: `@import\" ./src/css/_variables.scss \";`,},},},\n```\n\n```text\ncss: {\n     loaderOptions: {\n       sass: {\n         sassOptions: {\n            prependData: `@import\" @ / css / _variables.scss \";`,\n         }\n       }\n     }\n   },\n```\n\n```json\n// package.json\n{\n  \"dependencies\": {\n   ...\n    \"vue\": \"^3.0.5\"\n  },\n  \"devDependencies\": {\n    ...\n    \"sass\": \"^1.32.11\",\n    \"vite\": \"^2.2.3\"\n  }\n}\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\nexport default defineConfig({\n  plugins: [vue()]\n})\n```\n\n```html\n// App.vue\n<template>...</template>\n<script>...</script>\n\n<style lang=\"scss\">\n@import \"./assets/style.scss\";\n</style>\n```\n\n```css\n// style.scss\n[data-theme=\"dark\"] {\n  --bg-color1: #121416;\n  --font-color: #f4f4f4;\n}\n[data-theme=\"light\"] {\n  --bg-color1: #f4f4f4;\n  --font-color: #121416;\n}\n...\nbody {\n  background-color: var(--bg-color1);\n  color: var(--font-color);\n}\n```\n\n```text\nyarn add -D sass\n```\n\n```text\nvue.config.js\n```\n\n```js\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  css: {\n    preprocessorOptions: {\n      scss: {\n        additionalData: `\n          @import \"./src/styles/_animations.scss\";\n          @import \"./src/styles/_variables.scss\";\n          @import \"./src/styles/_mixins.scss\";\n          @import \"./src/styles/_helpers.scss\";\n        `\n      }\n    }\n  }\n})\n```\n\n```text\nnpm add -D sass\n```\n\n```text\n<style lang=\"scss\">\n// OR\n<style lang=\"sass\">\n```\n\n```text\nnpm i -D sass\n```\n\n```text\n\"devDependencies\": {\n\"@types/react\": \"^18.0.17\",\n\"@types/react-dom\": \"^18.0.6\",\n\"@vitejs/plugin-react\": \"^2.1.0\",\n\"vite\": \"^3.1.0\"   }\n```\n\n```text\nnpm cache clean --force or npm cache clean -f\n```\n\n```text\n# .scss and .sass\nnpm add -D sass\n\n# .less\nnpm add -D less\n\n# .styl and .stylus\nnpm add -D stylus\n```\n\n```text\n\"devDependencies\": {\n    \"@types/react\": \"^18.0.17\",\n    \"@types/react-dom\": \"^18.0.6\",\n    \"@vitejs/plugin-react\": \"^2.1.0\",\n    \"sass\": \"^1.55.0\",\n    \"vite\": \"^3.1.0\"\n  }\n```\n\n```js\n// vite.config.ts\n\nexport default defineConfig({\n  plugins: [\n    vue(),\n    ...\n  ],\n  ...,\n  css: {\n    preprocessorOptions: {\n      scss: {\n        additionalData: ` // just variables loaded globally\n          @import \"./src/assets/styles/setup/fonts\";\n          @import \"./src/assets/styles/setup/colors\";\n          @import \"./src/assets/styles/setup/mixins\";\n        `\n      }\n    }\n  }\n});\n\n// App.vue\n\n<style lang=\"scss\"> // the main file that imports everything related with styles\n@import \"@/assets/styles/main.scss\";\n</style>\n```\n\n```text\n<style lang=\"scss\">\n```\n\n```text\nnpm install -D sass\n```\n\n```text\nimport '@/assets/scss/styles.scss';\n```\n\n```text\nimport { fileURLToPath, URL } from 'node:url'\n```\n\n```text\nresolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url))\n    }\n  },\n```\n\n```text\nmain.js\n```\n\n```text\n@\n```\n\n```text\nvite.config.js\n```\n\n========================================\n\nComments:\n- Have you managed to compile any nested SCSS imports? I'm struggling to figure this out myself. Trying to get material components web to work. Seems like there is an issue with the @forward syntax. github.com/vitejs/vite/issues/4140\n- Have you tried to import your scss files in `main.js`? For me it works to import multiple scss files via `.&#47;` there.\n- Thanks. I was originally doing that myself too. Seems to be a bug with material design.\n- This is the correct answer if you are importing for use in all components, avoiding repeat imports.\n- This works brilliantly. Just remember to use `@use` instead of `@import` if it complains about `@forward` rules needing to be written before other rules.\n- you rock sir!! This was kicking my butt.\n- What syntax did you use to add from your index.html?\n- Remember to run command \"npm run dev\" again for it to take effect.\n- This is not question related to React.js but Vue but overall it similar fix path\n- What got it working for me was really the ` &#47;&#47; the main file that imports everything related with styles @import \"@&#47;assets&#47;styles&#47;main.scss\"; ` with my specific location for the scss in the App.Vue\n- Great, this Vite configuration and the importing in App.vue with lang=sass worked for me. Thanks. I was also able to import within the , maybe because I have just 'sass' installed too.","metadata":{"transformedAt":"2026-08-18T18:33:46.391Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":281,"estimatedTokens":1368}}25{"id":"stack-66275174","source":"stackoverflow","questionId":66275174,"title":"Enable sourcemaps in Vue-Vite","tags":["vue.js","vuejs3","bugsnag","vite"],"text":"Title: Enable sourcemaps in Vue-Vite\nTags: vue.js, vuejs3, bugsnag, vite\nSource: Stack Overflow\n\nQuestion:\nIs it possible to enable sourcemaps in Vue-Vite in production environment?\n\nI would like to use it for Bugsnag.\n\nCan't find anything about it in the docs.\n\nIn dev it just works out of the box.\n\n========================================\n\nTop Answer:\nVite 2.x (docs):\n\n```\n// vite.config.js\nexport default {\n build: {\n sourcemap: true,\n },\n}\n```\n\nVite 1.x:\n\n```\n// vite.config.js\nexport default {\n sourcemap: true,\n}\n```\n\n========================================\n\nCode:\n```js\n/**\n* @type {import('vite').UserConfig}\n*/\nexport default {\n    plugins: [vue()],\n    build: {\n        sourcemap: true,\n    },\n}\n```\n\n```text\n<projectRoot>/vite.config.js\n```\n\n```js\n// vite.config.js\nexport default {\n  build: {\n    sourcemap: true,\n  },\n}\n```\n\n```js\n// vite.config.js\nexport default {\n  sourcemap: true,\n}\n```\n\n```js\nimport ...;\n...\n\nexport default defineConfig({\n  plugins: [\n    vue(),\n    checker({\n      typescript: true,\n      vueTsc: true,\n    }),\n  ],\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url)),\n    },\n  },\n  css: {\n    devSourcemap: true,\n  },\n});\n```\n\n```text\nVite 2.9\n```\n\n```text\nvite.config.ts\n```\n\n```text\ndevSourcemap\n```\n\n```text\ncss\n```\n\n```text\ntrue\n```\n\n```text\nvite.config.ts\n```\n\n```js\nimport { defineConfig } from 'vite'\n        \n        // https://vitejs.dev/config/\n        export default defineConfig({\n          css: {\n            devSourcemap: true,\n          },\n        })\n```\n\n```text\nexport default {\n  build: {\n    sourcemap: true,\n  },\n}\n```\n\n```text\nexport default defineConfig({\n  plugins: [\n    vue(),\n  ],\n  css: {\n    devSourcemap: true // <-- works\n  }\n});\n```\n\n========================================\n\nComments:\n- Where is checker being defined?","metadata":{"transformedAt":"2026-08-18T18:33:46.391Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":152,"estimatedTokens":457}}26{"id":"stack-73045616","source":"stackoverflow","questionId":73045616,"title":"Vite manifest not found","tags":["php","laravel","vite","laravel-9"],"text":"Title: Vite manifest not found\nTags: php, laravel, vite, laravel-9\nSource: Stack Overflow\n\nQuestion:\nI'm working on a project that is using `laravel 9` and `Vite` with `laravel-vite`,\n\nIn the Dev environment everything works fine, but in production on the cPanel server I have the following issue:\n\n```\nVite manifest not found at: /home/???????/cart_shop/public/build/manifest.json\n\n# With \n\nMissing Vite Manifest File\nDid you forget to run `npm install && npm run dev`?\n```\n\nI tried to solve the problem but nothing work, I need to change the public folder and the sup folder build file place from vite.config.js but I don't find the way to do that.\n\nNote that: the file sequence is changed in cPanel shared server from\n\n```\n- home\n - public_html\n - cart_shop\n - Root\n - public\n - etc\n```\n\nTo\n\n```\n- home\n - public_html\n - public files and folders // I changed the index URLs too.\n- cart_shop\n - Root\n - etc\n```\n\nmy `vite.config.js` config is like:\n\n```\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\nimport vue from '@vitejs/plugin-vue';\n\nexport default defineConfig({\n plugins: [\n laravel({\n input: 'resources/js/app.js',\n }),\n vue({\n template: {\n transformAssetUrls: {\n base: null,\n includeAbsolute: false,\n },\n },\n }),\n ],\n});\n```\n\n========================================\n\nTop Answer:\nIn my case, I have solved this problem by doing some things.\n\nFirst of all, I have made sure required npm packages are installed by running this command\n\n```\nnpm install\n```\n\nAfter that, I have run\n\n```\nnpm run build\n```\n\nTo build assets and create the manifest file.\n\n========================================\n\nCode:\n```text\nVite manifest not found at: /home/???????/cart_shop/public/build/manifest.json\n\n# With \n\nMissing Vite Manifest File\nDid you forget to run `npm install && npm run dev`?\n```\n\n```text\n- home\n    - public_html\n        - cart_shop\n           - Root\n           - public\n           - etc\n```\n\n```text\n- home\n    - public_html\n       - public files and folders  // I changed the index URLs too.\n- cart_shop\n    - Root\n    - etc\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\nimport vue from '@vitejs/plugin-vue';\n\nexport default defineConfig({\n    plugins: [\n        laravel({\n            input: 'resources/js/app.js',\n        }),\n        vue({\n            template: {\n                transformAssetUrls: {\n                    base: null,\n                    includeAbsolute: false,\n                },\n            },\n        }),\n    ],\n});\n```\n\n```text\nlaravel 9\n```\n\n```text\nVite\n```\n\n```text\nlaravel-vite\n```\n\n```text\nvite.config.js\n```\n\n```text\nsudo npm cache clean -f\nsudo npm install -g n\nsudo n stable\n```\n\n```text\nsudo n latest\n```\n\n```text\nsudo apt-get install --reinstall nodejs-legacy     # fix /usr/bin/node\n```\n\n```text\nsudo n rm 6.0.0     # replace number with version of Node that was installed\n  sudo npm uninstall -g n\n```\n\n```text\npublicDirectory\n```\n\n```text\nlaravel-vite-plugin\n```\n\n```text\nvite.config.js\n```\n\n```text\nbuild\n```\n\n```text\npublic\n```\n\n```text\nbublic_html\n```\n\n```text\nnpm run build\n```\n\n```bash\nsudo chown www-data:www-data -R public/build/\nsudo chmod g+w -R public/build/\n```\n\n```text\nmanifest.json\n```\n\n```text\nnode\n```\n\n```text\n14+\n```\n\n```text\nv16.17.0\n```\n\n```text\nnode\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm install\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm run dev\n```\n\n```text\n@vite(['resources/sass/app.scss', 'resources/js/app.js'])\n```\n\n```text\n<head>\n```\n\n```text\napp.blade.php\n```\n\n```text\nnpm run build\n```\n\n```text\npublic\n```\n\n```text\npublic_html\n```\n\n```text\npublic\n```\n\n```text\nbuild\n```\n\n```text\nnvm use 19\nnpm run dev\n```\n\n```text\nnpm install --save-dev vite laravel-vite-plugin\n```\n\n```text\n\"scripts\": { \"dev\": \"vite\", \"build\": \"vite build\" }\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm run dev\n```\n\n```text\npublic_html\n```\n\n```text\npublic\n```\n\n```text\nmanifest.json\n```\n\n```text\npublic/build\n```\n\n```text\nmanifest.json\n```\n\n```text\npublic_html\n```\n\n```text\n/public/build\n```\n\n```text\n.gitignore\n```\n\n```text\nnpm install && npm run build\n```\n\n```text\n/public/build\n```\n\n```text\n.gitignore\n```\n\n```text\nnpm install --save-dev vite laravel-vite-plugin\n```\n\n```text\nnpm run build\n```\n\n```text\nphp artisan serve\n```\n\n```text\nnpm install\n```\n\n```text\nnpm run build\n```\n\n```text\n<?php\n\nuse Illuminate\\Http\\Request;\n\ndefine('LARAVEL_START', microtime(true));\n\n// Determine if the application is in maintenance mode...\nif (file_exists($maintenance = __DIR__.'/../laravel-core/storage/framework/maintenance.php')) {\n    require $maintenance;\n}\n\n// Register the Composer autoloader...\nrequire __DIR__.'/../laravel-core/vendor/autoload.php';\n\n\n// Bootstrap Laravel and handle the request...\n$app = require_once __DIR__.'/../laravel-core/bootstrap/app.php';\n\napp()->usePublicPath(__DIR__); // app bind here\n\n$app->handleRequest(Request::capture());\n```\n\n```text\nnpm install\n```\n\n```text\nnpm run build\nnpm run dev\n```\n\n```text\nnode_modules\n```\n\n```text\n\\Illuminate\\Support\\Facades\\Vite::useBuildDirectory('.');\n```\n\n```text\nnpm install\n```\n\n```text\nnpm run build\n```\n\n```text\nnvm install 20\n```\n\n```text\nnvm use 20.xx.xx\n```\n\n========================================\n\nComments:\n- What is the node version you have? `node -v`\n- node : `v16.13.1` with npm: `8.14.0`\n- Maybe you need to change your build directory in vite config,, open vite.config.js and add under input array `buildDirectory: '..&#47;..&#47;public&#47;build',` and see if it works.\n- were i can put `buildDirectory: '..&#47;public&#47;build',` inside `export default defineConfig` or in ` plugins:` can you send me the conf sequence.\n- I had the same problem, and I solved it with `npm run build` command\n- There is no such hot file in the public folder. Can you please be more specific?\n- firstly you need to add this code in your vite.config.js import { defineConfig } from 'vite'; import laravel from 'laravel-vite-plugin'; export default defineConfig({ buildDirectory: ['build',], plugins: [ laravel([ 'resources/css/app.css', 'resources/js/app.js', ]), ], server: { https: true, host: '0.0.0.0', }, }); ANd then move all the files in public/build to public_html except build/manifest.json and then it will work\n- done this commands sudo npm cache clean -f sudo npm install -g n and after that done this command sudo n latest then fixed issue\n- Also works for Debian Bullseye (v11.6), where the stable version of the node package is only 12.22. You may need to delete/move an existing */usr/local/bin/node* and symlink /usr/local/n/versions/node/18.14.2/bin/node (or whichever version) to it. Once this is done, `npm run build` will work.\n- Why would the `www-data` user need to write to this directory?\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- This worked for me, but it is not included in the instructions at Tailwindcss.\n- 'npm run build' solved the issue for me.\n- It works now , thank you . i try a lot of solutions\n- Thank you, duplication helped! I'm using hostinger, it is shared hosting too, but it has `ssh` and you can clone code via `git` by connectin to server itself hostinger.lt?REFERRALCODE=1MURASHKAAR72\n- Why would you do this when cPanel supports Git? Create a git repository within your cpanel. Push your local project to the server. Create a domain/sub-domain and point to the path including the public directory.\n- @Wade some free tier cpanels\n- @CyberPunkCodes, Hostinger has no cpanel.\n- For some obscure reason, my implementation was looking for the manifest in: `app&#47;Providers&#47;public_html&#47;build`, so I put my copy there, and it works.\n- Restarting the Terminal after following that procedure is important. It has worked for me.\n- This worked for me.\n- This worked for me , I initially had \\Illuminate\\Support\\Facades\\Vite::useBuildDirectory('.'); anytime i do a config:cache i get this error , explicitly specifying the build directory worked for me - \\Illuminate\\Support\\Facades\\Vite::useBuildDirectory('./build&zwnj;&#8203;');\n- Just a suggestion: remove **/public/build** from gitignore file. You'll never forget to update correct files when execute **npm run build**","metadata":{"transformedAt":"2026-08-18T18:33:46.391Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":67,"totalLines":441,"estimatedTokens":2089}}27{"id":"stack-70522494","source":"stackoverflow","questionId":70522494,"title":"Multiple entry points in Vite","tags":["vue.js","vite"],"text":"Title: Multiple entry points in Vite\nTags: vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI have a Vue2 project with Webpack, and I'm trying to switch from Webpack to Vite.\n\nIn `webpack.common.js`, I have multiple entry points:\n\n```\nmodule.exports = {\n entry: {\n appSchool: './resources/school/app.js',\n appStudent: './resources/student/app.js',\n appAuth: './resources/auth/app.js'\n },\n ...\n}\n```\n\nHow do I write this in `vite.config.js`?\n\n========================================\n\nTop Answer:\nIn addition to tony19's answer, you can also just use `resolve` to generate the paths, makes the code a lot more readable:\n\n```\n// vite.config.js\nimport { resolve } from 'path'\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\nexport default defineConfig({\n plugins: [vue()],\n build: {\n rollupOptions: {\n input: {\n appSchool: resolve(__dirname, 'resources/school/index.html'),\n appStudent: resolve(__dirname, 'resources/student/index.html'),\n appAuth: resolve(__dirname, 'resources/auth/index.html'),\n },\n },\n },\n})\n```\n\nSee the official docs for a multipage app.\n\n========================================\n\nCode:\n```js\nmodule.exports = {\n    entry: {\n        appSchool: './resources/school/app.js',\n        appStudent: './resources/student/app.js',\n        appAuth: './resources/auth/app.js'\n    },\n    ...\n}\n```\n\n```text\nwebpack.common.js\n```\n\n```text\nvite.config.js\n```\n\n```js\n// vite.config.js\nimport { fileURLToPath } from 'url'\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\nexport default defineConfig({\n  plugins: [vue()],\n  build: {\n    rollupOptions: {\n      input: {\n        appSchoool: fileURLToPath(new URL('./resources/school/index.html', import.meta.url)),\n        appStudent: fileURLToPath(new URL('./resources/student/index.html', import.meta.url)),\n        appAuth: fileURLToPath(new URL('./resources/auth/index.html', import.meta.url)),\n      },\n    },\n  },\n})\n```\n\n```text\nbuild.rollupOptions\n```\n\n```text\ninput\n```\n\n```text\nindex.html\n```\n\n```text\napp.js\n```\n\n```text\n./resources/student/index.html\n```\n\n```text\n<script src=\"./app.js\">\n```\n\n```text\ninput\n```\n\n```text\napp.js\n```\n\n```js\n// vite.config.js\nimport { resolve } from 'path'\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\nexport default defineConfig({\n  plugins: [vue()],\n  build: {\n    rollupOptions: {\n      input: {\n        appSchool: resolve(__dirname, 'resources/school/index.html'),\n        appStudent: resolve(__dirname, 'resources/student/index.html'),\n        appAuth: resolve(__dirname, 'resources/auth/index.html'),\n      },\n    },\n  },\n})\n```\n\n```text\nresolve\n```\n\n```js\n// vite.config.ts\n\nimport { fileURLToPath } from \"url\";\n\nexport default {\n  build: {\n    rollupOptions: {\n      input: {\n        ENTRY_POINT: fileURLToPath(new URL(\"./apps/ENTRY_POINT/index.html\", import.meta.url))\n      }\n    }\n  }\n}\n```\n\n```js\n// vite.config.ts\n\nimport { fileURLToPath } from \"url\";\nimport * as glob from \"glob\";\n\nexport default {\n  build: {\n    rollupOptions: {\n      input: glob\n        .sync(fileURLToPath(new URL(\"./apps/*/index.html\", import.meta.url)))\n        .reduce((acc, path) => {\n          const name = path.match(/apps\\/(.*)\\/index.html/)![1];\n          acc[name] = path;\n          return acc;\n        }, {} as Record<string, string>),\n    },\n  },\n};\n```\n\n```text\nimport.meta.url\n```\n\n```text\nfileURLToPath\n```\n\n```text\nglob\n```\n\n========================================\n\nComments:\n- Unable to specify lib name\n- The thing is, `__dirname` won't work in es modules.\n- Well it works for Vitejs. See their official docs.\n- do not forget `base: \".&#47;\"`\n- @s.meijer `import * as path from 'node:path'; let __dirname = path.dirname(import.meta.url.substring('file:&#47;&#47;'.length));`\n- Does this also supersede @andreas's answer from 2023?\n- I didn't check if `resolve` works still but most examples in the docs now tend to use `import.meta.url` and `fileURLToPath` which worked and I assume is more future proof.","metadata":{"transformedAt":"2026-08-18T18:33:46.391Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":206,"estimatedTokens":995}}28{"id":"stack-73298776","source":"stackoverflow","questionId":73298776,"title":"What's the difference between Nuxt and Vite?","tags":["javascript","vue.js","nuxt.js","vite"],"text":"Title: What's the difference between Nuxt and Vite?\nTags: javascript, vue.js, nuxt.js, vite\nSource: Stack Overflow\n\nQuestion:\nI'm learning Vue, and it's ecosystem, and now I read about nuxt.js.\n\nAs I understand, this is tool which help us to build Vue apps, but don't we do the same with vite.js?\n\nWhat's the difference between them?\n\n========================================\n\nComments:\n- I recommend working with Vue quite a bit before going to Nuxt btw. Don't rush the steps and learn the basics of Vue well.\n- Google search engine is reading JavaScript files on page. So you will have well indexed SPA page. But you won't have nice cards on Facebook and other sites and apps with may crawl your page.\n- @Mises even if it works somewhat, it's far from being good enough hence why I'm simplifying by saying it just doesn't. Google is asking you to go the extra mile nowadays, so an SPA is not good enough.\n- Would love to know what does the \"not as powerful\" mean specifically, that would be a good insight for people deciding whether to use nuxt or vite as those two are what vue ssr docs mention as options.\n- @Klesun as explained above, Vite is a bundler so it will only manage that part. Nuxt on the other side, is a powerful Vue app on steroids with a lot things around it (SSR baked in, routes, advanced life cycle hooks etc...) + a huge ecosystem. You can do all of this with Vite but it will require more time/work/knowledge overall. Also, Nuxt is specific to Vue while Vite can be used by any kind of Framework (React, Svelte, Astro etc...).","metadata":{"transformedAt":"2026-08-18T18:33:46.391Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":19,"estimatedTokens":388}}29{"id":"stack-78114219","source":"stackoverflow","questionId":78114219,"title":"Property 'env' does not exist on type 'ImportMeta'.ts(2339)","tags":["javascript","typescript","vue.js","vite"],"text":"Title: Property 'env' does not exist on type 'ImportMeta'.ts(2339)\nTags: javascript, typescript, vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nRecently i begin a project using vue.js and vite, everything run normal when using `npm run dev` but when `npm run build` its keep give me error `Property 'env' does not exist on type 'ImportMeta'.ts(2339)`\n\n```\nimport { createRouter, createWebHistory } from 'vue-router'\nimport HomeView from '../views/HomeView.vue'\n\nconst router = createRouter({\n history: createWebHistory(import.meta.env.BASE_URL),\n routes: [\n {\n path: '/',\n name: 'home',\n component: HomeView\n },\n {\n path: '/about',\n name: 'about',\n // route level code-splitting\n // this generates a separate chunk (About.[hash].js) for this route\n // which is lazy-loaded when the route is visited.\n component: () => import('../views/AboutView.vue')\n }\n ]\n})\n\n// test access to Vite environment variable\nconsole.log(import.meta.env.BASE_URL);\n\nexport default router\n```\n\nHere is my `env.d.ts`\n\n```\n/// \ninterface ImportMeta {\n readonly env: Record;\n}\n```\n\nhere is my `tsconfig.json`\n\n```\n{\n \"files\": [],\n \"references\": [\n {\n \"path\": \"./tsconfig.node.json\"\n },\n {\n \"path\": \"./tsconfig.app.json\"\n },\n {\n \"path\": \"./tsconfig.vitest.json\"\n }\n ],\n \"compilerOptions\": {\n \"module\": \"NodeNext\",\n \"allowJs\": true,\n \"types\": [\"vite/client\"]\n }\n}\n```\n\nI have added compiler options, for vite/client but still resulting the same, any guidance or tips will be really useful. I appreciate any response.\n\n========================================\n\nTop Answer:\nI recently ran into the same issue while working on a `React.ts` project with Vite. Everything worked fine with `npm run dev`, but I kept getting the error Property `'env'` does not exist on type `'ImportMeta'.ts(2339)'` when running `npm run build`.\n\nAfter some research and trial and error, I found a solution that worked for me:\n\n**Create** `vite-env.d.ts` file: At the root of your project (where\n`vite.config.js` or vite.config.ts is located), create a file named\n`vite-env.d.ts`. This file extends TypeScript's type definitions to\ninclude `import.meta.env`.\nenter code here\n\nHere's the content you need:\n\n```\ninterface ImportMetaEnv {\n readonly VITE_YOUR_URL: string;\n readonly VITE_REALM: string;\n readonly VITE_CLIENT_ID: string;\n \n}\n\ninterface ImportMeta {\n readonly env: ImportMetaEnv;\n}\n```\n\n**Update** `tsconfig.json`: Make sure your `tsconfig.json` is configured to\ninclude the type definitions from the `vite-env.d.ts` file. Here’s how\nmine looks:\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"ESNext\",\n \"useDefineForClassFields\": true,\n \"lib\": [\"DOM\", \"DOM.Iterable\", \"ESNext\"],\n \"allowJs\": false,\n \"skipLibCheck\": true,\n \"esModuleInterop\": false,\n \"allowSyntheticDefaultImports\": true,\n \"strict\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Node\",\n \"resolveJsonModule\": true,\n \"isolatedModules\": true,\n \"noEmit\": true,\n \"jsx\": \"react-jsx\",\n \"types\": [\"vite/client\"]\n },\n \"include\": [\"src\", \"vite-env.d.ts\"]\n}\n```\n\n**Restart Your Development Server:** Sometimes, changes to environment\nfiles or TypeScript configuration require restarting your\ndevelopment server. After making the above changes, stop your\ndevelopment server and restart it.\n\n**Access Environment Variables in Your Code:** Now you can safely access\nenvironment variables using `import.meta.env` in your code. Here’s an\nexample:\n\n```\nconst apiUrl = import.meta.env.VITE_YOUR_URL;\n```\n\nFollowing these steps resolved the error for me, and I was able to build my project without any issues. Hope this helps!\n\n========================================\n\nCode:\n```text\nimport { createRouter, createWebHistory } from 'vue-router'\nimport HomeView from '../views/HomeView.vue'\n\nconst router = createRouter({\n  history: createWebHistory(import.meta.env.BASE_URL),\n  routes: [\n    {\n      path: '/',\n      name: 'home',\n      component: HomeView\n    },\n    {\n      path: '/about',\n      name: 'about',\n      // route level code-splitting\n      // this generates a separate chunk (About.[hash].js) for this route\n      // which is lazy-loaded when the route is visited.\n      component: () => import('../views/AboutView.vue')\n    }\n ]\n})\n\n// test access to Vite environment variable\nconsole.log(import.meta.env.BASE_URL);\n\nexport default router\n```\n\n```text\n/// <reference types=\"vite/client\" />\ninterface ImportMeta {\n  readonly env: Record<string, string>;\n}\n```\n\n```text\n{\n  \"files\": [],\n  \"references\": [\n    {\n      \"path\": \"./tsconfig.node.json\"\n    },\n    {\n      \"path\": \"./tsconfig.app.json\"\n    },\n    {\n      \"path\": \"./tsconfig.vitest.json\"\n    }\n  ],\n  \"compilerOptions\": {\n    \"module\": \"NodeNext\",\n    \"allowJs\": true,\n    \"types\": [\"vite/client\"]\n  }\n}\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run build\n```\n\n```text\nProperty 'env' does not exist on type 'ImportMeta'.ts(2339)\n```\n\n```text\nenv.d.ts\n```\n\n```text\ntsconfig.json\n```\n\n```js\n/// <reference types=\"vite/types/importMeta.d.ts\" />\n```\n\n```js\n/// <reference types=\"vite/client\" />\n/// <reference types=\"vite/types/importMeta.d.ts\" />\n```\n\n```text\n^4.4.5\n```\n\n```text\nvite-env.d.ts\n```\n\n```text\nsrc/vite-env.d.ts\n```\n\n```text\ntsconfig.json\n```\n\n```text\nvite-env.d.ts\n```\n\n```text\nv4\n```\n\n```js\ninterface ImportMetaEnv {\n  readonly VITE_YOUR_URL: string;\n  readonly VITE_REALM: string;\n  readonly VITE_CLIENT_ID: string;\n \n}\n\ninterface ImportMeta {\n  readonly env: ImportMetaEnv;\n}\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"DOM\", \"DOM.Iterable\", \"ESNext\"],\n    \"allowJs\": false,\n    \"skipLibCheck\": true,\n    \"esModuleInterop\": false,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\",\n    \"types\": [\"vite/client\"]\n  },\n  \"include\": [\"src\", \"vite-env.d.ts\"]\n}\n```\n\n```js\nconst apiUrl = import.meta.env.VITE_YOUR_URL;\n```\n\n```text\nReact.ts\n```\n\n```text\nnpm run dev\n```\n\n```text\n'env'\n```\n\n```text\n'ImportMeta'.ts(2339)'\n```\n\n```text\nnpm run build\n```\n\n```text\nvite-env.d.ts\n```\n\n```text\nvite.config.js\n```\n\n```text\nvite-env.d.ts\n```\n\n```text\nimport.meta.env\n```\n\n```text\ntsconfig.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\nvite-env.d.ts\n```\n\n```text\nimport.meta.env\n```\n\n```text\n\"include\": [\"tests/**/*.ts\", \"src/**/*.vue\", \"src/**/*.ts\"],\n```\n\n```text\ntsconfig.vitest.ts\n```\n\n```text\nnpm init vue@latest\n```\n\n```text\nvite-env.d.ts\n```\n\n```text\n/// <reference types=\"vite/client\" />\n```\n\n```text\nsrc/vite-env.d.ts\n```\n\n```text\n/// <reference types=\"vite/client\" />\n```\n\n```text\n\"include\": [\"env.d.ts\", \"src/**/*\", \"src/**/*.vue\"],\n```\n\n```text\nnpm create vue@latest\n```\n\n```text\nenv.d.ts\n```\n\n```text\ntsconfig.app.json\n```\n\n```text\nenv.d.ts\n```\n\n```text\nnpm run build\n```\n\n```text\n\"compilerOptions\": {\n    \"types\": [\n      \"vite/client\",\n      \"vitest/globals\",\n      \"@testing-library/jest-dom\"\n    ]\n  }\n```\n\n```text\n// @ts-expect-error Fix: IntelliJ complains about import.meta.env.MODE\n  const env = import.meta.env;\n```\n\n========================================\n\nComments:\n- Hi, I'm facing the same trouble on my project. I'm just copy your env.d.ts content fix it using copilot to: `&#47;&#47;&#47; interface ImportMeta { readonly env: ImportMetaEnv }` and everything works now\n- All I needed to do was set the tsconfing `include` to `[\"vite.config.ts\"]`. I wonder if this happened because we updated vite...\n- This did indeed fix the issue for me, but I am in the dark why I only had to add this in one of 3 projects, while in the others it works without adding this line.\n- @cdonner - glad the answer helped! I have a theory on why one out of your three projects had this issue. Could it be the TypeScipt versions are different? The latest version of TypeScript as of this time of writing is 5.5, and within the release notes there's a mention of a change to Isolated Declarations. Maybe check if the TS versions between your projects are different, and if out-of-date / out-of-sync, then maybe update the TS dependency and see if that helps?\n- @cdonner - also, I've just removed the line: `&#47;&#47;&#47; `, and now no longer see the TSLint error on `import.meta.env` in VS Code. The only change I can think of is a VS Code release update 1.91 (June 2024 release) at the time which also introduced TypeScript 5.5 (e.g. with changes to Isolated Declarations, and as a possible consequence, have a positive effect on correctly inferring the import meta declarations automatically(?)\n- Thanks, this works on a astro project if you want to reference the .env files In a .ts file. add this line to the env.d.ts\n- It helped. I wonder why isn't this file included in ReactRouter templates?\n- Here's the link to the current Vite docs for those not interested in reading through the GitHub issue that covers many previous version of Vite. vite.dev/guide/features.html#client-types\n- Easiest and simplest solution here. Worked for me in React for vite 5.0.0 just one thing this answer missed for probably someone new that you need to add it in your tsconfig.json","metadata":{"transformedAt":"2026-08-18T18:33:46.391Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":47,"totalLines":428,"estimatedTokens":2295}}30{"id":"stack-76898372","source":"stackoverflow","questionId":76898372,"title":"Getting \"Type 'Element' is not assignable to type 'ReactNode'.\" when creating a React app with Vite","tags":["typescript","vite","react-typescript"],"text":"Title: Getting \"Type 'Element' is not assignable to type 'ReactNode'.\" when creating a React app with Vite\nTags: typescript, vite, react-typescript\nSource: Stack Overflow\n\nQuestion:\nI have created a React app with Typescript with npm create vite@latest. When I have done like this before everything have been working fine but when I did it today I get the errors:\nType 'Element' is not assignable to type 'ReactNode'.\nType 'Element' is not assignable to type 'ReactPortal'.\n\nThe page works fine in the browser without any errors though.\n\nI'm using Visual studio code version: 1.81.1 and Typescript version 5.1.6.\n\nThese errors also shows up when I open previous projects that have been working fine in the past.\n\nI have tried changing settings in tsconfig.json, for example moduleResolution: bundler --> node, but it did not help.\n\n```\nimport { useState } from 'react'\nimport reactLogo from './assets/react.svg'\nimport viteLogo from '/vite.svg'\nimport './App.css'\n\nfunction App() {\n const [count, setCount] = useState(0)\n\n return (\n <>\n \n \n \n \n \n \n \n \n \n\n### Vite + React\n\n \n setCount((count) => count + 1)}>\n count is {count}\n \n \n Edit `src/App.tsx` and save to test HMR\n \n\n \n \n Click on the Vite and React logos to learn more\n \n\n \n )\n}\n\nexport default App\n```\n\nImage of code and errors\n\n========================================\n\nTop Answer:\nUpgrade your \"@types/react\" in devDependencies to 18.2.25 as such:\n\n```\n\"devDependencies\": {\n ...\n \"@types/react\": \"18.2.25\",\n ...\n },\n```\n\nalso in my case, i had to add the same version to \"overrides\" too, while keeping react-dom 18.2.0\n\n========================================\n\nCode:\n```text\nimport { useState } from 'react'\nimport reactLogo from './assets/react.svg'\nimport viteLogo from '/vite.svg'\nimport './App.css'\n\nfunction App() {\n  const [count, setCount] = useState(0)\n\n  return (\n    <>\n      <div>\n        <a href=\"https://vitejs.dev\" target=\"_blank\">\n          <img src={viteLogo} className=\"logo\" alt=\"Vite logo\" />\n        </a>\n        <a href=\"https://react.dev\" target=\"_blank\">\n          <img src={reactLogo} className=\"logo react\" alt=\"React logo\" />\n        </a>\n      </div>\n      <h1>Vite + React</h1>\n      <div className=\"card\">\n        <button onClick={() => setCount((count) => count + 1)}>\n          count is {count}\n        </button>\n        <p>\n          Edit <code>src/App.tsx</code> and save to test HMR\n        </p>\n      </div>\n      <p className=\"read-the-docs\">\n        Click on the Vite and React logos to learn more\n      </p>\n    </>\n  )\n}\n\nexport default App\n```\n\n```text\n\"@types/react\"\n```\n\n```text\n\"devDependencies\"\n```\n\n```text\nnpm i\n```\n\n```text\nnpm i --legacy-peers-deps\n```\n\n```text\nnpm audit fix\n```\n\n```text\n\"devDependencies\": {\n    ...\n    \"@types/react\": \"18.2.25\",\n    ...\n  },\n```\n\n```text\ntsconfig.json\n```\n\n```text\ncompilerOptions.lib\n```\n\n```text\ncompilerOptions.module\n```\n\n```text\n\"moduleResolution\": \"Bundler\"\n```\n\n```text\ncompilerOptions\n```\n\n```bash\nyarn upgrade @types/react@latest @types/react-dom@latest -D\n```\n\n```text\n@types/react\n```\n\n```text\n@types/react-dom\n```\n\n```text\n\"compilerOptions\": {\n    \"paths\": {\n      \"react\": [\"./node_modules/@types/react\"]\n    }\n  }\n```\n\n```text\nTS2322: Type '({ todos, setTodos }: Props) => JSX.Element' is not assignable to type 'FC<{}>'.\nTypes of parameters '__0' and 'props' are incompatible.\nType '{}' is missing the following properties from type 'Props': todos, setTodos\n 8 | };\n 9 |\n10 | const todoList: React.FC  = ({todos, setTodos}: Props) => {\n   |       ^^^^^^^^\n11 |   return (\n12 |     <div className=\"todos\">\n13 |\n```\n\n```text\nconst todoList: React.FC<Props> = ({todos, setTodos})\n```\n\n```text\nimport React from \"react\"\n```\n\n========================================\n\nComments:\n- I think this could be the solution for you too. Try it!\n- I found no way to apply this solution to my problem. My theory is that it's got something to do with Typescript since i get the errors in my old project as well.\n- Please provide enough code so others can better understand or reproduce the problem.\n- Solved this by clearing VS Codes cache: bobbyhadz.com/blog/vscode-clear-cache\n- If you are updating types, I am guessing you will also need to update react version for it to match the dev dependencies, no?\n- While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.\n- That site is so bad it crashed Chrome. You can't trust instructions from site that can't even keep it together themselves.\n- Wish I knew WHY, but this worked for me\n- yarn add --dev @types/react @types/react-dom\n- or: yarn add --dev @types/react @types/react-dom\n- Should only be necessary if you’re still on React 16. Consider upgrading.","metadata":{"transformedAt":"2026-08-18T18:33:46.391Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":221,"estimatedTokens":1200}}31{"id":"stack-70714690","source":"stackoverflow","questionId":70714690,"title":"Buffer is not defined in React-vite","tags":["reactjs","buffer","vite"],"text":"Title: Buffer is not defined in React-vite\nTags: reactjs, buffer, vite\nSource: Stack Overflow\n\nQuestion:\nBuffer is not defined after migrating from CRA(create react app)\n\n\"vite\": \"^2.7.12\"\n\nI try to add plugins, add define for Buffer, but it's not work.\n\n```\nconst viteConfig = defineConfig({\n/* define: {\n \"Buffer\": {}\n },*/\n plugins: [reactRefresh(), react()],\n build: {\n rollupOptions: {\n input: {\n main: resolve('index.html'),\n },\n },\n },\n clearScreen: false\n});\n```\n\n========================================\n\nTop Answer:\nThe easiest solution I found was to install `vite-plugin-node-polyfills` (npm, repo).\n\n`npm i -D vite-plugin-node-polyfills`\n\nBelow is a basic version of the config file, `vite.config.js`, using this plugin:\n\n```\nimport { defineConfig } from 'vite'\nimport { nodePolyfills } from 'vite-plugin-node-polyfills'\n\nexport default defineConfig({\n plugins: [nodePolyfills()]\n})\n```\n\nThe current accepted answer recommends `@esbuild-plugins/node-globals-polyfill`, which is outdated according to its repository, while the replacement suggested there, `esbuild-plugin-polyfill-node`, doesn't work for vite (see issue here).\n\n========================================\n\nCode:\n```text\nconst viteConfig = defineConfig({\n/*    define: {\n        \"Buffer\": {}\n    },*/\n    plugins: [reactRefresh(), react()],\n    build: {\n        rollupOptions: {\n            input: {\n                main: resolve('index.html'),\n            },\n        },\n    },\n    clearScreen: false\n});\n```\n\n```text\nexport default defineConfig({\n    // ...other config settings\n    optimizeDeps: {\n        esbuildOptions: {\n            // Node.js global to browser globalThis\n            define: {\n                global: 'globalThis'\n            },\n            // Enable esbuild polyfill plugins\n            plugins: [\n                NodeGlobalsPolyfillPlugin({\n                    buffer: true\n                })\n            ]\n        }\n    }\n})\n```\n\n```text\nimport { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'\n```\n\n```text\nyarn install process util buffer events\nyarn add @esbuild-plugins/node-modules-polyfill\n```\n\n```text\nimport GlobalPolyFill from \"@esbuild-plugins/node-globals-polyfill\";\nimport react from \"@vitejs/plugin-react\";\nimport { resolve } from \"path\";\nimport { defineConfig } from \"vite\";\n\nexport default defineConfig({\n    plugins: [react()],\n    optimizeDeps: {\n        esbuildOptions: {\n            define: {\n                global: \"globalThis\",\n            },\n            plugins: [\n                GlobalPolyFill({\n                    process: true,\n                    buffer: true,\n                }),\n            ],\n        },\n    },\n    resolve: {\n        alias: {\n            process: \"process/browser\",\n            stream: \"stream-browserify\",\n            zlib: \"browserify-zlib\",\n            util: \"util\",\n        },\n    },\n});\n```\n\n```text\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\" />\n  <link rel=\"icon\" type=\"image/svg+xml\" href=\"/src/assets/images/favicon.svg\" />\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n  <title>Vite App</title>\n  <script>\n    window.global = window;\n  </script>\n  <script type=\"module\">\n    import process from \"process\";\n    import EventEmitter from \"events\";\n    import {Buffer} from \"buffer\";\n    window.Buffer = Buffer;\n    window.process = process;\n    window.EventEmitter = EventEmitter;\n  </script>\n</head>\n\n<body>\n  <div id=\"root\"></div>\n  <script type=\"module\" src=\"./src/index.js\"></script>\n</body>\n</html>\n```\n\n```text\n<html lang=\"en\">\n  <head>\n    <script type=\"module\">\n      import { Buffer } from \"buffer\";\n      window.Buffer = Buffer;\n    </script>   \n   ...\n```\n\n```text\nimport process from \"process\";\n      window.process = process;\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'\nimport { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill'\nimport rollupNodePolyFill from 'rollup-plugin-polyfill-node'\n\nexport default defineConfig({\n  plugins: [vue()],\n  base: '', \n  optimizeDeps: {\n    esbuildOptions: {\n      // Node.js global to browser globalThis\n      define: {\n        global: 'globalThis'\n      },\n      // Enable esbuild polyfill plugins\n      plugins: [\n        NodeGlobalsPolyfillPlugin({\n          buffer: true, \n          process: true,\n        }), \n        NodeModulesPolyfillPlugin() \n      ]\n    }\n  }, \n  build: {\n    rollupOptions: {\n      plugins: [\n        rollupNodePolyFill()\n      ]\n    }\n  }\n})\n```\n\n```text\nyarn add buffer\n```\n\n```text\nprocess\n```\n\n```text\nutil\n```\n\n```text\nprocess\n```\n\n```text\n@esbuild-plugins\n```\n\n```text\nvite dev\n```\n\n```text\nrollup-plugin-polyfill-node\n```\n\n```text\nvite build\n```\n\n```text\nvite.config.ts\n```\n\n```text\nrollup-plugin-polyfill-node\n```\n\n```text\nrollup-plugin-node-polyfills\n```\n\n```text\nnpm i -D rollup-plugin-polyfill-node\n```\n\n```text\nimport nodePolyfills from 'rollup-plugin-polyfill-node'\n```\n\n```text\nrollupOptions: {\n  plugins: [\n    // ...plugins\n    nodePolyfills(),\n  ],\n  // ...rollupOptions\n},\n```\n\n```text\nvite.config.ts\n```\n\n```ts\nimport { defineConfig } from 'vite';\n// added below polyfills to make near-api-js work with vite\n// npm install --dev @esbuild-plugins/node-globals-polyfill\nimport { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill';\n// npm install --dev @esbuild-plugins/node-modules-polyfill\nimport { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill';\n\nfs.rmSync('dist', { recursive: true, force: true }); // v14.14.0\n\nexport default defineConfig({\n  plugins: [],\n  build: {\n    commonjsOptions: {\n      include: [],\n    },\n  },\n  optimizeDeps: {\n    disabled: false,\n    esbuildOptions: {\n      // Enable esbuild polyfill plugins\n      plugins: [\n        NodeGlobalsPolyfillPlugin({\n          process: true,\n          buffer: true,\n        }),\n        NodeModulesPolyfillPlugin(),\n      ],\n    },\n  },\n});\n```\n\n```text\nvite.config.ts\n```\n\n```bash\nnpm i buffer\n```\n\n```js\nimport {Buffer} from 'buffer';\n...\nBuffer.from(...\n```\n\n```text\nbuffer\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport { nodePolyfills } from 'vite-plugin-node-polyfills'\n\nexport default defineConfig({\n  plugins: [nodePolyfills()]\n})\n```\n\n```text\nvite-plugin-node-polyfills\n```\n\n```text\nnpm i -D vite-plugin-node-polyfills\n```\n\n```text\nvite.config.js\n```\n\n```text\n@esbuild-plugins/node-globals-polyfill\n```\n\n```text\nesbuild-plugin-polyfill-node\n```\n\n```text\nimport inject from '@rollup/plugin-inject'\n\nexport default defineConfig({\n.......\n    build: {\n      rollupOptions: {\n        plugins: [\n          inject({ Buffer: ['buffer', 'Buffer'] })]\n      }\n    }\n})\n```\n\n```text\nnpm install --save  buffer\n```\n\n```text\nconst encodedString = Buffer.from(myString).toString('base64');\n```\n\n```text\nimport { Buffer } from 'buffer'\n```\n\n========================================\n\nComments:\n- i'm using vite.config.ts, how can i stop typescript complaining about missing types for @esbuild-plugins/node-globals-polyfill? couldn't find a @types package. best i've managed is adding //ts-ignore, but not happy about it\n- I'm getting this error while running, Invalid define value (must be an entity name or valid JSON syntax)\n- This only fixes it in development mode for me\n- This one didn't work for me, but `sable`'s answer below did work.\n- Minor fix: import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill';\n- There are some errors in which packages to use in the installation process and furthermore in their usage.\n- Is there a way to do this without importing in via script? I want to build it as a js file.\n- I am not aware of it sorry\n- This caused me to have other issues when trying to import items from react such as `useLayoutEffect`\n- This worked for me in vite 4. Thanks man!\n- Also worked for me with vite + vue 3, thank you!\n- this work only in DEV mode?\n- @LuisFelipeGongoraGarcia By default this adds polyfills in all modes. See the plugin npm or repo link for its options.\n- Great answer, thanks for the detailed analysis of alternative packages! Works in vite 5.0\n- Thanks, It worked for me for the VITE v5.2.11.","metadata":{"transformedAt":"2026-08-18T18:33:46.391Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":39,"totalLines":398,"estimatedTokens":2063}}32{"id":"stack-63724523","source":"stackoverflow","questionId":63724523,"title":"How to add typescript to Vue 3 and Vite project","tags":["typescript","vue.js","vite"],"text":"Title: How to add typescript to Vue 3 and Vite project\nTags: typescript, vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nMy setup: I installed Vue and Vite via the *create-vite-app* module, and then updated all the packages that was generated by 'init vite-app' to the very latest RC versions for Vue and Vite.\n\nNow I want to use typescript for all my code. First I just played around a little bit, and added the *lang=\"ts\"* to the tag in *HelloWorld.vue*. That seems to work, though I have no idea how typescript gets transpiled from the vue file though.\n\nThen I tried to rename the *main.js* to *main.ts*. Now nothing happen.\n\nI was thinking that I just need to install typescript, but then it hit me, why is it working in the *.vue* component then? Am I doing something wrong if I install typescript now?\n\nWhy does typescript work in the vue module (HelloWorld), but no js is generated from the *.ts file?\n\n========================================\n\nTop Answer:\nThere is a template for typescript named `vue-ts`.\nSo running `npm init vite@latest my-vue-app -- --template vue-ts` sets up a typescript vite project.\n\nhttps://vitejs.dev/guide/#scaffolding-your-first-vite-project\n\nUPDATE: reflected Olanrewaju's comment.\n\n========================================\n\nCode:\n```sh\n$ npm init vite-app <project-name>\n$ cd <project-name>\n$ npm install\n```\n\n```sh\n$ npm install typescript\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"target\": \"esnext\",\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"importHelpers\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  }\n}\n```\n\n```js\ndeclare module \"*.vue\" {\n  import { defineComponent } from \"vue\";\n  const Component: ReturnType<typeof defineComponent>;\n  export default Component;\n}\n```\n\n```html\n<script type=\"module\" src=\"/src/main.js\"></script>\n```\n\n```html\n<script type=\"module\" src=\"/src/main.ts\"></script>\n```\n\n```sh\nnpm run dev\n```\n\n```text\ntsconfig.json\n```\n\n```text\nshims-vue.d.ts\n```\n\n```text\nsrc\n```\n\n```text\nshims-vue.d.ts\n```\n\n```text\n.vue\n```\n\n```text\n.ts\n```\n\n```text\nmain.js\n```\n\n```text\nmain.ts\n```\n\n```text\nsrc\n```\n\n```text\nindex.html\n```\n\n```text\n.ts\n```\n\n```text\nvue-ts\n```\n\n```text\nnpm init vite@latest my-vue-app -- --template vue-ts\n```\n\n```text\nnpm init vite@latest\n```\n\n```text\nyarn create vite\n```\n\n```text\npnpm dlx create-vite\n```\n\n========================================\n\nComments:\n- Instead of `create-vite-app`, I would do `git clone https:&#47;&#47;github.com&#47;ktsn&#47;vite-typescript-starter.git`, which uses the latest version of Vue 3 and Vite.\n- Thank you, this helps a lot. Also it kind of confirms that the short answer to the main question is, yes, one just installs typscript and then run tsc -w while coding.\n- I did everything you said but to make it work I had to add `\"strict\": true` the `compilerOptions` object. Source github.com/vuejs/vetur/issues/2534#issuecomment-741752908\n- Shouldn't it be `npm install typescript --save-dev`?\n- @vitejs/create-app is deprecated, use npm init vite instead","metadata":{"transformedAt":"2026-08-18T18:33:46.391Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":143,"estimatedTokens":750}}33{"id":"stack-71726084","source":"stackoverflow","questionId":71726084,"title":"How do I make Vite build my files every time a change is made?","tags":["javascript","vite"],"text":"Title: How do I make Vite build my files every time a change is made?\nTags: javascript, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make Vite build my files and output them into the `dist` folder every time I save/make changes on to my files during development.\n\nHow would I do that?\n\nHere is my `vite.config.development.js` file:\n\n```\nimport { defineConfig } from \"vite\";\nexport default defineConfig({\n base: \"./\",\n build: {\n rollupOptions: {\n output: {\n assetFileNames: \"assets/[name].[ext]\",\n chunkFileNames: \"assets/[name].[ext]\",\n entryFileNames: \"assets/[name].js\",\n },\n },\n write: true,\n },\n});\n```\n\nHere is my scripts in `package.json`:\n\n```\n\"frontend-dev\": \"vite --config vite.config.development.js\",\n```\n\nIt does the usual `localhost:3000` thing, but it does not build my files and put them in the `dist` folder when I make changes to my source code.\n\nCurrently, I have to run a `vite build` npm script every time which takes a lot of time.\n\n========================================\n\nTop Answer:\nBuilding on @Mussini's answer, you have a few options:\n\nAdd `--watch` and optional `--config`: `vite build --watch --config vite.config.ts` on cli\n\nAdd to package.json:\n\n```\n{\n \"name\": \"frontend\",\n ...\n \"scripts\": {\n \"dev\": \"vite\",\n ...\n \"build-watch\": \"vite build --watch --config ./vite.config.js\",\n \"build\": \"vite build\",\n```\n\nIntegrate `--watch` into the vite.config.ts which adds watching to the build cmd by default (`vite build` does not exit!)\n\n```\nexport default defineConfig({\n build: {\n watch: './vite.config.js',\n```\n\nYou likely want option 2 and use with `npm run build-watch`\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from \"vite\";\nexport default defineConfig({\n    base: \"./\",\n    build: {\n        rollupOptions: {\n            output: {\n                assetFileNames: \"assets/[name].[ext]\",\n                chunkFileNames: \"assets/[name].[ext]\",\n                entryFileNames: \"assets/[name].js\",\n            },\n        },\n        write: true,\n    },\n});\n```\n\n```text\n\"frontend-dev\": \"vite --config vite.config.development.js\",\n```\n\n```text\ndist\n```\n\n```text\nvite.config.development.js\n```\n\n```text\npackage.json\n```\n\n```text\nlocalhost:3000\n```\n\n```text\ndist\n```\n\n```text\nvite build\n```\n\n```text\nvite build --watch\n```\n\n```text\nvite build --watch --config vite.config.development.js\n```\n\n```text\n--watch\n```\n\n```text\n--watch\n```\n\n```text\ndist\n```\n\n```text\n{\n  \"name\": \"frontend\",\n  ...\n  \"scripts\": {\n    \"dev\": \"vite\",\n    ...\n    \"build-watch\": \"vite build --watch --config ./vite.config.js\",\n    \"build\": \"vite build\",\n```\n\n```text\nexport default defineConfig({\n  build: {\n    watch: './vite.config.js',\n```\n\n```text\n--watch\n```\n\n```text\n--config\n```\n\n```text\nvite build --watch --config vite.config.ts\n```\n\n```text\n--watch\n```\n\n```text\nvite build\n```\n\n```text\nnpm run build-watch\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport { exec } from 'node:child_process';\n\n // https://vitejs.dev/config/\n export default defineConfig({\n    base: \"\",\n    publicDir: \"public\",\n    // ...more Vite configs....\n    plugins: [\n      { \n        name: 'run-script-on-change',\n        handleHotUpdate({ file }) {\n          console.log(`File changed: ${file}`);\n          // Add your script execution logic here\n          exec('node scripts/run-on-file-change.js', \n           (err, \n           stdout, stderr) => {\n           if (err) {\n             console.error(`Error executing script: ${err}`);\n             return;\n           }\n           console.info(`Script output: ${stdout}`);\n           if (stderr) {\n              console.error(`Script error output:{stderr}`);\n           }\n       });\n      }\n    }]\n })\n```\n\n```text\nscripts/run-on-file-change.js\n```\n\n```text\nvite dev\n```\n\n========================================\n\nComments:\n- What are you trying to do? Do you want to see the development files everytime you make a change on the filesystem?\n- @RahilWazir yeah, I have an express server that serves static files from the build folder 'dist', so everytime I make a change during development, I want to build the new files to the dist folder so my express server can get the new updated build files\n- is there a way to do this for the `vite dev` command? --watch isn't a valid flag and I have to send an API request every time I make a change to trigger a rebuild.\n- In dev Vite does not trigger a build, so it wouldn't make sense to use `--watch`. Perhaps you can leverage the HMR API to perform an action on changes, or use a plugin like `vite-plugin-run`.\n- Is there a way to configure this to work on the public dir?\n- Inside the package.json in the scripts section I added this to get it to watch in dev mode: \"watch-dev\": \"vite build --mode=development --watch\" and on the command line I just run: npm run watch-dev Took me a while to figure this out - hope it helps","metadata":{"transformedAt":"2026-08-18T18:33:46.391Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":226,"estimatedTokens":1212}}34{"id":"stack-73033899","source":"stackoverflow","questionId":73033899,"title":"plugin:vite:import-analysis - Failed to parse source for import analysis because the content contains invalid JS syntax. - Vue 3","tags":["javascript","vuejs3","vite"],"text":"Title: plugin:vite:import-analysis - Failed to parse source for import analysis because the content contains invalid JS syntax. - Vue 3\nTags: javascript, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI've updated my project from Vite 2.x to Vite 3.0.2 and suddenly i got this error:\n\n[plugin:vite:import-analysis] Failed to parse source for import\nanalysis because the content contains invalid JS syntax. If you are\nusing JSX, make sure to name the file with the .jsx or .tsx extension.\n\n/Volumes/Disk/Web/wce-system/src/i18n.js:51:20\n\nhttps://i.sstatic.net/Hkci3.png\n\nThere's nothing wrong in i18n.js file as it was working fine with Vite 2.x but im putting codes in here just in case you need:\n\n```\nimport { nextTick } from \"vue\"\nimport { createI18n } from \"vue-i18n\"\nimport axios from \"axios\"\nimport tr from \"@/locales/tr.json\"\nimport en from \"@/locales/en.json\"\n\nexport const SUPPORT_LOCALES = [\"tr\", \"en\"]\n\nexport function setupI18n(options = { locale: \"tr\" }) {\nconst i18n = createI18n(options)\nsetI18nLanguage(i18n, options.locale)\n return i18n\n}\n\nexport function setI18nLanguage(i18n, locale, url) {\n if (i18n.mode === \"legacy\") {\n i18n.global.locale = locale\n} else {\n i18n.global.locale.value = locale\n} \naxios.defaults.headers.common[\"Accept-Language\"] = locale\ndocument.querySelector(\"html\").setAttribute(\"lang\", locale)\n}\n\nexport async function loadLocaleMessages(i18n, locale) {\n const messages = await import(\n/* webpackChunkName: \"locale-[request]\" */ `./locales/${locale}.json`\n)\n\ni18n.global.setLocaleMessage(locale, messages.default)\n return nextTick()\n}\n\nconst i18n = createI18n({\n legacy: false,\n locale: \"tr\",\n fallbackLocale: \"tr\",\n globalInjection: true,\n messages: {\n tr,\n en,\n },\n})\n\nexport default i18n\n```\n\n========================================\n\nTop Answer:\nI had same error and fixed like this:\n\nChange file format from `.js` to `.jsx`.\n\n========================================\n\nCode:\n```text\nimport { nextTick } from \"vue\"\nimport { createI18n } from \"vue-i18n\"\nimport axios from \"axios\"\nimport tr from \"@/locales/tr.json\"\nimport en from \"@/locales/en.json\"\n\nexport const SUPPORT_LOCALES = [\"tr\", \"en\"]\n\nexport function setupI18n(options = { locale: \"tr\" }) {\nconst i18n = createI18n(options)\nsetI18nLanguage(i18n, options.locale)\n  return i18n\n}\n\nexport function setI18nLanguage(i18n, locale, url) {\n  if (i18n.mode === \"legacy\") {\n  i18n.global.locale = locale\n} else {\n  i18n.global.locale.value = locale\n}       \naxios.defaults.headers.common[\"Accept-Language\"] = locale\ndocument.querySelector(\"html\").setAttribute(\"lang\", locale)\n}\n\nexport async function loadLocaleMessages(i18n, locale) {\n const messages = await import(\n/* webpackChunkName: \"locale-[request]\" */ `./locales/${locale}.json`\n)\n\ni18n.global.setLocaleMessage(locale, messages.default)\n return nextTick()\n}\n\nconst i18n = createI18n({\n  legacy: false,\n  locale: \"tr\",\n  fallbackLocale: \"tr\",\n  globalInjection: true,\n  messages: {\n    tr,\n    en,\n  },\n})\n\nexport default i18n\n```\n\n```text\nconst messages = await import(\n  /* webpackChunkName: \"locale-[request]\" */ `./locales/${locale}.json`\n)\n```\n\n```text\nconst messages = await import(`./locales/${locale}.json`)\n```\n\n```text\nexport default ({ .. some code });\n```\n\n```text\nexport default { .. some code };\n```\n\n```text\nsvelte.config.js\ntsconfig.json\ntsconfig.node.json\nvite.config.ts\n```\n\n```text\n// vite.config.js\nimport vue from '@vitejs/plugin-vue'\n\nexport default {\n  plugins: [\n     vue()\n  ],\n}\n```\n\n```text\n@vite-js/plugin-vue\n```\n\n```text\n.js\n```\n\n```text\n.jsx\n```\n\n```text\nimport { Foo } from 'baz';\n\nexport class MyClass{\n    static myFunc() {\n        return ...;\n    //} <- missing curly brace here\n}\n```\n\n```text\n.tsx\n```\n\n```text\n.jsx\n```\n\n========================================\n\nComments:\n- I got this error because I moved my index.html file into a subfolder. It HAS to be in the root, even though the documentation says you can build a subdirectory. I have found that to be false.\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- So the problem is that there is a problem somewhere? Not sure how this is helpful\n- Is this 2023? If your framework requires you to do this in order to spot bugs then there is an issue with the framework design.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- Had the same, my `vite.config.js` was in another location. I found out using `vite build --debug`, it says something like \"no configuration\".\n- This one solved it for me. I'm using a browser extension framework that itself uses vite config, but Storybook wouldn't be able to use it. So I added this example here.\n- Thank you for mentioning this. Sometimes it is overlooking a bracket, and here I was thinking it was a serious, in depth error. Cheers to you!","metadata":{"transformedAt":"2026-08-18T18:33:46.392Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":200,"estimatedTokens":1287}}35{"id":"stack-70995121","source":"stackoverflow","questionId":70995121,"title":"How to avoid vite build deleting inside of \"dist\" directory?","tags":["javascript","typescript","build","vite"],"text":"Title: How to avoid vite build deleting inside of \"dist\" directory?\nTags: javascript, typescript, build, vite\nSource: Stack Overflow\n\nQuestion:\nI want to create multiple libraries by vite, so I try \"rollupOptions\" first. Like,\n\n```\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n build: {\n rollupOptions: {\n input: {\n \"qy-viewer\": 'src/qy-viewer.ts',\n \"qy-swiper\": 'src/qy-swiper.ts'\n }\n }\n }\n})\n```\n\nBut this create funny results including hash-like string, like `qy-swiper.f3fc032d.js`.\n\nThis is useless, so I gave up this approach.\n\nNext I try preparing multiple vite config files. Like,\n\nvite.qy-swiper.config.ts\n\n```\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n build: {\n lib: {\n entry: 'src/qy-swiper.ts',\n name: 'QySwiper',\n fileName: (format) => `qy-swiper.${format}.js`\n },\n rollupOptions: {\n }\n }\n})\n```\n\nvite.qy-viewer.config.ts\n\n```\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n build: {\n lib: {\n entry: 'src/qy-viewer.ts',\n name: 'QyViewer',\n fileName: (format) => `qy-viewer.${format}.js`\n },\n rollupOptions: {\n }\n }\n})\n```\n\npackage.json\n\n```\n{\n \"scripts\": {\n \"build:swiper\": \"tsc && vite build --config vite.qy-swiper.config.ts\",\n \"build:viewer\": \"tsc && vite build --config vite.qy-viewer.config.ts\",\n \"build:lib\": \"npm run build:swiper && npm run build:viewer\"\n },\n}\n```\n\nThis works very fine when I execute `npm run build:swiper` or `npm run build:viewer` independently, but once I execute `npm run build:lib`, only qy-viewer is created.\n\nAre there any way to avoid deleting files in dist directory by `vite build` ?\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  build: {\n    rollupOptions: {\n      input: {\n        \"qy-viewer\": 'src/qy-viewer.ts',\n        \"qy-swiper\": 'src/qy-swiper.ts'\n      }\n    }\n  }\n})\n```\n\n```text\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  build: {\n    lib: {\n      entry: 'src/qy-swiper.ts',\n      name: 'QySwiper',\n      fileName: (format) => `qy-swiper.${format}.js`\n    },\n    rollupOptions: {\n    }\n  }\n})\n```\n\n```text\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  build: {\n    lib: {\n      entry: 'src/qy-viewer.ts',\n      name: 'QyViewer',\n      fileName: (format) => `qy-viewer.${format}.js`\n    },\n    rollupOptions: {\n    }\n  }\n})\n```\n\n```text\n{\n  \"scripts\": {\n    \"build:swiper\": \"tsc && vite build --config vite.qy-swiper.config.ts\",\n    \"build:viewer\": \"tsc && vite build --config vite.qy-viewer.config.ts\",\n    \"build:lib\": \"npm run build:swiper && npm run build:viewer\"\n  },\n}\n```\n\n```text\nqy-swiper.f3fc032d.js\n```\n\n```text\nnpm run build:swiper\n```\n\n```text\nnpm run build:viewer\n```\n\n```text\nnpm run build:lib\n```\n\n```text\nvite build\n```\n\n```js\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  build: {\n    emptyOutDir: false,\n  },\n  ⋮\n})\n```\n\n```text\nbuild.emptyOutDir\n```\n\n```text\nfalse\n```\n\n========================================\n\nComments:\n- It is also available via command line as `--emptyOutDir`\n- It'd be cool if there was a way of running emptyOutDir at the start only, no matter the order that they're ran.\n- @OstapBrehin how to set `emptyOutDir` to false via CLI?\n- @AdamJagosz I think adding `--emptyOutDir=fase` to your Vite commands in the `scripts` section from `package.json` would work","metadata":{"transformedAt":"2026-08-18T18:33:46.392Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":186,"estimatedTokens":845}}36{"id":"stack-69260715","source":"stackoverflow","questionId":69260715,"title":"Skipping larger chunks while running \"Npm run build\"","tags":["vue.js","npm","vite"],"text":"Title: Skipping larger chunks while running \"Npm run build\"\nTags: vue.js, npm, vite\nSource: Stack Overflow\n\nQuestion:\nFacing this problem while trying to run \"`npm run build`\"\n\n```\n(!) Some chunks are larger than 500 KiB after minification. Consider:\n- Using dynamic import() to code-split the application\n- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/guide/en/#outputmanualchunks\n- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.\n```\n\n========================================\n\nTop Answer:\n**EDIT: This is a work around and only hides warnings**\n\nAdd command in vite.config.js\n\n```\nbuild: {\n chunkSizeWarningLimit: 1600,\n },\n```\n\nfull code\n\n```\n// https://vitejs.dev/config/\nexport default defineConfig({\n base: \"/Stakepool-Frontend/\",\n plugins: [vue()],\n resolve: {\n alias: {\n \"~\": path.resolve(__dirname, \"node_modules\"),\n \"@\": path.resolve(__dirname, \"src\"),\n },\n },\n build: {\n chunkSizeWarningLimit: 1600,\n },\n});\n```\n\n========================================\n\nCode:\n```text\n(!) Some chunks are larger than 500 KiB after minification. Consider:\n- Using dynamic import() to code-split the application\n- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/guide/en/#outputmanualchunks\n- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.\n```\n\n```text\nnpm run build\n```\n\n```text\nexport default defineConfig({\n....\nbuild: {\n        rollupOptions: {\n            output:{\n                manualChunks(id) {\n                    if (id.includes('node_modules')) {\n                        return id.toString().split('node_modules/')[1].split('/')[0].toString();\n                    }\n                }\n            }\n        }\n    }\n});\n```\n\n```text\nchunkSizeWarningLimit\n```\n\n```text\nnode_modules\n```\n\n```text\n@emotion/react\n```\n\n```text\nemotion\n```\n\n```text\nreact-dom\n```\n\n```text\nreact-dom\n```\n\n```text\n@mui/material\n```\n\n```text\nreact\n```\n\n```text\nbuild: {\n    chunkSizeWarningLimit: 1600,\n  },\n```\n\n```text\n// https://vitejs.dev/config/\nexport default defineConfig({\n  base: \"/Stakepool-Frontend/\",\n  plugins: [vue()],\n  resolve: {\n    alias: {\n      \"~\": path.resolve(__dirname, \"node_modules\"),\n      \"@\": path.resolve(__dirname, \"src\"),\n    },\n  },\n  build: {\n    chunkSizeWarningLimit: 1600,\n  },\n});\n```\n\n```text\nimport { defineConfig } from \"vite\"\n‌ \nexport default defineConfig({\n    build: {\n        chunkSizeWarningLimit: 100000000\n    },\n})\n```\n\n```js\nexport default {\n  ...\n  vite: {\n    build: {\n      rollupOptions: {\n        output: {\n          manualChunks(id: any) {\n            if (id.includes(\"node_modules\")) {\n              return id.toString().split(\"node_modules/\")[1].split(\"/\")[0].toString();\n            }\n          },\n        },\n      },\n    },\n  },\n}\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nnpx vite-bundle-visualizer\n```\n\n```text\nimport hljs from \"highlight.js/lib/core\";\n```\n\n```text\nconst iconMap = {\n  copy: () =>\n    import(\"./icon-exports/AiOutlineCopy\").then((module) => ({\n      default: module.AiOutlineCopy,\n    })),\n// Other icons omitted\n  awsLambda: () =>\n    import(\"./icon-exports/AwsLambda\").then((module) => ({\n      default: module.AwsLambda,\n    })),\n};\n\nexport type ColorVariant = \"white\" | \"dark\" | \"red\";\nexport const colorMap: Record<ColorVariant, string> = {\n  white: \"#fff\",\n  dark: \"#1e2329\",\n  red: \"#e33122\",\n};\n\nexport type IconType = keyof typeof iconMap;\n\nexport type IconProps = {\n  icon: IconType;\n  color?: ColorVariant;\n  stroke?: ColorVariant;\n  fill?: ColorVariant;\n  size?: number;\n  width?: string;\n  height?: string;\n  customColor?: string;\n  className?: string;\n};\n\nexport const Icon: React.FC<IconProps> = (props) => {\n  const { icon, color, stroke, customColor, size = 24, ...otherProps } = props;\n  const [loaded, setLoaded] = useState(false);\n  const { isIntersecting, setRef } = useIntersectionObserver({\n    root: null,\n    rootMargin: \"0px\",\n    threshold: 0.1,\n  });\n\n  useEffect(() => {\n    if (isIntersecting) {\n      setLoaded(true);\n    }\n  }, [isIntersecting]);\n\n  const Element = loaded ? lazy(iconMap[icon]) : null;\n  const width = `${size}px`;\n  const height = `${size}px`;\n\n  const colors = {\n    stroke: stroke ? colorMap[stroke] : undefined,\n    color: customColor ? customColor : color ? colorMap[color] : undefined,\n  };\n\n  return (\n    <div ref={setRef} style={{ width, height }}>\n      {loaded && Element ? (\n        <Suspense fallback={<div style={{ width, height }} />}>\n          <Element size={size} {...otherProps} {...colors} />\n        </Suspense>\n      ) : (\n        <div style={{ width, height }} />\n      )}\n    </div>\n  );\n};\n```\n\n```text\nimport { useEffect, useState } from \"react\";\n\nexport const useIntersectionObserver = (options: IntersectionObserverInit) => {\n  const [isIntersecting, setIsIntersecting] = useState(false);\n  const [ref, setRef] = useState<HTMLElement | null>(null);\n\n  useEffect(() => {\n    if (!ref) return;\n\n    const observer = new IntersectionObserver(([entry]) => {\n      if (entry.isIntersecting) {\n        setIsIntersecting(true);\n        observer.disconnect();\n      }\n    }, options);\n\n    observer.observe(ref);\n\n    return () => observer.disconnect();\n  }, [ref, options]);\n\n  return { isIntersecting, setRef };\n};\n```\n\n```text\nexport { AwsLambda } from \"../../../../assets/generated/icons\";\n```\n\n```text\nimport {}\n```\n\n```text\ndate-fns\n```\n\n```text\n./icon-exports/AwsLambda.tsx\n```\n\n```text\nbuild: {\n        chunkSizeWarningLimit: 600,\n        rollupOptions: {\n            output: {\n                manualChunks: (id) => {\n                    if (id.includes('node_modules')) {\n                        if (id.includes('@babylonjs/core/Animations')) {\n                            return '@babylonjs/core/Misc';\n                        }\n\n                        if (id.includes('@babylonjs/core/Behaviors')) {\n                            return '@babylonjs/core/Misc';\n                        }\n\n                        if (id.includes('@babylonjs/core/Cameras')) {\n                            return '@babylonjs/core/Base';\n                        }\n\n                        if (id.includes('@babylonjs/core/Engines')) {\n                            return '@babylonjs/core/types';\n                        }\n\n                        if (id.includes('@babylonjs/core/Gizmos')) {\n                            return '@babylonjs/core/Misc';\n                        }\n\n                        if (id.includes('@babylonjs/core/Layers')) {\n                            return '@babylonjs/core/Misc';\n                        }\n\n                        if (id.includes('@babylonjs/core/Lights')) {\n                            return '@babylonjs/core/Misc';\n                        }\n\n                        if (id.includes('@babylonjs/core/Materials')) {\n                            if (id.includes('@babylonjs/core/Materials/Node')) {\n                                return '@babylonjs/core/Materials/Node';\n                            }\n                            return '@babylonjs/core/Materials';\n                        }\n\n                        if (id.includes('@babylonjs/core/Maths')) {\n                            return '@babylonjs/core/Science';\n                        }\n\n                        if (id.includes('@babylonjs/core/Meshes')) {\n                            return '@babylonjs/core/Meshes';\n                        }\n\n                        if (id.includes('@babylonjs/core/Misc')) {\n                            return '@babylonjs/core/Misc';\n                        }\n\n                        if (id.includes('@babylonjs/core/Particles')) {\n                            return '@babylonjs/core/Base';\n                        }\n\n                        if (id.includes('@babylonjs/core/Physics')) {\n                            return '@babylonjs/core/Science';\n                        }\n\n                        if (id.includes('@babylonjs/core/PostProcesses')) {\n                            return '@babylonjs/core/Processing';\n                        }\n\n                        if (id.includes('@babylonjs/core/Rendering')) {\n                            return '@babylonjs/core/Processing';\n                        }\n    \n                        if (id.includes('@babylonjs/core/scene')) {\n                            return '@babylonjs/core/types';\n                        }\n\n                        if (id.includes('@babylonjs/core/Shaders')) {\n                            if (id.includes('/ShadersInclude')) {\n                                return '@babylonjs/core/ShadersInclude';\n                            }\n\n                            return '@babylonjs/core/Shaders';\n                        }\n    \n                        if (id.includes('@babylonjs/core/XR')) {\n                            return '@babylonjs/core/Base';\n                        }\n    \n                        if (id.includes('@babylonjs/core')) {\n                            return '@babylonjs/core';\n                        }\n\n                        if (id.includes('@babylonjs/gui-editor')) {\n                            return '@babylonjs/gui-editor';\n                        }\n\n                        if (id.includes('@babylonjs/gui')) {\n                            return '@babylonjs/gui';\n                        }\n\n                        if (id.includes('@babylonjs/inspector')) {\n                            return '@babylonjs/inspector';\n                        }\n\n                        return id.toString().split('node_modules/')[1].split('/')[0].toString();\n                    }\n\n                }\n            }\n        }\n    }\n```\n\n```text\nmanualChunks\n```\n\n```text\nmanualChunks\n```\n\n```text\nid\n```\n\n```text\nvite-bundle-visualizer\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\nnode_modules/@babylonjs/core/Blah\n```\n\n```text\n@babylonjs\n```\n\n```text\n@babylonjs/core\n```\n\n```text\ndist/assets\n```\n\n```text\n-ABC-1234.js\n```\n\n```text\n@babylonjs/inspector\n```\n\n```text\nmanualChunks\n```\n\n```text\nid\n```\n\n========================================\n\nComments:\n- So did you try any of those three things? Without a minimal reproducible example there's not much else to say.\n- so this only increases the size limit and does not actually address the size issue?\n- I don't think this should be the accepted answer as it only increases the size limit warning.\n- This is a work around you are not actually solve the issue\n- @JJP which answer works best for you. MohKoma's answer?\n- Can you please elaborate on what this does?\n- node_modules is mostly the main reason for the large chunk problem, With this you're telling Vite to treat the used modules separately. To understand better what it does, try to compare the logs from the build command with and without this change.\n- In the github post it says it screws with the CSS imports and imports them backwards with this. No solution.\n- The warning is there for a reason. Setting it to some ridiculous high value defeats the purpose of it.\n- If you don't care about the warning, you can use this solution, but not recommended. Better to just have the warning if you're not going to address it.","metadata":{"transformedAt":"2026-08-18T18:33:46.392Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":39,"totalLines":467,"estimatedTokens":2776}}37{"id":"stack-75798479","source":"stackoverflow","questionId":75798479,"title":"How can I solve the issue of 'failed to resolve import in '@/...'\" vitest?","tags":["javascript","typescript","vue.js","vite","vitest"],"text":"Title: How can I solve the issue of 'failed to resolve import in '@/...'\" vitest?\nTags: javascript, typescript, vue.js, vite, vitest\nSource: Stack Overflow\n\nQuestion:\nThis is the error I got. There is a problem with the file path I defined in the \"vite.config.ts\" file. Can you help me?\n\nError Log\n\nError Message:\n\n```\nFAIL tests/utils/ConvertFromDomainToCountryCode.test.ts [ tests/utils/ConvertFromDomainToCountryCode.test.ts ]\nError: Failed to resolve import \"@/constant\" from \"src/assets/ts/_utils/ConvertFromDomainToCountryCode.ts\". Does the file exist?\n```\n\n`ConvertFromDomainToCountryCode.test.ts` file\n\n```\nimport { describe, expect } from \"vitest\";\nimport { SetFlags } from \"../../src/assets/ts/_utils/ConvertFromDomainToCountryCode.ts\";\n\ndescribe(\"Convert From Domain To CountryCode\", () => {\n test(\"function defined\", () => {\n expect(SetFlags).toBeDefined();\n });\n});\n```\n\nHere it works fine when I make the file path \"../../../constant/index\".\n\n`ConvertFromDomainToCountryCode.ts` file\n\n```\nimport { COUNTRY_INFO } from \"@/constant\";\n```\n\nHere i added \"alias\"\n\n`vite.config.ts` file\n\n```\nimport { fileURLToPath, URL } from \"node:url\";\n\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\";\nimport { resolve, dirname } from \"node:path\";\nimport vueJsx from \"@vitejs/plugin-vue-jsx\";\n\nexport default defineConfig({\n plugins: [\n vue(),\n vueJsx()\n ],\n resolve: {\n alias: {\n \"@\": fileURLToPath(new URL(\"./src\", import.meta.url))\n }\n },\n base: \"/\"\n});\n```\n\n### System\n\n```\nOS: macOS 13.2.1\nCPU: (8) arm64 Apple M1 Pro\nMemory: 91.50 MB / 16.00 GB\nShell: 5.8.1 - /bin/zsh\nBinaries:\nNode: 16.18.1 - ~/.nvm/versions/node/v16.18.1/bin/node\nYarn: 1.22.19 - ~/.nvm/versions/node/v16.18.1/bin/yarn\nnpm: 8.19.2 - ~/.nvm/versions/node/v16.18.1/bin/npm\nBrowsers:\nChrome: 111.0.5563.64\nSafari: 16.3\nnpmPackages:\n@vitejs/plugin-vue: ^3.1.2 => 3.2.0\n@vitejs/plugin-vue-jsx: ^3.0.0 => 3.0.0\n@vitest/coverage-istanbul: ^0.29.3 => 0.29.3\nvite: ^3.1.8 => 3.2.5\nvitest: ^0.29.3 => 0.29.3\n```\n\nJust waiting for the path of the file to be found\n\n========================================\n\nTop Answer:\nHad the same problem and the answer helps to solve it but I wanna add you can import resolve from path\n\n```\nimport { resolve } from 'path'\n```\n\nand if you haven't declared `@` in your `tsconfig` but you have dynamic path for some specific folders you can just specify them.\n\n```\nresolve: {\n alias: [{ \n find: \"@server\", \n replacement: resolve(__dirname, './src/server/') \n }]\n}\n```\n\n========================================\n\nCode:\n```js\nFAIL  tests/utils/ConvertFromDomainToCountryCode.test.ts [ tests/utils/ConvertFromDomainToCountryCode.test.ts ]\nError: Failed to resolve import \"@/constant\" from \"src/assets/ts/_utils/ConvertFromDomainToCountryCode.ts\". Does the file exist?\n```\n\n```js\nimport { describe, expect } from \"vitest\";\nimport { SetFlags } from \"../../src/assets/ts/_utils/ConvertFromDomainToCountryCode.ts\";\n\ndescribe(\"Convert From Domain To CountryCode\", () => {\n  test(\"function defined\", () => {\n    expect(SetFlags).toBeDefined();\n  });\n});\n```\n\n```js\nimport { COUNTRY_INFO } from \"@/constant\";\n```\n\n```js\nimport { fileURLToPath, URL } from \"node:url\";\n\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\";\nimport { resolve, dirname } from \"node:path\";\nimport vueJsx from \"@vitejs/plugin-vue-jsx\";\n\nexport default defineConfig({\n  plugins: [\n    vue(),\n    vueJsx()\n  ],\n  resolve: {\n    alias: {\n      \"@\": fileURLToPath(new URL(\"./src\", import.meta.url))\n    }\n  },\n  base: \"/\"\n});\n```\n\n```text\nOS: macOS 13.2.1\nCPU: (8) arm64 Apple M1 Pro\nMemory: 91.50 MB / 16.00 GB\nShell: 5.8.1 - /bin/zsh\nBinaries:\nNode: 16.18.1 - ~/.nvm/versions/node/v16.18.1/bin/node\nYarn: 1.22.19 - ~/.nvm/versions/node/v16.18.1/bin/yarn\nnpm: 8.19.2 - ~/.nvm/versions/node/v16.18.1/bin/npm\nBrowsers:\nChrome: 111.0.5563.64\nSafari: 16.3\nnpmPackages:\n@vitejs/plugin-vue: ^3.1.2 => 3.2.0\n@vitejs/plugin-vue-jsx: ^3.0.0 => 3.0.0\n@vitest/coverage-istanbul: ^0.29.3 => 0.29.3\nvite: ^3.1.8 => 3.2.5\nvitest: ^0.29.3 => 0.29.3\n```\n\n```text\nConvertFromDomainToCountryCode.test.ts\n```\n\n```text\nConvertFromDomainToCountryCode.ts\n```\n\n```text\nvite.config.ts\n```\n\n```js\nresolve: {\n  alias: [{ find: \"@\", replacement: resolve(__dirname, \"./src\") }]\n}\n```\n\n```text\nvitest.config.ts\n```\n\n```text\nimport { resolve } from 'path'\n```\n\n```text\nresolve: {\n  alias: [{ \n    find: \"@server\", \n    replacement: resolve(__dirname, './src/server/') \n  }]\n}\n```\n\n```text\n@\n```\n\n```text\ntsconfig\n```\n\n```js\nimport CheckCircleIcon from '@mui/icons-material/CheckCircle';\n```\n\n```text\n[plugin:vite:import-analysis] Failed to resolve import \"@mui/icons-material/CheckCircle\" from \"src/auth/components/Pricing/PricingTable.tsx\". Does the file exist?\n```\n\n```js\nimport CheckCircleIcon from \"@material-ui/icons/CheckCircle\";\n```\n\n```text\nimport { defineConfig } from 'vitest/config';\nimport { defineConfig as viteDefineConfig } from 'vite';\nimport tsconfigPaths from 'vite-tsconfig-paths';\n\nexport default defineConfig(\n  viteDefineConfig({\n    // ... other Vite configurations\n    plugins: [tsconfigPaths()],\n  }),\n);\n```\n\n```text\nvite-tsconfig-paths\n```\n\n```text\ntsconfig.json\n```\n\n```text\nvitest.config.ts\n```\n\n```text\nnpm install vite-tsconfig-paths --save-dev\n```\n\n```text\nvitest.config.ts\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport path from \"node:path\";\n\nexport default defineConfig({\n  resolve: {\n    alias: {\n      '@': path.resolve(__dirname, 'src'),\n    },\n  },\n});\n```\n\n========================================\n\nComments:\n- Here is the reference link.\n- can not find `resolve` or `__dirname`\n- @AmirRezvani `import {resolve} from 'node:path'`\n- yea, i figure it out later. @jonathan-dumaine\n- thank you, the configuration in this answer worked for me as well in a react.js project when trying to implement some shadcn/ui components. note that you do have to `import { resolve } from 'path'` as a previous commenter Jonathan mentions. this is what was automatically generated with my project: `'@': fileURLToPath(new URL(__dirname, '.&#47;src', import.meta.url))` and this is something else I tried: `'@': path.resolve(__dirname, '.&#47;src', import.meta.url)`","metadata":{"transformedAt":"2026-08-18T18:33:46.392Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":281,"estimatedTokens":1543}}38{"id":"stack-68076527","source":"stackoverflow","questionId":68076527,"title":"How to set vite.config.js base public path?","tags":["vue.js","vite"],"text":"Title: How to set vite.config.js base public path?\nTags: vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to set a **base url** for both my dev and prod environments, but `vitejs` configs are not resolved.\n\nAccording to vitejs , you can set the base public path when served in development or production, in your config options.\n\nWhen running vite from the command line, Vite will automatically try to resolve a config file named vite.config.js inside project root.\n\nThe issue is that my application requests don't go through `'http://localhost:8080/'`, but are still appended to the default serving port `http://localhost:3000/`.\n\nMy current configs are bellow:\n\n```\n// vite.config.js\nexport default {\n base: 'http://localhost:8080/'\n}\n```\n\n```\n// packages.json\n{\n \"name\": \"vue3ui\",\n \"version\": \"0.0.0\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\"\n },\n \"dependencies\": {\n ...,\n \"vue\": \"^3.0.11\"\n },\n \"devDependencies\": {\n \"@vue/compiler-sfc\": \"^3.0.11\",\n \"vite\": \"^1.0.0-rc.13\"\n }\n}\n```\n\n========================================\n\nTop Answer:\nI think I understand what TC wants to solve.\nHe has 1 **build** for **dev** and **prod** envs.\n\nBut it depends on envs, he has a different base path.\n\n**Answer:**\nhttps://vitejs.dev/guide/build.html#advanced-base-options\nAt the moment it is an experimental feature\n\n```\nexperimental: {\n renderBuiltUrl(filename: string, { hostType }: { hostType: 'js' | 'css' | 'html' }) {\n if (['js', 'css'].includes(hostType)) {\n return { runtime: `window.__getFile(${JSON.stringify(filename)})` }\n } else {\n return { relative: true }\n }\n }\n}\n```\n\nand create global function\n\n```\nwindow.__getFile = function(file){\n if (window.location.host.includes('dev')) {\n return `http://cdn.dev/${file}`\n }\n return `http://cdn.prod/${file}`\n}\n```\n\nP.s. Sorry. I can't find any example with port\n\n========================================\n\nCode:\n```text\n// vite.config.js\nexport default {\n  base: 'http://localhost:8080/'\n}\n```\n\n```text\n// packages.json\n{\n  \"name\": \"vue3ui\",\n  \"version\": \"0.0.0\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\"\n  },\n  \"dependencies\": {\n    ...,\n    \"vue\": \"^3.0.11\"\n  },\n  \"devDependencies\": {\n    \"@vue/compiler-sfc\": \"^3.0.11\",\n    \"vite\": \"^1.0.0-rc.13\"\n  }\n}\n```\n\n```text\nvitejs\n```\n\n```text\n'http://localhost:8080/'\n```\n\n```text\nhttp://localhost:3000/\n```\n\n```text\nserver: {\n  port: '8080'\n}\n```\n\n```text\nserver: {\n    proxy: {\n      '/': {\n        target: 'http://localhost:8080/'\n      },\n\n      '/admin': {\n        target: 'http://localhost:8081/'\n      }\n    }\n  }\n```\n\n```text\n// .env\n \n// Running locally\nAPP_ENV=local\n// you change port of local/dev here to :8000\n// do not forget to adjust `server.port`\nASSET_URL=http://localhost:3000\n \n// Running production build\nAPP_ENV=production\nASSET_URL=https://your-prod-asset-domain.com\n```\n\n```text\nconst ASSET_URL = process.env.ASSET_URL || '';\n\nexport default { \n  base: `${ASSET_URL}/dist/`,\n\n  [...]\n}\n```\n\n```text\nvite.config.js\n```\n\n```text\n3000\n```\n\n```text\n8080\n```\n\n```text\nserver.port\n```\n\n```text\nlocalhost:3000\n```\n\n```text\nlocalhost:8080\n```\n\n```text\nserver.proxy\n```\n\n```text\n'/'\n```\n\n```text\nlocalhost:8080\n```\n\n```text\n'/admin'\n```\n\n```text\n/admin\n```\n\n```text\nhttp://localhost:8081\n```\n\n```text\n.env\n```\n\n```text\nvite.config.js\n```\n\n```js\nexperimental: {\n  renderBuiltUrl(filename: string, { hostType }: { hostType: 'js' | 'css' | 'html' }) {\n    if (['js', 'css'].includes(hostType)) {\n      return { runtime: `window.__getFile(${JSON.stringify(filename)})` }\n    } else {\n      return { relative: true }\n    }\n  }\n}\n```\n\n```js\nwindow.__getFile = function(file){\n  if (window.location.host.includes('dev')) {\n    return `http://cdn.dev/${file}`\n  }\n  return `http://cdn.prod/${file}`\n}\n```\n\n```text\nexport default defineConfig({\n  server: {\n    open: 'https://mycustomlocalurl.io/basepath'\n  }\n})\n```\n\n========================================\n\nComments:\n- Are you really just trying to change the port? That's the only change I see in the `base` config.\n- I'm trying to make the vite port config work, but yes. When it works I'll add a conditional statement to set a port for dev and `&#47;` for prod.\n- I tried applying your example to change `localhost:3000` to `api.domain.com` but it does not work. executing npm dev or yarn dev would still show on terminal `http:&#47;&#47;localhost:3000&#47;`\n- @Shulz without more details I cannot help you, but from what you are saying, of course, the `dev` command still launch the local server, in this answer I am only talking about **redirecting by the proxy some url segments configured in the config file.** This config `server: { proxy: { '&#47;api': { target: 'https:&#47;&#47;api.domain.com' }` will still show you localhost, but if you the request of `localhost:3000&#47;api`, it's sent to `api.domain.com`.\n- This only works for the css files. Since I'm using Remix with Vite that's SSR enabled, the JS bundle splits' paths are not changed at all. Am I supposed to make an addition change somewhere?\n- @Kevin in hostType you can select not only `css`, but `js` and `html` also","metadata":{"transformedAt":"2026-08-18T18:33:46.392Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":259,"estimatedTokens":1271}}39{"id":"stack-71286740","source":"stackoverflow","questionId":71286740,"title":"Cannot find module '@vitejs/plugin-react' or its corresponding type","tags":["typescript","vite"],"text":"Title: Cannot find module '@vitejs/plugin-react' or its corresponding type\nTags: typescript, vite\nSource: Stack Overflow\n\nQuestion:\nI have created the project using `npm create vite@latest` and I choose ts-react, when I ran the script the\n`npm run dev` worked, no warning however, I am getting an `Cannot find module '@vitejs/plugin-react' or its corresponding type` in vite.config.ts in vs code.\n\nScreenshot of error\n\n========================================\n\nTop Answer:\n**If you are using SWC!**\n\nUse **`\"@vitejs/plugin-react-swc\"`**, instead of `\"@vitejs/plugin-react\"`.\n\n========================================\n\nCode:\n```text\nnpm create vite@latest\n```\n\n```text\nnpm run dev\n```\n\n```text\nCannot find module '@vitejs/plugin-react' or its corresponding type\n```\n\n```text\nCommand\n```\n\n```text\nShift\n```\n\n```text\nP\n```\n\n```text\nTypeScript: Restart TS server\n```\n\n```text\nEnter\n```\n\n```text\n$ npm i -D @types/node\n```\n\n```text\nyarn add @vitejs/plugin-react\n```\n\n```text\nnpm i -S @vitejs/plugin-react\n```\n\n```text\n\"@vitejs/plugin-react-swc\"\n```\n\n```text\n\"@vitejs/plugin-react\"\n```\n\n```text\nvite.ts\n```\n\n```text\nvite.ts\n```\n\n```text\nvite.ts\n```\n\n```text\nnpm i -S @vitejs/plugin-react-swc\n```\n\n```text\n>=20.19\n```\n\n```text\n>=22.12\n```\n\n```text\n{\n  \"extends\": \"tsconfig.base.json\",\n  \"compilerOptions\": {\n    \"types\": [\"node\"],\n    \"esModuleInterop\": true,\n    \"moduleResolution\": \"node16\"\n  },\n  \"include\": [\n    \"vite.config.ts\"\n  ]\n}\n```\n\n```text\nmoduleResolution\n```\n\n```text\nimport\n```\n\n```text\n\"node\"\n```\n\n```text\n@vitejs/plugin-react\n```\n\n========================================\n\nComments:\n- Yes, I reopened the browser next morning, and the problems were fixed,\n- Yes, that seems to be the issue. Please update the top answer to include all cases that might solve the issue\n- Yep, this was my problem. I just assumed it would be added when I installed Vite. Don't forget to add `vite.config.js` as well!\n- How did I miss this obvious hint, Good job\n- That was my case, thanks a lot!!","metadata":{"transformedAt":"2026-08-18T18:33:46.392Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":134,"estimatedTokens":497}}40{"id":"stack-76191154","source":"stackoverflow","questionId":76191154,"title":"The requested module does not provide an export named 'default'","tags":["reactjs","typescript","vite"],"text":"Title: The requested module does not provide an export named 'default'\nTags: reactjs, typescript, vite\nSource: Stack Overflow\n\nQuestion:\nI am having some problems with the React project that I am currently working on. I use Vite as my build tool and for the last 2 or 3 days I see that sometimes I receive this error: `Uncaught SyntaxError: The requested module '/src/Components/App/HamburgerMenu.tsx?t=1683406454267' does not provide an export named 'default'` .\n\nAll my .tsx files have an exported default variable, and it works for every file most of the time, but sometimes I get this error, seemingly random.\nI cannot find a reason why it may happen but it can happen at any time when I save something in a file, it does not happen every time, just sometimes and it seems that for no reason, then it solves by itself after I save a few more times and/or I reload the page.\n\nEdit: I am doing the imports and exports like this:\n\n```\nimport Component from '../../Component'\n```\n\nand exporting\n\n```\nexport default function Component () {...\n}\n```\n\n========================================\n\nTop Answer:\nThis was driving me nuts as well. The issue turned out to be the way in which you write the import statement:\n\n```\nimport someFunction from '../../Component'\n```\n\nWhen written in this manner, **without brackets**, it causes the compiler to look for a *default export*. **Whatever** it finds as a default export will become `someFunction`.\n\nThis is ***not*** the same as:\n\n```\nimport { someFunction } from '../../Component'\n```\n\nWhich causes it to go look for a *named export* explicitly called `someFunction`.\n\nSo somewhere in your code, you are trying to use a default export (no brackets) and the source file does not have one defined as default.\n\n========================================\n\nCode:\n```js\nimport Component from '../../Component'\n```\n\n```js\nexport default function Component () {...\n}\n```\n\n```text\nUncaught SyntaxError: The requested module '/src/Components/App/HamburgerMenu.tsx?t=1683406454267' does not provide an export named 'default'\n```\n\n```text\nhttp://localhost:5173/node_modules/.vite/deps/... does not provide an export named ...\n```\n\n```text\n.vite\n```\n\n```text\nnode_modules\n```\n\n```text\n.vite\n```\n\n```text\nnode_modules\n```\n\n```text\nimport { myFunction } from './myModule';\n```\n\n```text\n// myModule.js\n\nexport const myFunction = () => { /* function code here */ };\n\nexport default myFunction;\n```\n\n```text\nimport myFunction from './myModule';\n```\n\n```text\nimport * as myModule from './myModule';\n```\n\n```text\nimport someFunction from '../../Component'\n```\n\n```text\nimport { someFunction } from '../../Component'\n```\n\n```text\nsomeFunction\n```\n\n```text\nsomeFunction\n```\n\n```text\nlet obj = new IMyInterface()\n```\n\n```text\nlet obj : IMyInterface = {}\n```\n\n```text\nnpm run start\n```\n\n```text\nimport { useTranslation } from 'react-i18next'\n```\n\n```text\nimport { useTranslation } from 'node_modules/react-i18next'\n```\n\n========================================\n\nComments:\n- Please provide enough code so others can better understand or reproduce the problem.\n- Well every file has a constant arrow function that is exported as default at the bottom of the file, as it has happened to many files I do not think any code would help with anything as it does not regard anything inside the component itself.\n- I have the same issue - what did you do?\n- @boggy I still have the issue with Vite, although I have not worked on a project with Vite for the last 2 or 3 months so I am not sure at the moment, but last time I remember I still have it. I saw that there was a Issue opened on this on github's vite but I don't know what happened with it.\n- See comment by 'nstuyvesant' regarding compilerOptions.allowSyntheticDefaultImports below, it may help you get rid of this error if you already have a lot of imports.\n- The exports and imports are not the problem they work as expected. I just get this error sometimes for apparently no real reason, as I said if I am working on a file and I make changes (like updating some values in the jsx or anything else) at some point I might get this error .\n- Does your tsconfig.json have compilerOptions.allowSyntheticDefaultImports set to true?\n- @nstuyvesant Yes, it does have it.\n- @nstuyvesant It was, I changed it to 'false' and error goes away. I needed it since already there were a lot of imports in this project.\n- In my case the exports in question were the components of that file and I was exporting each component out of its file as the default export.\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:46.392Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":150,"estimatedTokens":1191}}41{"id":"stack-68376035","source":"stackoverflow","questionId":68376035,"title":"How to include CSS from node_modules in Vite in production?","tags":["css","typescript","npm","vite"],"text":"Title: How to include CSS from node_modules in Vite in production?\nTags: css, typescript, npm, vite\nSource: Stack Overflow\n\nQuestion:\nI have a typescript web application that includes CSS files from its NPM dependencies in index.html like this:\n\n```\n\n```\n\nAfter I added vite to my project, this works in development mode (`vite`), because it serves the content from my development folder where the path to node_modules exists. However this breaks in production (`vite build`) or preview mode (`vite preview`) where it is served in another folder and the node_modules folder doesn't get included in the output.\n\nMy old workflow was to just `npm install` on the web server so it had all it's dependencies in the node_modules folder, but this does not work with an application bundled by Vite.\n\nI consulted the manual including https://vitejs.dev/guide/features.html#css but all the examples in the manual concern people using frameworks and libraries like PostCSS, React, Vue, tailwind, SASS and so on. However I don't use any of those technologies.\n\nHow can I get Vite to include CSS files from NPM dependencies in just a simple typescript application consisting of ES6 modules with no frameworks whatsoever?\n\nThe manual says something about importing but I don't understand, how and where exactly to import the CSS, in the index.html or in the modules?\n\n========================================\n\nCode:\n```text\n<link rel=\"stylesheet\" type=\"text/css\" href=\"./node_modules/notyf/notyf.min.css\" />\n```\n\n```text\nvite\n```\n\n```text\nvite build\n```\n\n```text\nvite preview\n```\n\n```text\nnpm install\n```\n\n```text\nmain.js\n```\n\n```text\nimport 'notyf/notyf.min.css'\n```\n\n========================================\n\nComments:\n- in `main.js` you try doing `import 'notyf&#47;notyf.min.css'`, let me know if that work.\n- @syed: Yes, this works! Can you make an answer out of your comment?\n- You need to be mindful of the file path you're importing your css file into. i.e: If you're on src/main.js, you need to link it relatively using \"../\" like (../node_modules/lib/index.css)\n- This inlines all the CSS inside javascript, which doesn't seem like the best idea for production","metadata":{"transformedAt":"2026-08-18T18:33:46.392Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":59,"estimatedTokens":539}}42{"id":"stack-70446474","source":"stackoverflow","questionId":70446474,"title":"How to set vite (preview) production port?","tags":["reactjs","vue.js","svelte","vite"],"text":"Title: How to set vite (preview) production port?\nTags: reactjs, vue.js, svelte, vite\nSource: Stack Overflow\n\nQuestion:\nI have been looking arround on how to set a production port for vite but I can't find way\nI have tried this vite js config\n\n```\nserver: {\n host: true,\n },\n preview:{\n port:5005\n }\n```\n\nbut it seems like it can't work\n\n========================================\n\nTop Answer:\nIn package.json, add this code\n\n```\n\"scripts\": {\n \"serve\": \"vite --port 8000\"\n},\n```\n\nIn terminal, run the command\n\n```\nnpm run serve\n```\n\n========================================\n\nCode:\n```js\nserver: {\n    host: true,\n  },\n  preview:{\n    port:5005\n  }\n```\n\n```js\nexport default defineConfig({\n  server: {\n    port: 3030\n  },\n  preview: {\n    port: 8080\n  }\n})\n```\n\n```js\n\"scripts\": {\n    \"serve\": \"vite preview --port 6000\"\n  },\n```\n\n```text\n--port\n```\n\n```text\npackage.json\n```\n\n```text\n\"scripts\": {\n    \"serve\": \"vite --port 8000\"\n},\n```\n\n```text\nnpm run serve\n```\n\n```text\n\"dev\": \"vite --port=8080\"\n```\n\n========================================\n\nComments:\n- You use `server.host` instead of `server.port`. I know this is old, but noone mentioned this before.. Maybe it helps somebody with the same trouble :)\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:46.392Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":92,"estimatedTokens":371}}43{"id":"stack-75971024","source":"stackoverflow","questionId":75971024,"title":"\"describe is not defined\" in Vitest","tags":["javascript","jestjs","jsx","vite","vitest"],"text":"Title: \"describe is not defined\" in Vitest\nTags: javascript, jestjs, jsx, vite, vitest\nSource: Stack Overflow\n\nQuestion:\nI'm starting out with Vite for a React application but unable to get jest tests working. I am trying to use Vitest with experimental ES module.\n\nI am getting:\n\n```\nFAIL src/App.test.tsx [ src/App.test.tsx ]\nReferenceError: describe is not defined\n```\n\nI have added Jest, Mocha Vite, and Vitest, but it hasn't helped.\n\nMy package.json has\n\n```\n\"devDependencies\": {\n \"@testing-library/react\": \"^14.0.0\",\n \"@types/jest\": \"^29.5.0\",\n \"@types/react\": \"^18.0.28\",\n \"@types/react-dom\": \"^18.0.11\",\n \"@vitejs/plugin-react-swc\": \"^3.0.0\",\n \"jest\": \"^29.5.0\",\n \"mocha\": \"^10.2.0\",\n \"typescript\": \"^4.9.3\",\n \"vite\": \"^4.2.0\",\n \"vitest\": \"^0.29.8\"\n }\n```\n\nMy Vite config is:\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\nexport default defineConfig({\n plugins: [react()],\n}\n```\n\nMy Vitest config is:\n\n```\nimport react from '@vitejs/plugin-react';\nimport { defineConfig } from 'vitest/config'\n\nexport default defineConfig({\n plugins: [react()],\n test: {\n include: ['**/*.test.tsx'],\n },\n})\n```\n\nThis is from running Vitest. If I run Jest directly with\n\n```\njest\n```\n\nor\n\n```\nnode --experimental-vm-modules node_modules/jest/bin/jest.js\n```\n\nI get:\n\n```\nSyntaxError: /home/durrantm/Dropnot/vite/thedeiscorecard-vite/src/App.test.tsx: \n Support for the experimental syntax 'jsx' isn't currently enabled\n```\n\n========================================\n\nTop Answer:\nTo summarise the answers and the documentation\n\n(Unlike some other test frameworks) vitest does not globally define its test functions.\n\nYou can either:\n\nExplicitly import the functions you need in each test file:\n\n```\nimport { describe, test, expect } from 'vitest';\n```\n\nor use `vitest.config.ts` to configure it globally\n\n```\n// vitest.config.ts\nimport { defineConfig } from 'vitest/config'\n\nexport default defineConfig({\n test: {\n globals: true\n }\n})\n```\n\n========================================\n\nCode:\n```text\nFAIL  src/App.test.tsx [ src/App.test.tsx ]\nReferenceError: describe is not defined\n```\n\n```text\n\"devDependencies\": {\n    \"@testing-library/react\": \"^14.0.0\",\n    \"@types/jest\": \"^29.5.0\",\n    \"@types/react\": \"^18.0.28\",\n    \"@types/react-dom\": \"^18.0.11\",\n    \"@vitejs/plugin-react-swc\": \"^3.0.0\",\n    \"jest\": \"^29.5.0\",\n    \"mocha\": \"^10.2.0\",\n    \"typescript\": \"^4.9.3\",\n    \"vite\": \"^4.2.0\",\n    \"vitest\": \"^0.29.8\"\n  }\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\nexport default defineConfig({\n  plugins: [react()],\n}\n```\n\n```text\nimport react from '@vitejs/plugin-react';\nimport { defineConfig } from 'vitest/config'\n\nexport default defineConfig({\n  plugins: [react()],\n  test: {\n    include: ['**/*.test.tsx'],\n  },\n})\n```\n\n```text\njest\n```\n\n```text\nnode --experimental-vm-modules node_modules/jest/bin/jest.js\n```\n\n```text\nSyntaxError: /home/durrantm/Dropnot/vite/thedeiscorecard-vite/src/App.test.tsx: \n Support for the experimental syntax 'jsx' isn't currently enabled\n```\n\n```text\nimport react from '@vitejs/plugin-react';\nimport { defineConfig } from 'vitest/config'\n\nexport default defineConfig({\n  plugins: [react()],\n  test: {\n    include: ['**/*.test.tsx'],\n    globals: true\n  },\n})\n```\n\n```json\n{\n  ...\n  \"compilerOptions\": {\n    ...\n    \"types\": [\"vitest/globals\"]\n  }\n}\n```\n\n```js\nimport { describe } from 'vitest';\n```\n\n```text\ndescribe\n```\n\n```js\nimport { describe, test, expect } from 'vitest';\n```\n\n```js\n// vitest.config.ts\nimport { defineConfig } from 'vitest/config'\n\nexport default defineConfig({\n  test: {\n    globals: true\n  }\n})\n```\n\n```text\nvitest.config.ts\n```\n\n```text\nimport { defineWorkspace } from \"vitest/config\";\n\nexport default defineWorkspace(['packages/**/*.spec.ts',{\n    test: {\n        globals: true\n    },\n}]);\n```\n\n```text\nglobals: true\n```\n\n```text\nvitest.workspace.ts\n```\n\n========================================\n\nComments:\n- Jest and vitest are different libraries to accomplish the same thing, you want one or the other, not both unless you know you specifically have a reason to need both (ie, a gradual migration from one to the other).\n- i am importing it though...\n- documented here: vitest.dev/config/#globals","metadata":{"transformedAt":"2026-08-18T18:33:46.392Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":236,"estimatedTokens":1061}}44{"id":"stack-68147471","source":"stackoverflow","questionId":68147471,"title":"How to set sassOptions in Vite","tags":["sass","vite"],"text":"Title: How to set sassOptions in Vite\nTags: sass, vite\nSource: Stack Overflow\n\nQuestion:\nWith webpack, we can set sassOptions like below:\n\n```\n{\n loader: require.resolve('sass-loader'),\n options: {\n sassOptions: { quietDeps: true },\n },\n}\n```\n\nFollowing the vite document, I'm trying to config as below:\n\n```\ncss: {\n preprocessorOptions: {\n scss: {\n sassOptions: { quietDeps: true },\n },\n },\n },\n```\n\nBut it seems not work for me. What I need is to hide third-party sass deps's warning message in terminal.\n\n========================================\n\nTop Answer:\nA fresh solution for those who are looking for a way to fix the warning in Vite:\n\nDeprecation Warning: The legacy JS API is deprecated and will be\nremoved in Dart Sass 2.0.0.\n\nThe `quietDeps: true` rule mentioned above does not work for this warning.\n\nThe most preferable way is to make Vite to use modern API for SASS:\n\n```\nvite: {\n css: {\n preprocessorOptions: {\n scss: {\n api: 'modern-compiler', // or 'modern'\n },\n },\n },\n },\n```\n\nVite docs: css.preprocessorOptions\n\nBut if you want to just silence deprecation warnings, use silenceDeprecations option:\n\n```\nvite: {\n css: {\n preprocessorOptions: {\n scss: {\n silenceDeprecations: ['legacy-js-api'],\n },\n },\n },\n },\n```\n\nSASS docs for silenceDeprecations\nSASS Deprecations list\n\nBoth solutions work on Vite 5.4.6, and Sass 1.79.1\n\n========================================\n\nCode:\n```text\n{\n  loader: require.resolve('sass-loader'),\n  options: {\n    sassOptions: { quietDeps: true },\n  },\n}\n```\n\n```text\ncss: {\n    preprocessorOptions: {\n      scss: {\n        sassOptions: { quietDeps: true },\n      },\n    },\n  },\n```\n\n```js\nexport default defineConfig({\n  css: {\n    preprocessorOptions: {\n      scss: {\n        quietDeps: true\n      }\n    }\n  }\n})\n```\n\n```text\n@forward 'spinkit/scss/spinners/7-three-bounce.scss';\n```\n\n```text\n@forward '../../node_modules/spinkit/scss/spinners/7-three-bounce.scss';\n```\n\n```text\nvite.config.js\n```\n\n```text\nnode_modules\n```\n\n```text\nloadPaths\n```\n\n```text\nnode_modules\n```\n\n```js\ncss: {\n        preprocessorOptions: {\n            scss: {\n                quietDeps: true,\n            },\n        },\n    }\n```\n\n```text\ncss.preprocessorOptions.scss.quiet\n```\n\n```text\nsass\n```\n\n```text\n1.32.13\n```\n\n```js\nvite: {\n        css: {\n            preprocessorOptions: {\n                scss: {\n                    api: 'modern-compiler', // or 'modern'\n                },\n            },\n        },\n    },\n```\n\n```js\nvite: {\n        css: {\n            preprocessorOptions: {\n                scss: {\n                    silenceDeprecations: ['legacy-js-api'],\n                },\n            },\n        },\n    },\n```\n\n```text\nquietDeps: true\n```\n\n```text\nvite: {\n    css: {\n        preprocessorOptions: {\n            scss: {\n                api: 'modern-compiler', // or 'modern'\n            },\n        },\n    },\n}\n```\n\n```text\ncss: {\n  preprocessorOptions: {\n    sass: {\n      silenceDeprecations: ['import', 'slash-div', 'global-builtin'], // list of warnings to hide\n      quietDeps: true,\n    },\n    scss: {\n      silenceDeprecations: ['import', 'slash-div', 'global-builtin'],\n      quietDeps: true,\n    },\n  },\n},\n```\n\n```text\nsass\n```\n\n```text\nscss\n```\n\n========================================\n\nComments:\n- Did you find the solution? I got `ReferenceErrror: scss is not defined` here.\n- None till now. I've also asked on GitHub, but not response...\n- Anybody knows how to do that in Svelte 5?\n- Please provide additional details in your answer. As it's currently written, it's hard to understand your solution.\n- I don't think this is working for me with vite 3.1.8 and sass 1.55.0. Can anyone else confirm it working? I am trying to suppress warnings about `&#47;` in font-awesome 4... it's possible this arg just doesn't work to do that, although it's suggested elsewhere it ought to.\n- Works for me with Vite v4.5.3 and sass v1.77.8\n- For SvelteKit folks, replace `scss` with `sass`\n- Indeed. Their docs say \"Stylesheets that are imported relative to the entrypoint are not considered dependencies.\".. Well, I am using Bootstrap (SCSS version of it) and obviously hosting it myself, so clearly the path is going to be relative...\n- The `definition of a \"dependency\"` link is dead.\n- I use v1.33.00 and it is fine. `npm i -d sass@1.33.00`\n- Using `css: { preprocessorOptions: { scss: { api: 'modern-compiler', silenceDeprecations: ['import', 'global-builtin'] } } }` did the trick to me without using the weird `quietDeps` option at all.\n- Thank you, this was driving me crazy today!\n- Same here - thanks Alex! I opted for the first solution: use the modern api.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- Used this. Adding or removing `quietDeps: true` didn't make any difference, so you might as well leave that out.\n- This is the right answer","metadata":{"transformedAt":"2026-08-18T18:33:46.392Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":237,"estimatedTokens":1258}}45{"id":"stack-71295772","source":"stackoverflow","questionId":71295772,"title":"In vite, is there a way to update the root html name from index.html","tags":["vite"],"text":"Title: In vite, is there a way to update the root html name from index.html\nTags: vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to update an existing project to vite but i read in the docs Vite expects an index.html file to work from.\nIs there anyway to specify another file name from which vite should build?\nin my case main.html\n\n========================================\n\nTop Answer:\nIf you're trying to change not just the name of the root HTML page but also the *path* to it, changing `build` or `server` options won't help. For example, if you want to load `/src/main.html` instead of `/index.html`, you can access it at `http://localhost:3000/src/main.html`, but not at simply `localhost:3000`.\n\nTo serve files from a different path, you'll need to set `root` in the config file. Note that you'll also need to define other paths relative to this new root, like `dist`. Otherwise, the packaged files will be output to `/src/dist`.\n\nA more complete config file that loads the HTML file from `/src` looks like this:\n\n```\nimport path from \"node:path\";\nimport process from \"node:process\";\nimport { defineConfig } from \"vite\";\n\nexport default defineConfig({\n server: {\n open: \"main.html\",\n },\n root: \"src\",\n publicDir: \"../public\",\n build: {\n outDir: \"../dist\"\n },\n resolve: {\n alias: { \"/src\": path.resolve(process.cwd(), \"src\") }\n },\n});\n```\n\n========================================\n\nCode:\n```js\nimport { defineConfig } from 'vite'\nexport default defineConfig({\n  ⋮\n  build: {\n    rollupOptions: {\n      input: {\n        app: './index.html', // default\n      },\n    },\n  },\n})\n```\n\n```js\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  ⋮\n  build: {\n    rollupOptions: {\n      input: {\n        app: './main.html',\n      },\n    },\n  },\n  server: {\n    open: '/main.html',\n  },\n})\n```\n\n```text\nbuild.rollupOptions.input\n```\n\n```text\nmain.html\n```\n\n```text\n/main.html\n```\n\n```text\nserver.open\n```\n\n```text\nindex.html\n```\n\n```text\nbuild.rollupOptions.input\n```\n\n```text\n./main.html\n```\n\n```text\nbuild.lib.entry\n```\n\n```text\nindex.html\n```\n\n```text\nindex.html\n```\n\n```text\n.html\n```\n\n```text\nbuild.rollupOptions.input\n```\n\n```text\nbuild.lib.entry\n```\n\n```js\nimport path from \"node:path\";\nimport process from \"node:process\";\nimport { defineConfig } from \"vite\";\n\nexport default defineConfig({\n  server: {\n    open: \"main.html\",\n  },\n  root: \"src\",\n  publicDir: \"../public\",\n  build: {\n    outDir: \"../dist\"\n  },\n  resolve: {\n    alias: { \"/src\": path.resolve(process.cwd(), \"src\") }\n  },\n});\n```\n\n```text\nbuild\n```\n\n```text\nserver\n```\n\n```text\n<project root>/src/main.html\n```\n\n```text\n<project root>/index.html\n```\n\n```text\nhttp://localhost:3000/src/main.html\n```\n\n```text\nlocalhost:3000\n```\n\n```text\nroot\n```\n\n```text\ndist\n```\n\n```text\n/src/dist\n```\n\n```text\n/src\n```\n\n```js\nexport default defineConfig({\n  plugins: [\n    vue(),\n    {\n      name: \"deep-index\",\n      configureServer(server) {\n        server.middlewares.use(\n          (req, res, next) => {\n            if (req.url === '/') {\n              req.url = '/some/path/to/your/index.html';\n            }\n            next();\n          }\n        )\n      }\n    }\n  ]\n})\n```\n\n```text\nindex.html\n```\n\n```text\n/\n```\n\n```text\nvite.config\n```\n\n```text\nindex.html\nindex_type1.html\nindex_type2.html\nwhatever.html\netc\n```\n\n```js\nimport fs from 'fs/promises'\n\nexport default defineConfig({\n\n    plugins: [\n      // ...\n\n      {\n        name: 'my-plugin-for-index-html-build-replacement',\n        transformIndexHtml: {\n          enforce: 'pre', // Tells Vite to run this before other processes\n          async transform() {\n\n            // Do some logic; whatever you want\n            if (env.MY_ENV_VARIABLE == 'myType2') {\n\n              // Grab new HTML content to place into index.html\n              return await fs.readFile('./index_type2.html', 'utf8')\n            }\n          }\n        }\n      }\n\n      // ...\n    ]\n\n})\n```\n\n```text\nindex.html\n```\n\n```text\nfs\n```\n\n```text\nindex.html\n```\n\n```text\nbuild\n```\n\n```js\nexport default defineConfig({\n  server: {\n    open: '/docs/index.html'\n  }\n})\n```\n\n```javascript\nexport default defineConfig(({command, mode, isSsrBuild, isPreview}) => {\n return {\n   plugins: [..., {\n        name: 'index-html-build-replacement', \n        apply: 'serve',  \n        async transformIndexHtml(html) {\n            switch (mode) {\n                case  'firstMode':\n                    return await fs.readFile('./index-first.html','utf8'); \n                case 'secondMode':\n                    return await fs.readFile('./index-second.html','utf8');\n            }\n\n            return html;\n        }\n     }],\n     ...\n    }\n  }\n```\n\n========================================\n\nComments:\n- Cannot import `path`. I get this error: `Cannot find module 'node:path' or its corresponding type declarations.ts(2307)`. I am using vite v5 + node v22. Any idea?\n- @MohammadJawadBarati you shoud run `npm install --save-dev @types&#47;node`\n- Thank you. Regarding next, do i need to call it at the end?\n- @elpddev good point, I think it should be called indeed. It worked in my case anyway, but I guess it only works when there's no other middleware\n- Not sure how this is an answer. This opens a browser after the server has started. vitejs.dev/config/server-options#server-open","metadata":{"transformedAt":"2026-08-18T18:33:46.392Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":38,"totalLines":310,"estimatedTokens":1318}}46{"id":"stack-70842377","source":"stackoverflow","questionId":70842377,"title":"How to run SASS with React on Vite?","tags":["reactjs","sass","vite"],"text":"Title: How to run SASS with React on Vite?\nTags: reactjs, sass, vite\nSource: Stack Overflow\n\nQuestion:\nI created a React project with Vite and want to use SASS as well. I have it installed already but I usually open a git bash and run `sass -w sass:css`.\n\nIs there a better way to do it? I couldn't understand a solution in the docs, nor an answer online.\n\n**This is my `package.json`:**\n\n```\n{\n \"name\": \"my_first_vite\",\n \"version\": \"0.0.0\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\"\n },\n \"dependencies\": {\n \"react\": \"^17.0.2\",\n \"react-dom\": \"^17.0.2\"\n },\n \"devDependencies\": {\n \"@vitejs/plugin-react\": \"^1.0.7\",\n \"sass\": \"^1.49.0\",\n \"vite\": \"^2.7.2\"\n }\n}\n```\n\n========================================\n\nTop Answer:\nI found the answer in the vite docs. I had to run:\n\n```\nnpm add -D sass\n```\n\n========================================\n\nCode:\n```json\n{\n  \"name\": \"my_first_vite\",\n  \"version\": \"0.0.0\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"preview\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"react\": \"^17.0.2\",\n    \"react-dom\": \"^17.0.2\"\n  },\n  \"devDependencies\": {\n    \"@vitejs/plugin-react\": \"^1.0.7\",\n    \"sass\": \"^1.49.0\",\n    \"vite\": \"^2.7.2\"\n  }\n}\n```\n\n```text\nsass -w sass:css\n```\n\n```text\npackage.json\n```\n\n```text\nvite\n```\n\n```text\nvite build\n```\n\n```text\nnpm add -D sass\n```\n\n```text\nyarn add -D sass-embedded\n```\n\n```text\n.scss\n```\n\n========================================\n\nComments:\n- so I just need to add the .scss file as normal? will try it out! tysm!\n- it does indeed works directly, just need to install sass first! TYSM!!\n- This seems to be outdated. As @Ashwin Chandran mentioned, you apparently need to install sass-embedded now.","metadata":{"transformedAt":"2026-08-18T18:33:46.393Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":99,"estimatedTokens":430}}47{"id":"stack-76689458","source":"stackoverflow","questionId":76689458,"title":"How to use env in index.html within a react vite application","tags":["javascript","reactjs","environment-variables","vite"],"text":"Title: How to use env in index.html within a react vite application\nTags: javascript, reactjs, environment-variables, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to access an env variable from my index.html file.\n\nThe code below seems to work in CRA but doesnt work with my vite, react project setup\n\n`const APP_ID = '%REACT_APP_ID%'`\n\n```\n\n //Set your APP_ID\n const APP_ID = '%REACT_APP_ID%'\n\n ....\n\n \n```\n\nmy vite config file\n\n```\nimport { defineConfig, splitVendorChunkPlugin } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport EnvironmentPlugin from 'vite-plugin-environment'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n splitVendorChunkPlugin(),\n react(),\n EnvironmentPlugin('all', { prefix: 'REACT_APP_' }),\n ],\n})\n```\n\n========================================\n\nTop Answer:\nYou should to use only \"%YOUR_VAR%\" like this:\n\n```\n\n const flag = \"%VITE_TRACKING_ID%\" \n if (flag) {\n ...\n\n```\n\nhave in mind you would need to update your Vite 4.2.0 as commented @Unmitigated\n\nthis is the thread to fix https://github.com/vitejs/vite/issues/3105#issuecomment-1441947641\n\n========================================\n\nCode:\n```text\n<script>\n      //Set your APP_ID\n      const APP_ID = '%REACT_APP_ID%'\n\n     ....\n\n    </script>\n```\n\n```text\nimport { defineConfig, splitVendorChunkPlugin } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport EnvironmentPlugin from 'vite-plugin-environment'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    splitVendorChunkPlugin(),\n    react(),\n    EnvironmentPlugin('all', { prefix: 'REACT_APP_' }),\n  ],\n})\n```\n\n```text\nconst APP_ID = '%REACT_APP_ID%'\n```\n\n```text\n<div>%VITE_SOME_KEY%</div>\n```\n\n```text\nVITE_\n```\n\n```text\n%\n```\n\n```text\n<script type=\"text/javascript\">\n    const flag = \"%VITE_TRACKING_ID%\" \n          if (flag) {\n            ...\n</script>\n```\n\n========================================\n\nComments:\n- `import.meta.REACT_APP_ID`?\n- I'm getting SyntaxError: Uncaught SyntaxError: Cannot use 'import.meta' outside a module\n- I'm trying to use it within the index.html file\n- Thanks, this fixes my error but I guess I can't use it with the `import EnvironmentPlugin from 'vite-plugin-environment'`\n- I was using that plugin to make jest tests work with envs, is there a solution for that. when I use `import.meta.env`. All my jest unit tests fail","metadata":{"transformedAt":"2026-08-18T18:33:46.393Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":115,"estimatedTokens":592}}48{"id":"stack-70996320","source":"stackoverflow","questionId":70996320,"title":"enable hot reload for vite react project instead of page reload","tags":["javascript","reactjs","vite"],"text":"Title: enable hot reload for vite react project instead of page reload\nTags: javascript, reactjs, vite\nSource: Stack Overflow\n\nQuestion:\nI am new to vite and I just started a new react application. My project had hmr (hot module replacement) enabled and it was ok. I just added some changes but when I start it now the hmr is disabled and when adding new change the browser is reloading (not updating fast) and in the terminal it logs:\n`12:37:54 PM [vite] page reload src/App.tsx`\nI created a new test application and it has hmr enabled and when I add any change it logs:\n`12:35:23 PM [vite] hmr update /src/App.tsx (x2)`\nCan any you tell me how to enable hmr instead of page reload?\n\nHere is my `vite.config.ts` for project that logs `page reload`\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()]\n})\n```\n\nand also `tsconfig.json` for project that logs `page reload`\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"ESNext\",\n \"useDefineForClassFields\": true,\n \"lib\": [\"DOM\", \"DOM.Iterable\", \"ESNext\"],\n \"allowJs\": false,\n \"skipLibCheck\": false,\n \"esModuleInterop\": false,\n \"allowSyntheticDefaultImports\": true,\n \"strict\": false,\n \"forceConsistentCasingInFileNames\": true,\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Node\",\n \"resolveJsonModule\": true,\n \"isolatedModules\": true,\n \"noEmit\": true,\n \"jsx\": \"react-jsx\"\n },\n \"include\": [\"./src\"]\n}\n```\n\n========================================\n\nTop Answer:\nTo enable the hot reload, you need to put this configuration in your vite.config.ts\n\n```\nexport default defineConfig({\n plugins: [react()],\n server: {\n watch: {\n usePolling: true\n }\n }\n})\n```\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()]\n})\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"DOM\", \"DOM.Iterable\", \"ESNext\"],\n    \"allowJs\": false,\n    \"skipLibCheck\": false,\n    \"esModuleInterop\": false,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": false,\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\"\n  },\n  \"include\": [\"./src\"]\n}\n```\n\n```text\n12:37:54 PM [vite] page reload src/App.tsx\n```\n\n```text\n12:35:23 PM [vite] hmr update /src/App.tsx (x2)\n```\n\n```text\nvite.config.ts\n```\n\n```text\npage reload\n```\n\n```text\ntsconfig.json\n```\n\n```text\npage reload\n```\n\n```text\nexport const foo = 12\n```\n\n```text\nexport default function FooBar(){}\n```\n\n```bash\n├── src\n│   ├── Components\n│   ├── Pages\n│   │   ├── Home\n│   │   │   ├── Home.styled.jsx\n│   │   │   ├── Index.jsx\n│   │   ├── About\n│   │   │   ├── About.styled.jsx\n│   │   │   ├── Index.jsx\n```\n\n```bash\n├── src\n│   ├── Components\n│   ├── pages\n│   │   ├── Home.jsx\n│   │   ├── About.jsx\n```\n\n```text\n(./pages/Home/)\n```\n\n```text\n(./pages/Home.jsx)\n```\n\n```js\nimport.meta.hot\n```\n\n```text\nimport Login from \"../components/Login.vue\";\n```\n\n```text\nimport Login from \"../components/LogIn.vue\"\n```\n\n```text\nLogIn.vue\n```\n\n```js\nexport default defineConfig({\n  plugins: [\n    react({\n      include: \"**/*.tsx\",\n    }),\n  ],\n});\n```\n\n```text\nvite.config.js\n```\n\n```text\ncomponent.tsx\n```\n\n```text\nComponent.tsx\n```\n\n```text\nnpm install\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react({\n    // Add this line\n    include: \"**/*.jsx\",\n  })]\n})\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react({\n    // Add this line\n    include: \"**/*.tsx\",\n  })]\n})\n```\n\n```text\n.jsx\n```\n\n```text\nvite.config.js\n```\n\n```text\n.tsx\n```\n\n```text\nvite.config.js\n```\n\n```text\nimport NewReleases from '../components/homepageComps/NewReleases'\n```\n\n```text\nimport NewReleases from '../components/homepageComps/OtherNameHere'\n```\n\n```text\nconst funcName = () => {...}\n```\n\n```text\nfunction App() {...}\n```\n\n```text\nfunction App() {...}\n```\n\n```text\nconst App = () => {...}\n```\n\n```text\nexport default defineConfig({\n  plugins: [react()],\n  server: {\n    watch: {\n      usePolling: true\n    }\n  }\n})\n```\n\n```text\nplugins: [react({\n    include: \"**/*.tsx\",\n  })],\n  server: {\n    watch: {\n      usePolling: true\n    }\n  }\n```\n\n```text\nexport\n```\n\n```text\ndefault export\n```\n\n========================================\n\nComments:\n- Mahdi-Jafaree, I don't know how to express my thanks to you, I was struggling to get the Vite HMR working for the past few days, I am trying to migrate CRA to Vite, and I do have the export statements in my index.tsx and moving them to a separate file worked like a charm, Thank you so much for this answer.\n- for what it's worth your old folder structure was incorrect, it might be that you didn't know because you're on a case insensitive filesystem. the index files should be `index.jsx` not `Index.js`... (additionally it's bad practice to use `index.jsx` implying you've defined react components in your index file, just name them `index.js` and only put exports in there.\n- Can't believe I missed that. Thanks @airtonix\n- where did you add it to?\n- I updated the answer to be more clear\n- `where did you add it to` Still not clear? @jaksco\n- add the line to any of the `.js` or `.ts` files which vite is aware of. for example if you have an `index.html` file you can create a regular `.js` file and reference the file in a normal `script` tag\n- I feel so stupid rn this of the solutions is what worked\n- For future google arrivals: tsconfig.json has a field `forceConsistentCasingInFileNames` you want to set to `true`\n- This worked for me perfectly. However, I use JS so I used `include: \"**&#47;*.jsx\"`\n- Doesn't work for me...\n- This worked for @vitejs react, if you are using something different, probably there is another problem. You can try in your vite.config.js to enable HMR, with adding the lines - server: { hmr: true }. This enables HMR. As well, try to clear the npm or yarn cache, sometimes that is the issue as well.\n- I found the solution just a few minutes after writing this comment. I somehow named the `pages` folder `Pages` and this was the issue in my case. Strange enough instead of showing an error vite continues to run the server with hotreload not working\n- Glad you managed to solve it, have a nice day :)\n- do you have a source for this? was it announced somewhere or in the docs?\n- can't think of any source at this point... but this worked for me...\n- Did not work for me, unfortunately.\n- This is needed for WSL vitejs.dev/config/server-options#server-watch\n- This was required to enable any automatic reloading on Windows in my case.\n- Same here using VS Code and devcontainer setup via docker. Tnanks.\n- This also worked on a Mac when hot reloading mysteriously stopped working.\n- running under bun, this helped me. (restart the server after you change the file)\n- This was the last piece i needed, I had not enabled the \"watch...\". now works great!","metadata":{"transformedAt":"2026-08-18T18:33:46.395Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":39,"totalLines":324,"estimatedTokens":1821}}49{"id":"stack-79383705","source":"stackoverflow","questionId":79383705,"title":"Cannot build frontend using Vite, TailwindCSS with PostCSS","tags":["reactjs","tailwind-css","vite","postcss","tailwind-css-4"],"text":"Title: Cannot build frontend using Vite, TailwindCSS with PostCSS\nTags: reactjs, tailwind-css, vite, postcss, tailwind-css-4\nSource: Stack Overflow\n\nQuestion:\n10:04:32 PM [vite] Internal server error: [postcss] It looks like you're trying to use tailwindcss directly as a PostCSS plugin. The PostCSS plugin has moved to a separate package, so to continue using Tailwind CSS with PostCSS you'll need to install @tailwindcss/postcss > and update your PostCSS configuration.\nPlugin: vite:css\nFile: ...\n\n10:04:32 PM [vite] Internal server error: [postcss] Missing > \"./components\" specifier in \"tailwindcss\" package\nPlugin: vite:css\nFile: ...\n\nI developed my chat app so I wanted everything updated so I removed `node_modules` then `npm install` and `build` then the above error keeps coming. It has to be something related to dependencies because it was working before I remove `node_modules`.\n\n```\nnpm cache clean --force\n\nnpm install -D tailwindcss autoprefixer postcss\n```\n\nI uninstalled them and did the above commands but it keeps giving me above error. What is the relation of PostCSS to TailwindCSS why are both dependent on each other?\n\n```\nnpx tailwindcss init\n```\n\nalso it says\n\nnpm error could not determine executable to run\nnpm error A complete log of this run can be found in: /home/amosmurmu/.npm/_logs/2025-01-23T15_39_50_870Z-debug-0.log\n\nI also tried to change Node.js version using NVM but it gives structured clone error so its not Node.js or NPX or NPM.\n\n========================================\n\nTop Answer:\nDelete the `postcss.config.js` file\n\nAnd then `npm i -d @tailwindcss/vite`,\nand also change the `vite.config.ts` file\n\n```\n...\nimport tailwindcss from \"@tailwindcss/vite\";\n\nexport default defineConfig(async () => ({\n plugins: [\n react(),\n tailwindcss(),\n ],\n...\n...\n```\n\nthen add `@import \"tailwindcss\";` in your css file\n\n========================================\n\nCode:\n```text\nnpm cache clean --force\n\nnpm install -D tailwindcss autoprefixer postcss\n```\n\n```text\nnpx tailwindcss init\n```\n\n```text\nnode_modules\n```\n\n```text\nnpm install\n```\n\n```text\nbuild\n```\n\n```text\nnode_modules\n```\n\n```text\nnpm install -D tailwindcss@3\n```\n\n```none\nnpm uninstall postcss autoprefixer\nnpm install tailwindcss @tailwindcss/vite\n```\n\n```none\nnpm uninstall autoprefixer\nnpm install tailwindcss @tailwindcss/postcss postcss\n```\n\n```text\n@tailwind\n```\n\n```text\ncontent\n```\n\n```text\n@import \"tailwindcss\";\n```\n\n```text\n.scss\n```\n\n```text\ntailwind.config.js\n```\n\n```text\n@config\n```\n\n```text\n@theme\n```\n\n```text\n@custom-variant\n```\n\n```text\n@utility\n```\n\n```text\n@config\n```\n\n```text\n@utility\n```\n\n```text\n...\nimport tailwindcss from \"@tailwindcss/vite\";\n\nexport default defineConfig(async () => ({\n  plugins: [\n    react(),\n    tailwindcss(),\n  ],\n...\n...\n```\n\n```text\npostcss.config.js\n```\n\n```text\nnpm i -d @tailwindcss/vite\n```\n\n```text\nvite.config.ts\n```\n\n```text\n@import \"tailwindcss\";\n```\n\n```text\nnode_modules\n```\n\n```text\nnpm install\n```\n\n```text\nnpm install -D tailwindcss@3\n```\n\n```text\nnpm install autoprefixer postcss\n```\n\n```text\nnpm run dev\n```\n\n```text\ncreate-next-app\n```\n\n```text\n--turboback\n```\n\n```text\n\"dev\": \"next dev\",\n```\n\n========================================\n\nComments:\n- There are huge differences between TailwindCSS v3 and v4. Use `npm install tailwindcss@3` to use v3. To migrate to v4, read the update guide in the documentation. The v4 was released a few days ago, so npm install tailwindcss now automatically installs v4 instead of v3. However, for this, you should no longer use the default Vite plugin, PostCSS and Autoprefixer: `npm install tailwindcss @tailwindcss&#47;vite` - TailwindCSS v4 with Vite; TailwindCSS v4 with PostCSS\n- Using v3 should resolve all your issues. If you want to switch to v4, make sure to read the update and new installation guides.\n- Related: Tailwind CSS v4: more packages and new Vite support and How to switch to a CSS-first configuration in Tailwind CSS v4 and above\n- Related: Is \"git init\" required when using the TailwindCSS v4 Vite plugin?\n- Which TailwindCSS v4 namespace matches a given TailwindCSS v3's theme keys?","metadata":{"transformedAt":"2026-08-18T18:33:46.395Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":33,"totalLines":213,"estimatedTokens":1026}}50{"id":"stack-66288645","source":"stackoverflow","questionId":66288645,"title":"Vite does not build tailwind based on config","tags":["tailwind-css","vite","postcss","tailwind-css-3"],"text":"Title: Vite does not build tailwind based on config\nTags: tailwind-css, vite, postcss, tailwind-css-3\nSource: Stack Overflow\n\nQuestion:\nI created a new `react-ts` app using `yarn create @vitejs/app my-app --template react-ts`.\n\nI installed tailwind using `yarn add --dev tailwindcss@latest postcss@latest autoprefixer@latest`.\n\nI initialized tailwind: `npx tailwindcss init -p`.\n\nI set `from` and `to` in `postcss.config.js`:\n\n```\nmodule.exports = {\n from: 'src/styles/App.css',\n to: 'src/styles/output.css',\n plugins: {\n tailwindcss: {},\n autoprefixer: {}\n }\n}\n```\n\nI created a `App.css` file in `src/styles`:\n\n```\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\nAccording to https://vitejs.dev/guide/features.html#postcss, any valid `postcss-load-config` syntax is allowed. `from` and `to` seem to be allowed.\n\nWhen I call `yarn dev` which essentially runs `vite`, my app is starting without build errors but tailwind output is not generated.\n\nWhat am I doing wrong?\n\n========================================\n\nTop Answer:\nFor those who are still having issues fixing this error: I fixed mine using this solution from another question.\n\nSolution Link\n\nKindly update your **vite.config** file with these changes.\n\n\r\n\r\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport tailwindcss from 'tailwindcss'\n\nexport default defineConfig({\n plugins: [react()],\n css: {\n postcss: {\n plugins: [tailwindcss()],\n },\n }\n})\n```\n\n========================================\n\nCode:\n```js\nmodule.exports = {\n  from: 'src/styles/App.css',\n  to: 'src/styles/output.css',\n  plugins: {\n    tailwindcss: {},\n    autoprefixer: {}\n  }\n}\n```\n\n```css\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n```text\nreact-ts\n```\n\n```text\nyarn create @vitejs/app my-app --template react-ts\n```\n\n```text\nyarn add --dev tailwindcss@latest postcss@latest autoprefixer@latest\n```\n\n```text\nnpx tailwindcss init -p\n```\n\n```text\nfrom\n```\n\n```text\nto\n```\n\n```text\npostcss.config.js\n```\n\n```text\nApp.css\n```\n\n```text\nsrc/styles\n```\n\n```text\npostcss-load-config\n```\n\n```text\nfrom\n```\n\n```text\nto\n```\n\n```text\nyarn dev\n```\n\n```text\nvite\n```\n\n```text\nfrom\n```\n\n```text\nto\n```\n\n```text\nimport\n```\n\n```text\nmain.tsx\n```\n\n```text\nsrc/styles/App.css\n```\n\n```text\nvite\n```\n\n```text\npostcss\n```\n\n```js\nmodule.exports = {\n  content: ['./src/*.{js,jsx}', './src/**/*.{js,jsx}'],\n  theme: {\n    extend: {},\n  },\n  plugins: [],\n}\n```\n\n```text\nconst defaultTheme = require('tailwindcss/defaultTheme')\n\nmodule.exports = {\n  mode: 'jit',\n  purge: {\n    enabled: process.env.NODE_ENV === 'production',\n    // classes that are generated dynamically, e.g. `rounded-${size}` and must\n    // be kept\n    safeList: [],\n    content: [\n      './index.html',\n      './src/**/*.{vue,js,ts}',\n      // etc.\n    ],\n  },\n  theme: {\n    extend: {\n      fontFamily: {\n        sans: ['Inter var', ...defaultTheme.fontFamily.sans],\n      },\n    },\n  },\n}\n```\n\n```text\nplugins: [react(),tailwindcss()],\n```\n\n```text\nimport tailwindcss from 'tailwindcss';\n```\n\n```text\nnpm install -D tailwindcss postcss autoprefixer\n```\n\n```text\nnpm install -D tailwindcss\n```\n\n```text\nexport const plugins = {\n```\n\n```text\ntailwindcss: {},\n```\n\n```text\nautoprefixer: {}\n```\n\n```text\n};\n```\n\n```text\n/** @type {import(tailwindcss').Config */\n```\n\n```text\nexport const content = [\"./src/**/*.{html,js,jsx,tsx}\"];\n```\n\n```text\nexport const theme = {\n```\n\n```text\nextend: {},\n```\n\n```text\n};\n```\n\n```text\nexport const plugins = [];\n```\n\n```text\n@tailwind base;\n```\n\n```text\n@tailwind components;\n```\n\n```text\n@tailwind utilities;\n```\n\n```text\nnpm install -D tailwindcss postcss autoprefixer\nnpx tailwindcss init -p\n```\n\n```text\nimport './index.css'\n```\n\n```text\nindex.css\n```\n\n```text\nmain.jsx\n```\n\n```text\nmain.jsx\n```\n\n```text\n/** @type {import('tailwindcss').Config} */\nmodule.exports = {\n  content: [\"./src/**/*.{js,jsx}\"],\n  mode: \"jit\",\n  theme: {\n    extend: {\n      colors: {\n        primary: \"#050816\",\n        secondary: \"#aaa6c3\",\n        tertiary: \"#151030\",\n        \"black-100\": \"#100d25\",\n        \"black-200\": \"#090325\",\n        \"white-100\": \"#f3f3f3\",\n      },\n      boxShadow: {\n        card: \"0px 35px 120px -15px #211e35\",\n      },\n      screens: {\n        xs: \"450px\",\n      },\n      backgroundImage: {\n        \"hero-pattern\": \"url('/src/assets/herobg.png')\",\n      },\n    },\n  },\n  plugins: [],\n};\n```\n\n```text\ntailwind. config\n```\n\n```text\n/** @type {import('tailwindcss').Config} */\nmodule.exports = {\n  content: [\n    \"./index.html\",\n    \"./src/**/*.{js,ts,jsx,tsx,vue}\",\n  ],\n  theme: {\n    extend: {},\n  },\n  plugins: [],\n}\n```\n\n```text\n[ReferenceError] module is not defined in ES module scope\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\nmodule.exports = {\n    plugins: {\n      tailwindcss: {},\n      autoprefixer: {},\n      // Add other PostCSS plugins here if needed\n    },\n  }\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport WindiCSS from 'vite-plugin-windicss'; // Import WindiCSS plugin\n\nexport default defineConfig({\n  plugins: [\n    react(),\n    WindiCSS(), \n  ],\n});\n```\n\n```text\nmodule.exports = {\n  plugins: {\n    tailwindcss: {},\n    autoprefixer: {},\n  },\n};\n```\n\n```text\npostcss.config.cjs\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport tailwindcss from 'tailwindcss'\n\nexport default defineConfig({\n  plugins: [react()],\n  css: {\n    postcss: {\n      plugins: [tailwindcss()],\n    },\n  }\n})\n```\n\n```json\n{\n  // ...\n  \"scripts\": {\n    \"dev\": \"vite\",\n  },\n  // ...\n}\n```\n\n```bash\nnpm run dev -- --force\n# ... or ...\nvite --force\n```\n\n```text\n--force\n```\n\n```text\nvite\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport tailwindcss from 'tailwindcss'\n\nexport default defineConfig({\n  plugins: [react()],\n  css: {\n    postcss: {\n      plugins: [tailwindcss()],\n    },\n  }\n})\n```\n\n```text\nimport \"../index.css\"\n```\n\n```text\nnpm install tailwindcss @tailwindcss/vite\n```\n\n```text\nimport tailwindcss from '@tailwindcss/vite'\n\nexport default defineConfig({\n  plugins: [tailwindcss()],\n})\n```\n\n```text\n@import \"tailwindcss\";\n```\n\n```text\nimport './index.css'\n```\n\n========================================\n\nComments:\n- it sounds like the package.json tailwind dev dependency needs to be installed by running yarn (or npm install)\n- The question was written during v3. If you're using v4 or higher, please see the installation guide or check other v4-related questions: Problem installing TailwindCSS with Vite; How to upgrade TailwindCSS?; Cannot build frontend using Vite\n- How to install TailwindCSS v4 with Next.js and How to install TailwindCSS v4 with Vite & React app\n- Could you elaborate giving some code example, I couldn't picture how you did, please.\n- That was my issue with vite, thanks for saving me time :)\n- This is actually the comment that worked for me. If these content strings are missing tailwind wont work.\n- This answer helped me. For future debuggers, make sure the \"content\" key points to some files :+1:\n- I get this Typescript error: `Type 'Plugin | Processor' is not assignable to type 'PluginOption'. Type 'Plugin' is not assignable to type 'PluginOption'.` - postcss v8.4.21, tailwindcss v3.2.7, vite v4.1.0\n- It didn't work for me. Throwing the same error as above. It doesn't import tailwindcss like this. Can you the working code?\n- stackoverflow.com/a/78451703 this worked for me\n- Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. **Would you kindly edit your answer to include additional details for the benefit of the community?**\n- The 'vue' part was missing in my tailwind.config.js, as it isn't mentioned in the official tailwind documentation. Adding that fixed the issue. Thanks!\n- Is your keyboard missing punctuation characters?","metadata":{"transformedAt":"2026-08-18T18:33:46.395Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":68,"totalLines":484,"estimatedTokens":2032}}51{"id":"stack-79372334","source":"stackoverflow","questionId":79372334,"title":"Blocked request. This host (\"frontend_web\") is not allowed","tags":["reactjs","node.js","nginx","dockerfile","vite"],"text":"Title: Blocked request. This host (\"frontend_web\") is not allowed\nTags: reactjs, node.js, nginx, dockerfile, vite\nSource: Stack Overflow\n\nQuestion:\nWhen building vite react in docker-compose application, a message appears when opening the web-site page\n\nBlocked request. This host (\"frontend_web\") is not allowed. To allow this host, add \"frontend_web\" to `server.allowedHosts` in vite.config.js.\n\nI tried to use `vite-plugin-allowed-hosts` but it gives me an error when building the docker-container\n\n[ERROR] Failed to resolve entry for package \"vite-plugin-allowed-hosts\". The package may have incorrect main/module/exports specified in its package.json. [plugin externalize-deps]\n\n========================================\n\nTop Answer:\nin angular you can open angular.json file and add this section there:\n\n```\n\"serve\": {\n \"builder\": \"@angular-devkit/build-angular:dev-server\",\n //add belove code\n \"options\": {\n \"allowedHosts\": [\"localhost\",\"your-domain\"]\n },\n //...\n },\n```\n\nin your-domain put your own url and it will get from that part\n\n========================================\n\nCode:\n```text\nserver.allowedHosts\n```\n\n```text\nvite-plugin-allowed-hosts\n```\n\n```js\nserver: {\n  allowedHosts: ['frontend_web'],\n}\n```\n\n```js\nserver: {\n  allowedHosts: true\n}\n```\n\n```text\nallowedHosts\n```\n\n```text\n\"serve\": {\n          \"builder\": \"@angular-devkit/build-angular:dev-server\",\n          //add belove code\n          \"options\": {\n            \"allowedHosts\": [\"localhost\",\"your-domain\"]\n          },\n          //...\n        },\n```\n\n```text\nng serve --disable-host-check\n```\n\n========================================\n\nComments:\n- I had this pop up today as well, and saw your question. Seems like some recent releases are relevant to the server.allowedHosts feature: github.com/vitejs/vite/commit/&hellip; I rolled back to version 6.0.6 which gets my application back up and running. This doesn't \"fix\" the issue technically, but perhaps more information will come out soon on how to properly set this up in newer versions.\n- Thanks for the answer! It turned out that the dockerfile specified the line ``` RUN npm install -g vite``` without specifying the version, so the latest release was installed, which broke the application. I installed the version below\n- or `allowedHosts: true` to allow any host\n- If this happens with a quasar app, add `allowedHosts: true` or `allowedHosts: ['yourhost']` to **devServer** in quasar.config.js or quasar.config.ts\n- whr should this be added? I do not have a vite.config.js or quasar.config.js. Should i add it now explicitly? I have an angular v19 application. And this error started occuring after i recently updated my packages with ng update.\n And as rightly pointed out, my package-lock.json showed a upgrade to vite.js (v6.0.6 to v6.0.11)\n- @angular/build\": { \"version\": \"19.1.7\", -> This upgraded the version from v6.0.7 to v6.0.11\n- i have the EXACT host added at `allowedHosts`, still gives the same error. weird\n- If you are using NUXT instead of using vite directly, add a vite/server/allowedHosts option to your **nuxt.config.js** or **nuxt.config.ts** file: export default defineNuxtConfig({ .. vite: { server: { allowedHosts: [\"forms.sosv.local\"], }, }, ... })\n- @SirishKumar Did you try the solution proposed here? stackoverflow.com/a/79600289/3937506\n- Thank you, this solve the issue\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- Yes, after I added this configuration it works: `\"options\": { \"allowedHosts\": [ \"host.docker.internal\" ] },`\n- it works! and vite docs is here : docs cn.vite.dev/config/server-options#server-allowedhosts\n- What are the possible negative side effects of this solution?\n- @ryanwebjackson assuming you do this in your local environment, I don't think there's any","metadata":{"transformedAt":"2026-08-18T18:33:46.395Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":93,"estimatedTokens":1064}}52{"id":"stack-77486735","source":"stackoverflow","questionId":77486735,"title":"Docker with Vite - env variables are undefined inside the docker container","tags":["reactjs","docker","environment-variables","vite"],"text":"Title: Docker with Vite - env variables are undefined inside the docker container\nTags: reactjs, docker, environment-variables, vite\nSource: Stack Overflow\n\nQuestion:\nI'm building a react project with Vite, and I'm new to Docker, and when I created a docker file, all was good, but the env variables are always undefined inside the Docker container.\n\nHere's my simple `Dockerfile` ...\n\n```\nFROM node:18.17.1-alpine\nWORKDIR /app\nCOPY package.json .\nRUN npm install\nCOPY . .\nRUN npm run build\nEXPOSE 8080\nCMD [\"npm\",\"run\",\"preview\"]\n```\n\nAnd here's the `.dockerignore` file ...\n\n```\nREADME.md\nbuild\ndist\nnode_modules\nLICENSE\npackage-lock.json\n.git\n.DS_Store\n.env\n```\n\nAnd here's the `.env` file ...\n\n```\nVITE_API_BASE_URL=https://example.com\n```\n\nAnd this is how I'm accessing the env variable inside the code ...\n\n```\nimport.meta.env.VITE_API_BASE_URL\n```\n\nWhenever I build the Docker image and run the Docker container, the `VITE_API_BASE_URL` is always undefined in the `network` tab, however when I remove the `.env` from the `.dockerignore` file and build the image again and run it, it works fine.\nBut obviously that's not the solution, I need the app to be able to read the env variables inside the Dockere container.\n\nWhat can I do?\n\n========================================\n\nTop Answer:\nI got to work passing env variable when running the container.\n\nIn my `.env.production` file in vite project I put the values in a standard starting with `MY_APP_`\n\n```\nVITE_API_SMARTGLPI_BACKEND=MY_APP_API_SMARTGLPI_BACKEND\nVITE_SAC_NTINF_URL=MY_APP_SAC_NTINF_URL\n```\n\nSo, I created a `env.sh` script with the content below:\n\n```\n#!/bin/sh\nfor i in $(env | grep MY_APP_)\ndo\n key=$(echo $i | cut -d '=' -f 1)\n value=$(echo $i | cut -d '=' -f 2-)\n echo $key=$value\n # sed All files\n # find /usr//nginx/html -type f -exec sed -i \"s|${key}|${value}|g\" '{}' +\n\n # sed JS and CSS only\n find /usr//nginx/html -type f \\( -name '*.js' -o -name '*.css' \\) -exec sed -i \"s|${key}|${value}|g\" '{}' +\ndone\n```\n\nThis script will be executed when the container get up and will change the values `MY_APP_API_SMARTGLPI_BACKEND` and `MY_APP_SAC_NTINF_URL` inside **js** and **css** code, replacing this values for the env vars informed on docker-compose.\n\nI created a `Dockerfile` with the content\n\n```\nFROM node:20.7.0-alpine as BUILD_IMAGE\nWORKDIR /app/react-app\nCOPY package.json .\nRUN npm install\nCOPY . .\nRUN npm run build\n\nFROM nginx:1.21.6-alpine as PRODUCTION_IMAGE\nCOPY --from=BUILD_IMAGE /app/react-app/dist/ /usr//nginx/html\nCOPY env.sh /docker-entrypoint.d/env.sh\nRUN chmod +x /docker-entrypoint.d/env.sh\n```\n\nAs you can see, I copied the `env.sh` to inside `/docker-entrypoint.d` directory of nginx container. All script inside this directory will be executed as soon the container get up.\n\nSo, I created the `docker-compose.yml` file with the content below:\n\n```\nversion: '3.3'\n\nservices:\n app:\n image: app-image:v1.0 \n environment:\n MY_APP_API_SMARTGLPI_BACKEND: \"URL_BACKEND\"\n MY_APP_SAC_NTINF_URL: \"URL_SAC_NTINF\"\n```\n\nMore datails, you can see in https://dev.to/sanjayttg/dynamic-environment-variables-for-dockerized-react-apps-5bc5\n\n========================================\n\nCode:\n```text\nFROM node:18.17.1-alpine\nWORKDIR /app\nCOPY package.json .\nRUN npm install\nCOPY . .\nRUN npm run build\nEXPOSE 8080\nCMD [\"npm\",\"run\",\"preview\"]\n```\n\n```text\nREADME.md\nbuild\ndist\nnode_modules\nLICENSE\npackage-lock.json\n.git\n.DS_Store\n.env\n```\n\n```text\nVITE_API_BASE_URL=https://example.com\n```\n\n```text\nimport.meta.env.VITE_API_BASE_URL\n```\n\n```text\nDockerfile\n```\n\n```text\n.dockerignore\n```\n\n```text\n.env\n```\n\n```text\nVITE_API_BASE_URL\n```\n\n```text\nnetwork\n```\n\n```text\n.env\n```\n\n```text\n.dockerignore\n```\n\n```text\nFROM node:18.17.1-alpine\n\n# Define build arguments for environment variables\nARG VITE_API_BASE_URL\nARG VITE_API_KEY\n\n# Set environment variables during the build process\nENV VITE_API_BASE_URL=$VITE_API_BASE_URL\nENV VITE_API_KEY=$VITE_API_KEY\n\nWORKDIR /app\n\nCOPY package.json .\nRUN npm install\nCOPY . .\n\n# Rest of your Dockerfile...\n\n# For example:\nRUN npm run build\n\nEXPOSE 8080\nCMD [\"npm\", \"run\", \"preview\"]\n```\n\n```text\ndocker build \\\n  --build-arg VITE_API_BASE_URL=https://example.com \\\n  --build-arg VITE_API_KEY=A12O6f90eCfMFf8 \\\n  -t your-image-name .\n```\n\n```text\nDockerfile\n```\n\n```text\nVITE_API_SMARTGLPI_BACKEND=MY_APP_API_SMARTGLPI_BACKEND\nVITE_SAC_NTINF_URL=MY_APP_SAC_NTINF_URL\n```\n\n```text\n#!/bin/sh\nfor i in $(env | grep MY_APP_)\ndo\n    key=$(echo $i | cut -d '=' -f 1)\n    value=$(echo $i | cut -d '=' -f 2-)\n    echo $key=$value\n    # sed All files\n    # find /usr/share/nginx/html -type f -exec sed -i \"s|${key}|${value}|g\" '{}' +\n\n    # sed JS and CSS only\n    find /usr/share/nginx/html -type f \\( -name '*.js' -o -name '*.css' \\) -exec sed -i \"s|${key}|${value}|g\" '{}' +\ndone\n```\n\n```text\nFROM node:20.7.0-alpine as BUILD_IMAGE\nWORKDIR /app/react-app\nCOPY package.json .\nRUN npm install\nCOPY . .\nRUN npm run build\n\nFROM nginx:1.21.6-alpine as PRODUCTION_IMAGE\nCOPY --from=BUILD_IMAGE /app/react-app/dist/ /usr/share/nginx/html\nCOPY env.sh /docker-entrypoint.d/env.sh\nRUN chmod +x /docker-entrypoint.d/env.sh\n```\n\n```text\nversion: '3.3'\n\nservices:\n  app:\n    image: app-image:v1.0 \n    environment:\n      MY_APP_API_SMARTGLPI_BACKEND: \"URL_BACKEND\"\n      MY_APP_SAC_NTINF_URL: \"URL_SAC_NTINF\"\n```\n\n```text\n.env.production\n```\n\n```text\nMY_APP_\n```\n\n```text\nenv.sh\n```\n\n```text\nMY_APP_API_SMARTGLPI_BACKEND\n```\n\n```text\nMY_APP_SAC_NTINF_URL\n```\n\n```text\nDockerfile\n```\n\n```text\nenv.sh\n```\n\n```text\n/docker-entrypoint.d\n```\n\n```text\ndocker-compose.yml\n```\n\n```text\nimport.meta.env\n```\n\n```text\nimport.meta.env\n```\n\n```text\nwindow.env = { key: process.env[key] }\n```\n\n```text\nimport.meta.env\n```\n\n```text\n.env\n```\n\n```text\nStill works like a charm - for future reference, im posting my VITE reactjs app Dockerfile\n\n\n\n    # Define build arguments for environment variables\nARG NODE_VERSION=22.14.0\n\n# First stage: Build the application\nFROM node:${NODE_VERSION}-alpine AS build\n\n# Set working directory for all build stages.\nWORKDIR /usr/src/app\n\nRUN --mount=type=bind,source=package.json,target=package.json \\\n    --mount=type=bind,source=package-lock.json,target=package-lock.json \\\n    --mount=type=cache,target=/root/.npm \\\n    npm ci\n\nENV VITE_API_BASE_URL=https://api.example.com/\n\n# Copy the rest of the source files into the image.\nCOPY . .\n\n# Run the build script.\nRUN npm run build\n\n# SET NODE_ENV to production\nENV NODE_ENV=production\n\n# Create a new stage for the production image\nFROM nginx:alpine\n\n# Copy the nginx configuration\nCOPY nginx.conf /etc/nginx/conf.d/default.conf\n\n# Copy the build output from the build stage\nCOPY --from=build /usr/src/app/dist /usr/share/nginx/html\n\n# Expose the port\nEXPOSE 80\n\n# Nginx starts automatically, no need for CMD\n\n\n\n    # Define build arguments for environment variables\nARG NODE_VERSION=22.14.0\n\n# First stage: Build the application\nFROM node:${NODE_VERSION}-alpine AS build\n\n# Set working directory for all build stages.\nWORKDIR /usr/src/app\n\nRUN --mount=type=bind,source=package.json,target=package.json \\\n    --mount=type=bind,source=package-lock.json,target=package-lock.json \\\n    --mount=type=cache,target=/root/.npm \\\n    npm ci\n\nENV VITE_API_BASE_URL=https://api.example.com/\n\n# Copy the rest of the source files into the image.\nCOPY . .\n\n# Run the build script.\nRUN npm run build\n\n# SET NODE_ENV to production\nENV NODE_ENV=production\n\n# Create a new stage for the production image\nFROM nginx:alpine\n\n# Copy the nginx configuration\nCOPY nginx.conf /etc/nginx/conf.d/default.conf\n\n# Copy the build output from the build stage\nCOPY --from=build /usr/src/app/dist /usr/share/nginx/html\n\n# Expose the port\nEXPOSE 80\n\n# Nginx starts automatically, no need for CMD\n```\n\n```js\n# Define build arguments for environment variables\nARG NODE_VERSION=22.14.0\n\n# First stage: Build the application\nFROM node:${NODE_VERSION}-alpine AS build\n\n# Set working directory for all build stages.\nWORKDIR /usr/src/app\n\nRUN --mount=type=bind,source=package.json,target=package.json \\\n    --mount=type=bind,source=package-lock.json,target=package-lock.json \\\n    --mount=type=cache,target=/root/.npm \\\n    npm ci\n\nENV VITE_API_BASE_URL=https://api.example.com/\n\n# Copy the rest of the source files into the image.\nCOPY . .\n\n# Run the build script.\nRUN npm run build\n\n# SET NODE_ENV to production\nENV NODE_ENV=production\n\n# Create a new stage for the production image\nFROM nginx:alpine\n\n# Copy the nginx configuration\nCOPY nginx.conf /etc/nginx/conf.d/default.conf\n\n# Copy the build output from the build stage\nCOPY --from=build /usr/src/app/dist /usr/share/nginx/html\n\n# Expose the port\nEXPOSE 80\n\n# Nginx starts automatically, no need for CMD\n```\n\n========================================\n\nComments:\n- And how exactly *are* you trying to set the env vars on the running container? Note that they're likely required at *build* time, not runtime (which is a problem for reasons I expand on in blog.jonrshar.pe/2020/Sep/19/spa-config.html).\n- @jonrsharpe I'm not exactly sure what you mean, this is all I have, I'm new to Docker. But this is how I'm trying to read the env variable in my code `import.meta.env.VITE_API_BASE_URL`\n- I'm not asking how you're trying to access them in the code, I'm asking how you're trying to provide them to the container. If the answer is that you aren't, then there's the problem.\n- @jonrsharpe Aha, got it. So I'll search on that point, that's what the missing piece of the puzzle. Thank you for the hint.\n- I was in similar line and this works for passing env variables on build time, how to update this at run time or while starting the container.\n- This is nonsense! How should I use one container for dev, stage, prod? I will have to create 3 different images and use them...\n- Is there another way to do this? There's got to be a better way than having to list every single variable in your Dockerfile.\n- How is this making sense by storing ENV inside a docker image?\n- Doesn't work for SSR, it seems to detect mismatches when you change it. Also, the static file names stay the same, so old values will still be cached by clients even if you change the container env vars. People need to keep that in mind.\n- How are you going to set `window.env` during SSR?","metadata":{"transformedAt":"2026-08-18T18:33:46.395Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":455,"estimatedTokens":2563}}53{"id":"stack-66878723","source":"stackoverflow","questionId":66878723,"title":"How to setup PhpStorm / WebStorm to work with Vite aliases?","tags":["phpstorm","webstorm","vite"],"text":"Title: How to setup PhpStorm / WebStorm to work with Vite aliases?\nTags: phpstorm, webstorm, vite\nSource: Stack Overflow\n\nQuestion:\nVite isn't supported by the PhpStorm / WebStorm yet, so given following Vite configuration:\n\n```\nexport default defineConfig({\n plugins: [vue()],\n resolve: {\n alias: {\n '@': path.resolve(__dirname, '/src'),\n },\n },\n});\n```\n\nit doesn't recognize the following import correctly:\n\n```\nimport { getAllItems } from '@/api'\n```\n\nHow can this be setup to work correctly?\n\n========================================\n\nTop Answer:\nI had this issue with Webstorm and solved it by adding a file named `jsonfig.json` with the following content to my project directory:\n\n```\n{\n \"compilerOptions\": {\n \"baseUrl\": \".\",\n \"paths\": {\n \"@/*\": [\n \"/src/*\"\n ]\n }\n }\n}\n```\n\n========================================\n\nCode:\n```js\nexport default defineConfig({\n  plugins: [vue()],\n  resolve: {\n    alias: {\n      '@': path.resolve(__dirname, '/src'),\n    },\n  },\n});\n```\n\n```js\nimport { getAllItems } from '@/api'\n```\n\n```js\nSystem.config({\n  \"paths\": {\n    \"@/*\": \"./src/*\",\n  }\n});\n```\n\n```js\n{\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@/*\": [\"./src/*\"]\n    }\n  }\n}\n```\n\n```text\nphpstorm.config.js\n```\n\n```text\n.gitignore\n```\n\n```text\njsconfig.json\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@/*\": [\n        \"/src/*\"\n      ]\n    }\n  }\n}\n```\n\n```text\njsonfig.json\n```\n\n```js\nconst alias = {\n  '@': path.join(__dirname, './src/renderer/src'),\n  static: path.resolve(__dirname, '../static'),\n  Core: path.resolve(__dirname, 'src/core'),\n  Main: path.resolve(__dirname, 'src/main'),  \n  Custom: path.resolve(__dirname, 'src/custom/'),\n  Store: path.resolve(__dirname, 'src/renderer/src/store/'),\n  Views: path.resolve(__dirname, 'src/renderer/src/components/views'), \n  Router: path.resolve(__dirname, 'src/renderer/src/router'),\n  NM: path.resolve(__dirname, 'node_modules'),\n  Root: path.resolve(__dirname, '.'),\n  crypto: 'crypto-browserify',\n  stream: 'stream-browserify',\n  zlib: 'browserify-zlib',\n  buffer: 'buffer/',\n  util: 'util/'\n}\n```\n\n```js\n{\n  name: 'phpstorm-config-generator',\n  configureServer() {\n    const fs = require('fs')\n    const path = require('path')\n    const aliasObj = alias\n    const paths = {}\n    for (const [key, value] of Object.entries(aliasObj)) {\n      if (typeof value === 'string') {\n        const aliasKey = key.endsWith('/*') ? key : key + '/*'\n        const aliasValue = value.endsWith('/*') ? value : value + '/*'\n        paths[aliasKey] = aliasValue\n      }\n    }\n    const configContent =\n      'System.config({\\n  \"paths\": ' + JSON.stringify(paths, null, 4) + '\\n});\\n'\n    fs.writeFileSync(path.resolve(__dirname, 'phpstorm.config.js'), configContent, 'utf8')\n  }\n}\n```\n\n========================================\n\nComments:\n- another option is using `jsconfig.json` for specifying path aliases, see code.visualstudio.com/docs/languages/&hellip;\n- @lena yeah haha, I'd say using visual studio is another option indeed :P\n- I'm not suggesting using VSCode:) WebStorm/PHpStorm do support resolving aliases defined in `jsconfig.json`, so it's just another way to define your aliases. We can't afford supporting all possible ways to define path mappings coming from different bundlers, frameworks and plugins, so in the future we'd likely provide some unified way to deal with them in the IDE. And using `jsconfig.json` is one of the options we are evaluating now\n- Oh, sorry then :sweat-smile: I was a bit shocked that a jetBrains engineer advocates using VScode. I'm updating my answer right away!\n- Decent workaround. A bit of a pain to then need to define your aliases in 2 files, solely for the IDE however.\n- What about just giving us a way, in IDE settings to define custom aliases?\n- If I try System.config({ \"paths\": { \"/autocode-js/*\": \"./web/app/autocode/*\" } }); -- then import {...} from \"/autocode-js/php-enums.mjs\" is still not recognized. Any ideas?\n- @JohnCarrell That would be nice, but versioning it as a config is a great way to that little fix with a team.\n- You are amazing even phpstorm support couldn't solve this\n- Using `jsconfig.json` seems to be working with PHPStorm version 2024.3.2.1.","metadata":{"transformedAt":"2026-08-18T18:33:46.395Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":165,"estimatedTokens":1055}}54{"id":"stack-68217795","source":"stackoverflow","questionId":68217795,"title":"Vite: resolve.alias - how to resolve paths?","tags":["javascript","vite"],"text":"Title: Vite: resolve.alias - how to resolve paths?\nTags: javascript, vite\nSource: Stack Overflow\n\nQuestion:\nWhat can resolve.alias do? It doesn't resolve the path below:\n\n```\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport path from 'path'\n\nexport default defineConfig({\n resolve: {\n alias: {\n '@': path.resolve(__dirname, '/src'),\n },\n }\n})\n```\n\nIn my HTML:\n\n```\n\n```\n\nError in the browser Console:\n\n```\nGET http://localhost:3000/@/assets/images/sample-1.jpg \nFailed to load resource: the server responded with a status of 404 (Not Found)\nclient:180 [vite] connecting...\nclient:202 [vite] connected.\n```\n\nAny ideas how to do it correctly?\n\n========================================\n\nTop Answer:\nLooks like no additional plugins needed (vite 3.1.0), configuration `vite.config.js`:\n\n```\nimport { defineConfig } from 'vite';\nimport * as path from 'path';\n\nexport default defineConfig({\n...\n resolve: {\n alias: [\n { find: '@', replacement: path.resolve(__dirname, 'src') },\n ],\n },\n...\n});\n```\n\n`tsconfig.json`\n\n```\n{\n \"compilerOptions\": {\n...\n \"baseUrl\": \".\",\n \"paths\": {\n \"@/*\": [\"./src/*\"],\n },\n...\n },\n...\n}\n```\n\nAlso don't forget about linting, eslint also should know about aliases. Just install eslint plugin `eslint-import-resolver-alias` and define it in eslint config\n`.eslintrc.js`\n\n```\nmodule.exports = {\n...\n settings: {\n 'import/resolver': {\n node: {\n extensions: ['.js', '.vue', '.ts', '.d.ts'],\n },\n alias: {\n extensions: ['.vue', '.js', '.ts', '.scss', '.d.ts'],\n map: [\n ['@/components', './src/components'],\n ['@/pages', './src/pages'],\n ['@/router', './src/router'],\n ['@/store', './src/store'],\n ['@/styles', './src/styles'],\n ['@/types', './src/types'],\n ['@/utils', './src/utils'],\n ],\n },\n },\n },\n...\n};\n```\n\nAs you can see I defined aliases for every folder, it's because i got problem with alias for whole folder `src`, it throw error for packages started with `@` symbol - can't resolve package, but current way works well.\n\n========================================\n\nCode:\n```text\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport path from 'path'\n\nexport default defineConfig({\n  resolve: {\n    alias: {\n      '@': path.resolve(__dirname, '/src'),\n    },\n  }\n})\n```\n\n```text\n<img src=\"@/assets/images/sample-1.jpg\">\n```\n\n```text\nGET http://localhost:3000/@/assets/images/sample-1.jpg \nFailed to load resource: the server responded with a status of 404 (Not Found)\nclient:180 [vite] connecting...\nclient:202 [vite] connected.\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport alias from '@rollup/plugin-alias'\nimport { resolve } from 'path'\n\nconst projectRootDir = resolve(__dirname);\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    vue(),\n    alias({\n      entries: [\n        {\n          find: '@',\n          replacement: resolve(projectRootDir, 'src')\n        }\n      ]\n    })\n  ],\n  server: {\n    host: '0.0.0.0',\n    port: 10086, \n    open: false,\n    cors: true, \n  },\n  build: {\n    outDir: 'dist',\n  }\n})\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport alias from '@rollup/plugin-alias'\nimport { resolve } from 'path'\n\nconst projectRootDir = resolve(__dirname);\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    alias(),\n    vue()\n  ],\n  resolve: {\n    alias: {\n      \"@\": resolve(projectRootDir, \"src\"),\n    },\n  },\n  server: {\n    host: '0.0.0.0',\n    port: 10086,\n    open: false, \n    cors: true, \n  },\n  build: {\n    outDir: 'dist',\n  }\n})\n```\n\n```text\nimport vue from '@vitejs/plugin-vue'\nimport { defineConfig } from 'vite'\nimport path from 'path'\n\nexport default defineConfig({\n  plugins: [ vue() ],\n  resolve: {\n    alias: [\n      { find: '@', replacement: path.resolve(__dirname, './src') },\n      { find: '@config', replacement: path.resolve(__dirname, './src/config') },\n      { find: '@plugins', replacement: path.resolve(__dirname, './src/plugins') },\n      { find: '@views', replacement: path.resolve(__dirname, './src/views') },\n      { find: '@mixins', replacement: path.resolve(__dirname, './src/mixins') },\n      { find: '@svg', replacement: path.resolve(__dirname, './src/svg') },\n      { find: '@models', replacement: path.resolve(__dirname, './src/models') },\n      { find: '@components', replacement: path.resolve(__dirname, './src/components') },\n    ]\n  }\n})\n```\n\n```text\nresolve?: ResolveOptions & {\n  alias?: AliasOptions;\n};\n```\n\n```text\nexport declare type AliasOptions = readonly Alias[] | { [find: string]: string }\n```\n\n```js\nimport { defineConfig } from 'vite';\nimport * as path from 'path';\n\nexport default defineConfig({\n...\n    resolve: {\n        alias: [\n            { find: '@', replacement: path.resolve(__dirname, 'src') },\n        ],\n    },\n...\n});\n```\n\n```text\n{\n  \"compilerOptions\": {\n...\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@/*\": [\"./src/*\"],\n    },\n...\n  },\n...\n}\n```\n\n```text\nmodule.exports = {\n...\n    settings: {\n        'import/resolver': {\n            node: {\n                extensions: ['.js', '.vue', '.ts', '.d.ts'],\n            },\n            alias: {\n                extensions: ['.vue', '.js', '.ts', '.scss', '.d.ts'],\n                map: [\n                    ['@/components', './src/components'],\n                    ['@/pages', './src/pages'],\n                    ['@/router', './src/router'],\n                    ['@/store', './src/store'],\n                    ['@/styles', './src/styles'],\n                    ['@/types', './src/types'],\n                    ['@/utils', './src/utils'],\n                ],\n            },\n        },\n    },\n...\n};\n```\n\n```text\nvite.config.js\n```\n\n```text\ntsconfig.json\n```\n\n```text\neslint-import-resolver-alias\n```\n\n```text\n.eslintrc.js\n```\n\n```text\nsrc\n```\n\n```text\n@\n```\n\n```text\nimport { resolve, join } from 'path';\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n  resolve: {\n    alias: [\n      { find: /@(.*)/, replacement: join(resolve(__dirname, 'src'), \"$1\") }\n    ]\n  }\n});\n```\n\n```text\n{\n    \"compilerOptions\": {\n        \"paths\": {\n            \"@*\": [\"./src/*\"]\n        }\n     }\n}\n```\n\n```text\n@*\n```\n\n```text\nimport @(.*)\n```\n\n```text\n__dirname/src/$1\n```\n\n```text\n$1\n```\n\n```text\n@\n```\n\n```text\ntsconfig.json\n```\n\n```text\nbody {\n    cursor: url(\"/assets/g-portfoliocursor-64.png\"), auto;\n}\n\n#welcome-background-image {\n    background-image: linear-gradient(90deg, #0c4cff36, #6aabffa3),\n        url(\"/assets/water-droplets.jpg\");\n    background-size: 100% 100vh;\n}\n\n#main-background-image {\n    background-image: linear-gradient(90deg, #00000036, #00ffffa3),\n        url(\"/assets/water-droplets.jpg\");\n    background-size: 100% 100vh;\n}\n```\n\n```text\nbody {\n    cursor: url(\"/public/assets/g-portfoliocursor-64.png\"), auto;\n}\n\n#welcome-background-image {\n    background-image: linear-gradient(90deg, #0c4cff36, #6aabffa3),\n        url(\"/public/assets/water-droplets.jpg\");\n    background-size: 100% 100vh;\n}\n\n#main-background-image {\n    background-image: linear-gradient(90deg, #00000036, #00ffffa3),\n        url(\"/public/assets/water-droplets.jpg\");\n    background-size: 100% 100vh;\n}\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport laravel from \"laravel-vite-plugin\";\n\nexport default defineConfig({\n    base: '/',\n    build: {\n        outDir: \"public\",\n        emptyOutDir: false,\n        rollupOptions: {\n            input: {\n                main: \"resources/js/app.js\",\n            },\n            output: {\n                format: \"umd\",\n                entryFileNames: \"app.js\",\n                assetFileNames: (assetInfo) => {\n                    if (assetInfo.name.endsWith(\".css\")) {\n                        return \"app.css\";\n                    }\n                    return \"assets/[name][extname]\";\n                    // return \"assets/[name]-[hash][extname]\";\n                },\n                globals: {\n                    jquery: \"$\",\n                },\n            },\n        },\n        cssCodeSplit: false,\n        cssMinify: true,\n        minify: false,\n    },\n    plugins: [laravel([\"/app.css\", \"/app.js\"])],\n    resolve: {\n        alias: {\n            xlsx: \"./public/uncompiled-js/xlsx.full.min.js\",\n        },\n    },\n    server: {\n        host: \"localhost\",\n        port: 3000,\n        strictPort: true,\n        hmr: {\n            overlay: false,\n        },\n        watch: {\n            usePolling: true,\n        },\n    },\n});\n```\n\n========================================\n\nComments:\n- * As a note for people coming these days, I think using @ as an alias is probably a bad idea as many npm packages now include @ as a prefix and so you'll need to work around that. Perhaps use ~ which for aspnet devs has always meant 'the root'.\n- the config for tsconfig.json work also in jsconfig.json, in VS Code i had no need for the eslint.js config\n- Thanks, this has been very helpful, do you know how to activate IDE autocomplete for aliases? When I type `import \"@...\"`, the path autocomplete doesn't work.\n- I found out how to do it. I activated this in the settings. `\"javascript.suggest.paths\": true` and `\"typescript.suggest.paths\": true` !image","metadata":{"transformedAt":"2026-08-18T18:33:46.395Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":450,"estimatedTokens":2278}}55{"id":"stack-71180561","source":"stackoverflow","questionId":71180561,"title":"Vite - change ouput directory of assets","tags":["javascript","reactjs","vite"],"text":"Title: Vite - change ouput directory of assets\nTags: javascript, reactjs, vite\nSource: Stack Overflow\n\nQuestion:\nBy default **Vite** generates files in the source directory under `dist`.\n\n```\nmy-app/\n├─ node_modules/\n├─ dist/\n│ ├─ assets/\n| | | index.js\n| | | index.css \n│ ├─ index.html\n├─ index.html\n├─ main.js\n├─ style.scss\n├─ package.json\n```\n\nI need to create a different folder for `js` and `css` files under `assets`. In other words, I need to put `js` and `css` filer under `/assets/js` and `/assets/css` folders respectively.\n\n```\nmy-app/\n├─ node_modules/\n├─ dist/\n│ ├─ assets/\n| | |-js/\n| | | index.js\n| | |-css/\n| | | index.css\n```\n\nThis is my config file.\n\n```\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport svgrPlugin from \"vite-plugin-svgr\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n base: \"./\",\n plugins: [react(), svgrPlugin()],\n server: {\n open: true,\n proxy: {\n \"/base\": {\n target: \"http://localhost:19000\",\n changeOrigin: true,\n rewrite: (path) => path.replace(/^\\/base/, \"\"),\n },\n },\n },\n});\n```\n\nHow to do so?\n\n========================================\n\nTop Answer:\nIf you use `@font-face` in your css file, it masses up. You may need to put fonts in the same folder as the css files.\n\n*I have used `woff` and `woff2` fonts*\n\n```\nrollupOptions: {\n output: {\n assetFileNames: (assetInfo) => {\n var info = assetInfo.name.split(\".\");\n var extType = info[info.length - 1];\n if (/png|jpe?g|svg|gif|tiff|bmp|ico/i.test(extType)) {\n extType = \"img\";\n } else if (/woff|woff2/.test(extType)) {\n extType = \"css\";\n }\n return `static/${extType}/[name]-[hash][extname]`;\n },\n chunkFileNames: \"static/js/[name]-[hash].js\",\n entryFileNames: \"static/js/[name]-[hash].js\",\n },\n }\n```\n\n========================================\n\nCode:\n```text\nmy-app/\n├─ node_modules/\n├─ dist/\n│  ├─ assets/\n|  |    | index.js\n|  |    | index.css        \n│  ├─ index.html\n├─ index.html\n├─ main.js\n├─ style.scss\n├─ package.json\n```\n\n```text\nmy-app/\n├─ node_modules/\n├─ dist/\n│  ├─ assets/\n|  |    |-js/\n|  |    |   index.js\n|  |    |-css/\n|  |    |  index.css\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport svgrPlugin from \"vite-plugin-svgr\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  base: \"./\",\n  plugins: [react(), svgrPlugin()],\n  server: {\n    open: true,\n    proxy: {\n      \"/base\": {\n        target: \"http://localhost:19000\",\n        changeOrigin: true,\n        rewrite: (path) => path.replace(/^\\/base/, \"\"),\n      },\n    },\n  },\n});\n```\n\n```text\ndist\n```\n\n```text\njs\n```\n\n```text\ncss\n```\n\n```text\nassets\n```\n\n```text\njs\n```\n\n```text\ncss\n```\n\n```text\n/assets/js\n```\n\n```text\n/assets/css\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  build: {\n    rollupOptions: {\n      output: {\n        1️⃣\n        assetFileNames: (assetInfo) => {\n          let extType = assetInfo.name.split('.').at(1);\n          if (/png|jpe?g|svg|gif|tiff|bmp|ico/i.test(extType)) {\n            extType = 'img';\n          }\n          return `assets/${extType}/[name]-[hash][extname]`;\n        },\n        2️⃣\n        chunkFileNames: 'assets/js/[name]-[hash].js',\n        3️⃣\n        entryFileNames: 'assets/js/[name]-[hash].js',\n      },\n    },\n  },\n});\n```\n\n```text\nbuild.rollupOptions\n```\n\n```text\noutput.assetFileNames\n```\n\n```text\noutput.chunkFileNames\n```\n\n```text\noutput.entryFileNames\n```\n\n```text\nindex.js\n```\n\n```text\nassetInfo.name.split('.').at(1);\n```\n\n```text\nassetInfo.name.split('.')[1];\n```\n\n```text\nrollupOptions: {\n      output: {\n        assetFileNames: (assetInfo) => {\n          var info = assetInfo.name.split(\".\");\n          var extType = info[info.length - 1];\n          if (/png|jpe?g|svg|gif|tiff|bmp|ico/i.test(extType)) {\n            extType = \"img\";\n          } else if (/woff|woff2/.test(extType)) {\n            extType = \"css\";\n          }\n          return `static/${extType}/[name]-[hash][extname]`;\n        },\n        chunkFileNames: \"static/js/[name]-[hash].js\",\n        entryFileNames: \"static/js/[name]-[hash].js\",\n      },\n    }\n```\n\n```text\n@font-face\n```\n\n```text\nwoff\n```\n\n```text\nwoff2\n```\n\n```text\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n  root: './src',\n  build: {\n    outDir: '../dist',\n    assetsDir: '', // Leave `assetsDir` empty so that all static resources are placed in the root of the `dist` folder.\n    assetsInlineLimit: 0,\n    rollupOptions: {\n      // input: {\n      //   // Uncomment if you need to specify entry points for .html files\n      //   index: resolve(__dirname, 'src/index.html'),\n      //   myworks: resolve(__dirname, 'src/my-works.html'),\n      //   thoughts: resolve(__dirname, 'src/thoughts.html'),\n      //   about: resolve(__dirname, 'src/about.html'),\n      //   contact: resolve(__dirname, 'src/contact.html'),\n      // },\n      output: {\n        entryFileNames: 'js/[name]-[hash].js', // If you need a specific file name, comment out\n        chunkFileNames: 'js/[name]-[hash].js', // these lines and uncomment the bottom ones\n        // entryFileNames: chunk => {\n        //   if (chunk.name === 'main') {\n        //     return 'js/main.min.js';\n        //   }\n        //   return 'js/main.min.js';\n        // },\n        assetFileNames: assetInfo => {\n          const info = assetInfo.name.split('.');\n          const extType = info[info.length - 1];\n          if (/\\.(png|jpe?g|gif|svg|webp|webm|mp3)$/.test(assetInfo.name)) {\n            return `media/[name]-[hash].${extType}`;\n          }\n          if (/\\.(css)$/.test(assetInfo.name)) {\n            return `css/[name]-[hash].${extType}`;\n          }\n          if (/\\.(woff|woff2|eot|ttf|otf)$/.test(assetInfo.name)) {\n            return `fonts/[name]-[hash].${extType}`;\n          }\n          return `[name]-[hash].${extType}`;\n        },\n      },\n    },\n  },\n});\n```\n\n```text\nimport '../scss/style.scss'\n```\n\n```text\n<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <!-- <link rel=\"stylesheet\" href=\"scss/style.scss\" /> \".scss styles can be included in html and not in main.js\" -->\n    <title class=\"dawd\">Starter_Vite</title>\n  </head>\n  <body>\n    <div id=\"app\"><p class=\"dawd\">Lorem ipsum dolor sit amet.</p></div>\n    <script type=\"module\" src=\"js/main.js\"></script>\n  </body>\n</html>\n```\n\n```text\nStarter_Vite\n    ├── .gitignore\n    ├── package.json\n    ├── vite.config.js\n    └── src\n        ├── index.html\n        ├── fonts\n        │   ├── iosevka-ss11-extendedthin.ttf\n        │   ├── MuseoCyrl-500.otf\n        │   └── MuseoCyrl-500.woff2\n        ├── js\n        │   └── main.js\n        ├── media\n        │   └── 0.webp\n        └── scss\n            ├── style.scss\n            └── _fonts.scss\n```\n\n```text\ndist\n├── index.html\n├── css\n│   └── index-113614d4.css\n├── fonts\n│   ├── iosevka-ss11-extendedthin-550d1ad8.ttf\n│   ├── MuseoCyrl-500-8f1dc1cc.otf\n│   └── MuseoCyrl-500-dc3a33d1.woff2\n├── js\n│   └── index-190da3b7.js\n└── media\n    └── 0-21ab3b1b.webp\n```\n\n```text\nnpm i sass\n```\n\n```text\nnpm i vite\n```\n\n========================================\n\nComments:\n- This works well except I changed it to `assetInfo.name.split('.').at(-1)` to get the last item in the array instead of the 2nd. In my case there was a `.` in my user folder name that broke it.\n- Thanks, I wish they added this example in the docs. I couldnt find an example on how to write that function except here.\n- Honestly you should use `.pop()` to remove the last element from the array, since there can be more than one dot and then this hardcoded [1] index won't work","metadata":{"transformedAt":"2026-08-18T18:33:46.396Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":372,"estimatedTokens":1937}}56{"id":"stack-78979789","source":"stackoverflow","questionId":78979789,"title":"Tailwind error when installing shadcn in Vite React App","tags":["reactjs","npm","tailwind-css","vite","shadcnui"],"text":"Title: Tailwind error when installing shadcn in Vite React App\nTags: reactjs, npm, tailwind-css, vite, shadcnui\nSource: Stack Overflow\n\nQuestion:\nI was setting up shadcn in a React App using Vite by using the following command:\n\n`npx shadcn@latest init`\n\nand I received an error (please see error below). I had installed tailwind and did setup as mentioned on official website.\n\n`npm install -D tailwindcss postcss autoprefixer`\n\n`npx tailwindcss init -p`\n\nError:\n\nNo Tailwind CSS configuration found at\n/Users/mubashirahmed/Code/shadcn-project.\n\nIt is likely you do not have\nTailwind CSS installed or have an invalid configuration.\n\nInstall\nTailwind CSS then try again. \n\nVisit https://tailwindcss.com/docs/guides/vite to get started.\n\nWhat could be the possible reason for that?\n\n========================================\n\nTop Answer:\nCurrent approach\n\nin twind v4\n\nin global.css or in style.css\n\nuse\n\n```\n@import \"tailwindcss\";\n```\n\nnow run\n\n```\nnpx --legacy-peer-deps shadcn@latest init\n```\n\nin case the dep problem there in the project other wise only\n\n```\nnpx shadcn@latest init\n```\n\nalso it can be\n\n```\nnpx shadcn@latest create\n```\n\n========================================\n\nCode:\n```text\nnpx shadcn@latest init\n```\n\n```text\nnpm install -D tailwindcss postcss autoprefixer\n```\n\n```text\nnpx tailwindcss init -p\n```\n\n```text\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n```text\n@import \"tailwindcss\";\n```\n\n```text\nnpx --legacy-peer-deps shadcn@latest init\n```\n\n```text\nnpx shadcn@latest init\n```\n\n```text\nnpx shadcn@latest create\n```\n\n========================================\n\nComments:\n- This question is similar to: Error Installing Shadcn UI and Tailwind CSS in React.js Project with Vite.\n- This worked for me\n- and note that if you're using sass/scss you have to change your global style file from scss extension to css\n- @AbolfazlAkbarzadeh thanks. I wanted to ask one more thing, when I copy components from shadcn website into my app, components work but the css is very different. Do you know what could be the reason? By different I mean it seems some of the css is not getting applied properly.\n- Nevermind, had some issues in config file.\n- @mubashir maybe, but it's better to install shadcn components by it's cli interface to prevent this kind of issues \"npx shadcn add \"\n- Worked for me. I didn't have an index.css file in my project\n- Until TailwindCSS v3, you had to the steps in the v3 documentation 100%. However, today, running `npm install tailwindcss` will install v4 by default. So, you either the new v4 installation steps or continue using the v3 version with the `npm install tailwindcss@3` command.\n- I ran into the same error but with tailwind v4 which as far as I can tell just isn't supported with the shadcn cli (i.e. it yields the tailwind css config error). This blog post outlines an alternative though.\n- @GregVenech Yes, you made the right conclusion. We've gathered more information on the topic here: Error Installing Shadcn UI and Tailwind CSS in React.js Project with Vite - A few days ago, Shadcn officially started supporting TailwindCSS v4; See: `shadcn-ui&#47;ui` #6427 and Shadcn UI with TailwindCSS v4\n- Thanks this works.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:46.396Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":115,"estimatedTokens":868}}57{"id":"stack-68643743","source":"stackoverflow","questionId":68643743,"title":"Separating Material UI in Vite (Rollup) as a manual chunk to reduce chunk size","tags":["reactjs","material-ui","rollup","vite"],"text":"Title: Separating Material UI in Vite (Rollup) as a manual chunk to reduce chunk size\nTags: reactjs, material-ui, rollup, vite\nSource: Stack Overflow\n\nQuestion:\nIs anyone using Vite to bundle their MUI app? I was surprised at how big my vendor chunk (1.1MB) was from Vite/Rollup. I've come up with the below config which separates MUI packages into it's own chunk:\n\n```\nimport { defineConfig } from \"vite\";\nimport reactRefresh from \"@vitejs/plugin-react-refresh\";\nimport { dependencies } from \"./package.json\";\n\n// whenever you get the error: (!) Some chunks are larger than 500kb after minification\n// find the biggest lib in your vendors chunk and add it to bigLibs\nconst bigLibs = [\n { regExp: /^@material-ui*/, chunkName: \"@material-ui\" },\n { regExp: /^@aws-amplify*/, chunkName: \"@aws-amplify\" },\n];\n\nfunction getManualChunks(deps: Record) {\n return Object.keys(deps).reduce(\n (prev, cur) => {\n let isBigLib = false;\n for (const l of bigLibs) {\n if (l.regExp.test(cur)) {\n isBigLib = true;\n if (prev[l.chunkName]) {\n prev[l.chunkName].push(cur);\n } else {\n prev[l.chunkName] = [cur];\n }\n break;\n }\n }\n if (!isBigLib) prev.vendors.push(cur);\n return prev;\n },\n { vendors: [] } as Record\n );\n}\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n build: {\n rollupOptions: {\n output: {\n manualChunks: getManualChunks(dependencies),\n },\n },\n },\n plugins: [reactRefresh()],\n resolve: {\n alias: [\n {\n find: \"./runtimeConfig\",\n replacement: \"./runtimeConfig.browser\",\n },\n ],\n },\n});\n```\n\nbut... I get an error in the browser:\n\n```\n@material-ui.1d552186.js:1 Uncaught TypeError: Cannot read property 'exports' of undefined\n at @material-ui.1d552186.js:1\n```\n\nDoes anyone know what's going on? I have a suspicion that I'm not correctly tree shaking.\n\n========================================\n\nTop Answer:\nIf you wanna spare all modules try this\n\n```\n...\nmanualChunks: (id) => {\n if (id.includes('node_modules')) return id.toString().split('node_modules/')[1].split('/')[0].toString();\n}\n...\n```\n\nRegards\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from \"vite\";\nimport reactRefresh from \"@vitejs/plugin-react-refresh\";\nimport { dependencies } from \"./package.json\";\n\n// whenever you get the error: (!) Some chunks are larger than 500kb after minification\n// find the biggest lib in your vendors chunk and add it to bigLibs\nconst bigLibs = [\n  { regExp: /^@material-ui*/, chunkName: \"@material-ui\" },\n  { regExp: /^@aws-amplify*/, chunkName: \"@aws-amplify\" },\n];\n\nfunction getManualChunks(deps: Record<string, string>) {\n  return Object.keys(deps).reduce(\n    (prev, cur) => {\n      let isBigLib = false;\n      for (const l of bigLibs) {\n        if (l.regExp.test(cur)) {\n          isBigLib = true;\n          if (prev[l.chunkName]) {\n            prev[l.chunkName].push(cur);\n          } else {\n            prev[l.chunkName] = [cur];\n          }\n          break;\n        }\n      }\n      if (!isBigLib) prev.vendors.push(cur);\n      return prev;\n    },\n    { vendors: [] } as Record<string, string[]>\n  );\n}\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  build: {\n    rollupOptions: {\n      output: {\n        manualChunks: getManualChunks(dependencies),\n      },\n    },\n  },\n  plugins: [reactRefresh()],\n  resolve: {\n    alias: [\n      {\n        find: \"./runtimeConfig\",\n        replacement: \"./runtimeConfig.browser\",\n      },\n    ],\n  },\n});\n```\n\n```text\n@material-ui.1d552186.js:1 Uncaught TypeError: Cannot read property 'exports' of undefined\n    at @material-ui.1d552186.js:1\n```\n\n```text\nmanualChunks: (id) => {\nif (id.includes(\"node_modules\")) {\n    if (id.includes(\"@aws-amplify\")) {\n        return \"vendor_aws\";\n    } else if (id.includes(\"@material-ui\")) {\n        return \"vendor_mui\";\n    }\n\n    return \"vendor\"; // all other package goes here\n}\n},\n```\n\n```text\n...\nmanualChunks: (id) => {\n    if (id.includes('node_modules')) return id.toString().split('node_modules/')[1].split('/')[0].toString();\n}\n...\n```\n\n========================================\n\nComments:\n- I ended up still having very large chunks but this is because those libs are so big. This is the correct answer to fix the error. Thank you!\n- Newer versions of Vite no longer separate the vendor files by default. Include the splitVendorChunkPlugin to turn this back on.\n- I had to add `if (id.indexOf(\"react\") !== -1) { return; }` for this to work. Not sure why.\n- I added if (id.indexOf(\"node_modules/react/\") !== -1) return;","metadata":{"transformedAt":"2026-08-18T18:33:46.396Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":178,"estimatedTokens":1115}}58{"id":"stack-69626090","source":"stackoverflow","questionId":69626090,"title":"How to watch public directory in Vite project for hot-reload?","tags":["javascript","reactjs","typescript","vite"],"text":"Title: How to watch public directory in Vite project for hot-reload?\nTags: javascript, reactjs, typescript, vite\nSource: Stack Overflow\n\nQuestion:\nI have a react project configured with Vite.\n\nHot reload works great, but I use `react-i18next` for multiple language support and this is my structure:\n\n```\npublic\n -> en\n -> translation.json\n -> ru\n -> translation.json\n```\n\nWhen I change the `translation.json` files, Vite doesn't watch it, and I have to refresh the page to see the changes.\n\nIs there a way to tell Vite to watch all the files in the `public` directory?\n\n========================================\n\nTop Answer:\nI've modified flydev's answer so that it can hot-reload the i18n-dependent components without reloading the whole page. (Currently using in a typescript project)\n\n```\nimport { PluginOption } from \"vite\";\n\nexport default function I18nHotReload(): PluginOption {\n return {\n name: 'i18n-hot-reload',\n handleHotUpdate({ file, server }) {\n if (file.includes('locales') && file.endsWith('.json')) {\n console.log('Locale file updated')\n server.ws.send({\n type: \"custom\",\n event: \"locales-update\",\n });\n }\n },\n }\n}\n```\n\nThen adding it to the vite's plugins:\n\n```\nplugins: [\n ...,\n i18nHotReload(),\n]\n```\n\nAnd then adding the listener anywhere your code can reach (I'm using it in the i18n initial config file)\n\n```\nif (import.meta.hot) {\n import.meta.hot.on('locales-update', () => {\n i18n.reloadResources().then(() => {\n i18n.changeLanguage(i18n.language)\n })\n })\n}\n```\n\n`i18n.reloadResources()` alone doesn't trigger the translations hot reload\n\n========================================\n\nCode:\n```text\npublic\n  -> en\n    -> translation.json\n  -> ru\n    -> translation.json\n```\n\n```text\nreact-i18next\n```\n\n```text\ntranslation.json\n```\n\n```text\npublic\n```\n\n```js\nexport default function CustomHmr() {\n    return {\n      name: 'custom-hmr',\n      enforce: 'post',\n      // HMR\n      handleHotUpdate({ file, server }) {\n        if (file.endsWith('.json')) {\n          console.log('reloading json file...');\n  \n          server.ws.send({\n            type: 'full-reload',          \n            path: '*'\n          });\n        }\n      },\n    }\n}\n```\n\n```text\n{\n  plugins: [\n    CustomHmr()   <---  custom plugin\n  ]\n}\n```\n\n```text\nfull-reload\n```\n\n```text\nupdate\n```\n\n```text\nvite.config.js\n```\n\n```js\nimport { PluginOption } from \"vite\";\n\nexport default function I18nHotReload(): PluginOption {\n  return {\n    name: 'i18n-hot-reload',\n    handleHotUpdate({ file, server }) {\n      if (file.includes('locales') && file.endsWith('.json')) {\n        console.log('Locale file updated')\n        server.ws.send({\n          type: \"custom\",\n          event: \"locales-update\",\n        });\n      }\n    },\n  }\n}\n```\n\n```js\nplugins: [\n    ...,\n    i18nHotReload(),\n]\n```\n\n```js\nif (import.meta.hot) {\n  import.meta.hot.on('locales-update', () => {\n    i18n.reloadResources().then(() => {\n      i18n.changeLanguage(i18n.language)\n    })\n  })\n}\n```\n\n```text\ni18n.reloadResources()\n```\n\n```text\nserver.hot.send({ data: file, event: 'locales-update', type: 'custom' })\n```\n\n```text\nif (import.meta.hot) {\n  import.meta.hot.on('locales-update', (file) => {\n    let index = file.lastIndexOf('/');\n    if (index > -1) index = file.lastIndexOf('/', index - 1);\n    if (index === -1) return;\n\n    const [lng, ns] = file.slice(index + 1).split('/');\n    i18n\n      .reloadResources(lng, ns.replace('.json', ''))\n      .then(() => i18n.changeLanguage(i18n.language));\n  });\n}\n```\n\n```text\n/public/locales/en/namespace.json\n```\n\n```text\nfile\n```\n\n```text\ndata\n```\n\n```text\nserver.ws\n```\n\n```text\nserver.hot\n```\n\n```text\nlocales-update\n```\n\n```text\nreloadResources\n```\n\n```js\n//vite.config.js\n\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\n\n// https://vitejs.dev/config/\nexport default defineConfig(async ({ mode }) => {\n  const devPlugins = [];\n  if (mode === 'development') {\n    const { i18nextHMRPlugin } = await import('i18next-hmr/vite');\n    devPlugins.push(i18nextHMRPlugin({ localesDir: './public/locales' }));\n  }\n  return {\n    plugins: [react()].concat(devPlugins),\n  };\n});\n```\n\n```text\ni18next-hmr\n```\n\n========================================\n\nComments:\n- Tried it, doesn't work. Also I'm using Typescript and the return type of the custom plugin doesn't match to what Vite accepts in the plugins array which is `Plugin`\n- @TwoHorses I updated my answer, you will find a Gituhb repo with full working example.\n- Thanks this works. One question, I notice that when I update a json file, the entire window is reloaded. But when you just change a component content, it only updates that part of the app, without full reload. Is that impossible to achieve?\n- This should be in the official documentation.\n- @TwoHorses, just add `import type { Plugin } from 'vite';` at the top of your typescript file and then type the exported function as a `Plugin` like this: `export default function CustomHmr(): Plugin {}` and it worked for me.\n- much more elegant solution, been searching for this :)\n- This solution is good","metadata":{"transformedAt":"2026-08-18T18:33:46.396Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":251,"estimatedTokens":1261}}59{"id":"stack-71760177","source":"stackoverflow","questionId":71760177,"title":"Styling the body element in svelte","tags":["css","svelte","vite","darkmode"],"text":"Title: Styling the body element in svelte\nTags: css, svelte, vite, darkmode\nSource: Stack Overflow\n\nQuestion:\nMy goal is to make a darkmode for my web app.\nTo get my setup enter `npm init vite` and pick svelte as a framwork. Then the command line instructions. Go to src > App.svelte:\n\nTry the following:\n\n\r\n\r\n\n```\nbody {\n background: black;\n}\n```\n\n\r\n\r\n\r\n\nYou will get the following warning by the svelte extension in vs-code:\n\n```\nUnused CSS selector \"body\"\n```\n\nTo check if this error is related to the browser I manually set the property in chrome dev tools and the expected result was achieved.\n\nBecause of this I have the following questions:\n\n- Why doesn't svelte allow styling of the body in this way?\n\n- How can you style the body tag in svelte?\n\n- How would darkmode be implemented?\n\n========================================\n\nTop Answer:\nYou can achieve what I tried to do by adding a `global.css` file to your project and importing it to your file like this:\n\n\r\n\r\n\n```\n\n import \"./global.css\";\n\n```\n\n\r\n\r\n\r\n\nIf you really want it to be global you can also link it in your index.html in the root of your project like this:\n\n\r\n\r\n\n```\n\n```\n\n========================================\n\nCode:\n```css\nbody {\n    background: black;\n}\n```\n\n```text\nUnused CSS selector \"body\"\n```\n\n```text\nnpm init vite\n```\n\n```text\n:global(body)\n```\n\n```text\nbody\n```\n\n```text\n:global(body)\n```\n\n```text\n:global(body.dark-mode)\n```\n\n```html\n<script>\n  import \"./global.css\";\n</script>\n```\n\n```html\n<link rel=\"stylesheet\" href=\"styles.css\">\n```\n\n```text\nglobal.css\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.396Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":112,"estimatedTokens":388}}60{"id":"stack-70346829","source":"stackoverflow","questionId":70346829,"title":"ESLint Vue multiword components","tags":["vue.js","vue-router","eslint","vuejs3","vite"],"text":"Title: ESLint Vue multiword components\nTags: vue.js, vue-router, eslint, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nIs there a way to stop getting error from ESLint for single word **view** name in Vue3?\n\nEvery time I run ESLint, I get following message:\n\n```\n1:1 error Component name \"About\" should always be multi-word vue/multi-word-component-names\n```\n\nI currently have this setup:\n\nfile structure:\n\n```\n├── index.html\n├── node_modules\n├── npm\n├── package.json\n├── package-lock.json\n├── public\n│   └── favicon.ico\n├── README.md\n├── src\n│   ├── App.vue\n│   ├── assets\n│   │   └── logo.svg\n│   ├── components\n│   │   └── Menu.vue\n│   ├── env.d.ts\n│   ├── main.ts\n│   ├── router\n│   │   └── index.ts\n│   └── views\n│   ├── About.vue\n│   └── Home.vue\n├── tsconfig.json\n└── vite.config.ts\n```\n\n.eslintrc:\n\n```\n{\n \"root\": true,\n \"env\": {\n \"node\": true\n },\n \"extends\": [\n \"plugin:vue/vue3-essential\",\n \"eslint:recommended\",\n \"@vue/typescript/recommended\"\n ],\n \"parserOptions\": {\n \"ecmaVersion\": 2021\n },\n \"rules\": {}\n}\n```\n\npackage.json\n\n```\n{\n...\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vue-tsc --noEmit && vite build\",\n \"preview\": \"vite preview\",\n \"lint\": \"eslint --ext .ts,vue --ignore-path .gitignore .\"\n },\n...\n}\n```\n\n========================================\n\nTop Answer:\nFor those still having this issue, add the following under rules in the `.eslintrc.js` file\n\n```\nrules: {\n ...\n 'vue/multi-word-component-names': 0,\n}\n```\n\n========================================\n\nCode:\n```sh\n1:1  error  Component name \"About\" should always be multi-word  vue/multi-word-component-names\n```\n\n```text\n├── index.html\n├── node_modules\n├── npm\n├── package.json\n├── package-lock.json\n├── public\n│   └── favicon.ico\n├── README.md\n├── src\n│   ├── App.vue\n│   ├── assets\n│   │   └── logo.svg\n│   ├── components\n│   │   └── Menu.vue\n│   ├── env.d.ts\n│   ├── main.ts\n│   ├── router\n│   │   └── index.ts\n│   └── views\n│       ├── About.vue\n│       └── Home.vue\n├── tsconfig.json\n└── vite.config.ts\n```\n\n```json\n{\n    \"root\": true,\n    \"env\": {\n        \"node\": true\n    },\n    \"extends\": [\n        \"plugin:vue/vue3-essential\",\n        \"eslint:recommended\",\n        \"@vue/typescript/recommended\"\n    ],\n    \"parserOptions\": {\n        \"ecmaVersion\": 2021\n    },\n    \"rules\": {}\n}\n```\n\n```json\n{\n...\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vue-tsc --noEmit && vite build\",\n    \"preview\": \"vite preview\",\n    \"lint\": \"eslint --ext .ts,vue --ignore-path .gitignore .\"\n  },\n...\n}\n```\n\n```js\n// <projectRoot>/.eslintrc.js\nmodule.exports = {\n  ⋮\n  rules: {\n    'vue/multi-word-component-names': 0,\n  },\n}\n```\n\n```js\n// <projectRoot>/.eslintrc.js\nmodule.exports = {\n  ⋮\n  overrides: [\n    {\n      files: ['src/views/**/*.vue'],\n      rules: {\n        'vue/multi-word-component-names': 0,\n      },\n    },\n  ],\n}\n```\n\n```js\n// <projectRoot>/src/views/.eslintrc.js\nmodule.exports = {\n  rules: {\n    'vue/multi-word-component-names': 0,\n  },\n}\n```\n\n```text\nsrc/components\n```\n\n```text\noverrides\n```\n\n```text\nsrc/views/\n```\n\n```text\nsrc/views/**/*.vue\n```\n\n```text\noverrides\n```\n\n```text\n>ESLint: Restart ESLint Server\n```\n\n```text\nsrc/views/\n```\n\n```text\nsrc/views/**/*.vue\n```\n\n```text\n.eslintrc.js\n```\n\n```text\nrules: {\n  ...\n  'vue/multi-word-component-names': 0,\n}\n```\n\n```text\n.eslintrc.js\n```\n\n```text\nvue.config.js\n```\n\n```text\n<!-- in pre-compiled templates -->\n<Item />\n\n<!-- in in-DOM templates -->\n<item></item>\n```\n\n```text\n<!-- in pre-compiled templates -->\n<TodoItem />\n\n<!-- in in-DOM templates -->\n<todo-item></todo-item>\n```\n\n```text\nAbout\n```\n\n```text\nAboutView\n```\n\n```text\nnpm remove @vue/cli-plugin-eslint\n```\n\n```text\n{\n  rules: {\n   'vue/multi-word-component-names': 'off'\n  }\n```\n\n```js\nimport globals from 'globals';\nimport pluginJs from '@eslint/js';\nimport tseslint from 'typescript-eslint';\nimport pluginVue from 'eslint-plugin-vue';\n\nexport default [\n {files: ['**/*.{js,mjs,cjs,ts,vue}']},\n {languageOptions: {globals: globals.browser}},\n pluginJs.configs.recommended,\n ...tseslint.configs.recommended,\n ...pluginVue.configs['flat/essential'],\n {files: ['**/*.vue'], languageOptions: {parserOptions: {parser: tseslint.parser}}},\n {\n  ignores: [\"dist/*\", \"public/*\"]\n },\n {\n  rules: {\n   'vue/multi-word-component-names': 'off'\n  }\n }\n];\n```\n\n========================================\n\nComments:\n- Add the configuration you want into the `.eslintrc`? There's extensive guidance in the docs: eslint.org/docs/user-guide/configuring. But the Vue style guide describes that one as \"essential\": vuejs.org/v2/style-guide/#Multi-word-component-names-essenti&zwnj;&#8203;al, which is why it's in that preset.\n- @jonrsharpe That was my initial idea, but as you say in \"Components\" it is essential. But from my understanding this does not include views as even vue-cli generates them with single-word names as you do not use them as tags in your code...\n- @Tomkys The only Component that is (should be) one word is App.vue - with the new update the generated components are also Multi-Word i bleieve\n- my eslint config rules were listed under `package.json`, and I had to *restart* VS Code for the change to take effect","metadata":{"transformedAt":"2026-08-18T18:33:46.396Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":305,"estimatedTokens":1279}}61{"id":"stack-76074040","source":"stackoverflow","questionId":76074040,"title":"Vite Server is running on 127.0.0.1 by default instead of localhost","tags":["localhost","vite"],"text":"Title: Vite Server is running on 127.0.0.1 by default instead of localhost\nTags: localhost, vite\nSource: Stack Overflow\n\nQuestion:\nWhenever i run `npm run dev`, i get vite running on domain 127.0.0.1 by default.\n\n**How to make vite run on localhost instead?**\n\nTheses are my configs:\n\n**package.json:**\n\n```\n\"scripts\": {\n \"dev\": \"vite --host=localhost\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\"\n },\n```\n\n**vite.config.js:**\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n server: {\n host: 'localhost',\n port: 3000\n }\n})\n```\n\nhttps://i.sstatic.net/ETSJ2.png\n\n========================================\n\nTop Answer:\nAn **other alternative** solution that works:\n\n**package.json:**\n\n```\n\"scripts\": {\n \"dev\": \"vite --host\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\"\n },\n```\n\n**vite.config.js:**\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n server: {\n host: 'localhost',\n port: 3000\n }\n})\n```\n\nresult:\n\nhttps://i.sstatic.net/mRic0.png\n\nread more\n\n========================================\n\nCode:\n```text\n\"scripts\": {\n    \"dev\": \"vite --host=localhost\",\n    \"build\": \"vite build\",\n    \"preview\": \"vite preview\"\n  },\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  server: {\n    host: 'localhost',\n    port: 3000\n  }\n})\n```\n\n```text\nnpm run dev\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport dns from 'dns'\nimport react from '@vitejs/plugin-react-swc'\n\ndns.setDefaultResultOrder('verbatim')\n\nexport default defineConfig({\n  plugins: [react()],\n  server: {\n    host: 'localhost',\n    port: 3000\n  }\n})\n```\n\n```text\ndns.setDefaultResultOrder('verbatim')\n```\n\n```json\n\"scripts\": {\n    \"dev\": \"vite --host\",\n    \"build\": \"vite build\",\n    \"preview\": \"vite preview\"\n  },\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  server: {\n    host: 'localhost',\n    port: 3000\n  }\n})\n```\n\n```text\nProperty 'setDefaultResultOrder' does not exist on type 'typeof import(\"dns\")'\n```\n\n```text\ndns.setDefaultResultOrder('verbatim')\n```\n\n```text\n@types/node\n```\n\n```text\nport: 'localhost'\n```\n\n```text\nsetDefaultResultOrder\n```\n\n```text\nmkdir react_dev; cd react_dev/\nnpm create vite@latest my-react-app -- --template react\ncd my-react-app/\nnpm install\n```\n\n```text\n$ npm run dev -- --host\n```\n\n```text\n0.0.0.0:5173\n```\n\n```text\nnpx vite --host [HOST] --port [PORT]\n```\n\n========================================\n\nComments:\n- Is there a way to prevent it from listening on the other network interfaces as well?\n- To be clear this solution only change `\"dev\": \"vite --host\",` inside `package.json` file.","metadata":{"transformedAt":"2026-08-18T18:33:46.396Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":191,"estimatedTokens":751}}62{"id":"stack-70086712","source":"stackoverflow","questionId":70086712,"title":"Load local fonts in vite vue3 project","tags":["css","vue.js","vuejs3","vite"],"text":"Title: Load local fonts in vite vue3 project\nTags: css, vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nIn `main.scss` I load local fonts from `assets/styles/fonts` folder:\n\n```\n@font-face {\n font-family: 'Opensans-Bold';\n font-style: normal;\n src: local('Opensans-Bold'), url(./fonts/OpenSans-Bold.ttf) format('truetype');\n}\n@font-face {\n font-family: 'Opensans-Light';\n font-style: normal;\n src: local('Opensans-Light'), url(./fonts/OpenSans-Light.ttf) format('truetype');\n}\n```\n\nthen in `vite.config` I load `main.scss`:\n\n```\ncss: {\n preprocessorOptions: {\n scss: {\n additionalData: `@import \"@/assets/styles/main.scss\";`\n }\n }\n},\n```\n\nbut all css from `main.scss` is applied except fonts, I get error:\n\n```\ndownloadable font: download failed (font-family: \"Opensans-Bold\" style:normal weight:400 stretch:100 src index:1): status=2152398850 source: http://localhost:3000/fonts/OpenSans-Bold.ttf\n```\n\nAm I on right track or I need some other approach (similar works with Vue-CLI)?\n\n========================================\n\nTop Answer:\nI was able to make this work by simply put the fonts on a public folder on root.\n\nlike:\n\n```\npublic/.**.ttf\nsrc/\n```\n\n========================================\n\nCode:\n```text\n@font-face {\n  font-family: 'Opensans-Bold';\n  font-style: normal;\n  src: local('Opensans-Bold'), url(./fonts/OpenSans-Bold.ttf) format('truetype');\n}\n@font-face {\n  font-family: 'Opensans-Light';\n  font-style: normal;\n  src: local('Opensans-Light'), url(./fonts/OpenSans-Light.ttf) format('truetype');\n}\n```\n\n```text\ncss: {\n  preprocessorOptions: {\n    scss: {\n      additionalData: `@import \"@/assets/styles/main.scss\";`\n    }\n  }\n},\n```\n\n```text\ndownloadable font: download failed (font-family: \"Opensans-Bold\" style:normal weight:400 stretch:100 src index:1): status=2152398850 source: http://localhost:3000/fonts/OpenSans-Bold.ttf\n```\n\n```text\nmain.scss\n```\n\n```text\nassets/styles/fonts\n```\n\n```text\nvite.config\n```\n\n```text\nmain.scss\n```\n\n```text\nmain.scss\n```\n\n```text\nsrc: local('Opensans-Bold'), url(@/assets/styles/fonts/OpenSans-Bold.ttf) format('truetype');\n```\n\n```text\nresolve: {\n  alias: {\n    '@': path.resolve(__dirname, 'src'),\n  }\n}\n```\n\n```text\nvite.config.js\n```\n\n```text\npublic/.**.ttf\nsrc/\n```\n\n========================================\n\nComments:\n- I have the same issue. The path seems nothing to do with it. In both cases - `@&#47;assets`, `..&#47;assets` - fonts do not load randomly when I refresh the page. But on production, everything seems fine. I believe this issue is related to the Vite dev server.\n- Did you configure an alias for this?\n- hmm, how does the @ work then? I wonder if it's set by default. I have a similar problem and haven't managed to make iit work on react.\n- @Juan De la Cruz ahhhh sorry mate my bad, I updated my answer take a look pls\n- mmm, I though I had done a config similar and it didn't work, but yours actually did. Anyways, it's weird that the relative path doesn't work and that we have to resort to aliases.\n- That alias fixed everything! Relative or absolute, in resources/ or in in public/fonts, Vite wouldn't process the URLs &#175;_(ツ)_/&#175;\n- Thanks for this. I did not know Vite does not resolve relative paths, and that paths need to be absolute.\n- this is the only think that work for me thanks","metadata":{"transformedAt":"2026-08-18T18:33:46.396Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":134,"estimatedTokens":822}}63{"id":"stack-70547375","source":"stackoverflow","questionId":70547375,"title":"Global Sass Import & Usage - Nuxt 3 Static Assets","tags":["vue.js","nuxt.js","vuejs3","vite","nuxt3.js"],"text":"Title: Global Sass Import & Usage - Nuxt 3 Static Assets\nTags: vue.js, nuxt.js, vuejs3, vite, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to import a global Sass stylesheet from the `/assets` directory and use stuff like variables and mixins defined there throughout the components. My `nuxt.config.ts` looks like this currently:\n\n```\nimport { defineNuxtConfig } from \"nuxt3\";\n\nexport default defineNuxtConfig({\n css: [\"@/assets/styles/main.sass\"],\n styleResources: {\n sass: [\"@/assets/styles/main.sass\"],\n },\n build: {\n extractCSS: true,\n styleResources: {\n sass: \"@/assets/styles/main.sass\",\n hoistUseStatements: true,\n },\n },\n // buildModules: [\"@nuxtjs/style-resources\"], // This throws error\n vite: {\n css: {\n loaderOptions: {\n sass: {\n additionalData: ` @import \"@/assets/styles/main.sass\"; `,\n },\n },\n },\n },\n});\n```\n\nWhen I try to use a variable now, I get `[plugin:vite:css] Undefined variable.` error. This used to work very well in Nuxt 2 with `@nuxtjs/style-resources` but I'm not sure how to make this work in Nuxt 3.\n\nHowever, classes and applied styles from that stylesheet are working, only varibles, mixins and maps are not accessible.\n\nCan someone please help?\n\n========================================\n\nTop Answer:\nI'm using Nuxt 3 with TS setup and today is February 16, 2023 in the US. After trying many different variations, it would not work for me without the semi-colon at end of _variables.scss although I do agree with Juan, that first line of import { defineNuxtConfig } from nuxt3 is not needed.\n\n```\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n app: {\n head: {\n htmlAttrs: { lang: \"en\" },\n },\n },\n css: [\"@/assets/styles/main.scss\"],\n vite: {\n css: {\n preprocessorOptions: {\n scss: {\n additionalData: '@import \"@/assets/styles/_variables.scss\";',\n },\n },\n },\n },\n});\n```\n\nImage of my IDE and terminal messages\n\n========================================\n\nCode:\n```js\nimport { defineNuxtConfig } from \"nuxt3\";\n\nexport default defineNuxtConfig({\n    css: [\"@/assets/styles/main.sass\"],\n    styleResources: {\n        sass: [\"@/assets/styles/main.sass\"],\n    },\n    build: {\n        extractCSS: true,\n        styleResources: {\n            sass: \"@/assets/styles/main.sass\",\n            hoistUseStatements: true,\n        },\n    },\n    // buildModules: [\"@nuxtjs/style-resources\"], // This throws error\n    vite: {\n        css: {\n            loaderOptions: {\n                sass: {\n                    additionalData: ` @import \"@/assets/styles/main.sass\"; `,\n                },\n            },\n        },\n    },\n});\n```\n\n```text\n/assets\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\n[plugin:vite:css] Undefined variable.\n```\n\n```text\n@nuxtjs/style-resources\n```\n\n```js\nimport { defineNuxtConfig } from \"nuxt3\";\n\nexport default defineNuxtConfig({\n    css: [\"@/assets/styles/main.sass\"],\n    vite: {\n        css: {\n            preprocessorOptions: {\n                sass: {\n                    additionalData: '@import \"@/assets/styles/_variables.sass\"',\n                },\n            },\n        },\n    },\n});\n```\n\n```text\nmain.sass\n```\n\n```text\n_variables.sass\n```\n\n```text\n_variables.sass\n```\n\n```text\n// nuxt.config.ts\nexport default {\n  css: ['@/static/assets/scss/base.scss'],\n  vite: {\n    css: {\n      preprocessorOptions: {\n        scss: {\n          additionalData: '@import \"@/assets/style/global.sass\";'\n        }\n      }\n    }\n  }\n};\n```\n\n```text\ndefineNuxtConfig\n```\n\n```text\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n  app: {\n    head: {\n      htmlAttrs: { lang: \"en\" },\n    },\n  },\n  css: [\"@/assets/styles/main.scss\"],\n  vite: {\n    css: {\n      preprocessorOptions: {\n        scss: {\n          additionalData: '@import \"@/assets/styles/_variables.scss\";',\n        },\n      },\n    },\n  },\n});\n```\n\n========================================\n\nComments:\n- As per the Docs, Nuxt loads preprocessor automatically. you might need to add the preprocessor.\n- I have `sass` and `sass-loader` installed in `package.json` and I'm using `` tag as well in the components. Still not working for some reason.\n- codesandbox.io/s/confident-saha-w4cpj\n- I'm not sure if I was able to set this up correctly, but let's try this. I think this is pretty the structure I've been working on.\n- In `app.vue`, we can try setting the `div` background to `$test` variable defined in the `main.sass`\n- This worked for me, but the problem is that I've just one Sass entry file (index.scss) wich is importing all the stuf (settings, utilities...) and it is not possible to add it in \"css\" and \"additionalData\" imports at the same time. I solved it adding an empty file called index.scss, importing it like so (css: [\"@/assets/styles/index.scss\"]), renaiming the file with all the imports to scssImports.scss and importing it like this (additionalData: '@import \"@/assets/styles/scssImports.scss\";'). There is any way to directly add the imports in the index.scss and get rid of the scssImports.scss?\n- The only difference between my answer and @bacon-delight 's answer is the semi-colon at the end of additionalData: '@import \"@/assets/styles/_variables.scss\";',\n- You can edit your answer, and It won't work without semicolon?\n- Compare your answer to the second answer written by Juan. He has semicolon too.\n- Thanks for bringing that to my attention @Mises. I missed that.","metadata":{"transformedAt":"2026-08-18T18:33:46.396Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":199,"estimatedTokens":1345}}64{"id":"stack-74312482","source":"stackoverflow","questionId":74312482,"title":"Getting \"404 not found\" when refreshing a page that has a nested route, because Vite doesn't redirect all routes to index.html","tags":["reactjs","react-router","vite"],"text":"Title: Getting \"404 not found\" when refreshing a page that has a nested route, because Vite doesn't redirect all routes to index.html\nTags: reactjs, react-router, vite\nSource: Stack Overflow\n\nQuestion:\nI can use React router's `useNavigate` hook to go to a nested route like `localhost:3000/nested/route`, but as soon as a reload, I get a 404 not found error, because it's trying to find `localhost:3000/nested/route/index.html` for some reason.\n\nHow can I configure Vite in dev as a SPA with client side routing so that all requests are redirected to the root index.html?\n\n========================================\n\nTop Answer:\nMake sure the script tag in your `index.html` has the full path (including `./`) to the entry point:\n\nFor example, this doesn't work (404 on page reload):\n\n``\n\nbut this DOES work:\n\n``\n\n========================================\n\nCode:\n```text\nuseNavigate\n```\n\n```text\nlocalhost:3000/nested/route\n```\n\n```text\nlocalhost:3000/nested/route/index.html\n```\n\n```text\n<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"icon\" href=\"/favicon.png\" />\n    <meta name=\"viewport\" content=\"minimum-scale=1, initial-scale=1, width=device-width\" />\n    <meta name=\"description\" content=\"My App\" />\n    <title>My App</title>\n    <base href=\"/\" />\n  </head>\n\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <script type=\"module\" src=\"src/index.tsx\"></script>\n    <div id=\"root\"></div>\n  </body>\n</html>\n```\n\n```text\nbase\n```\n\n```text\nindex.html\n```\n\n```js\nconst context =  [\n  ...\n  \"/api/my_controller_name\",\n  ...\n];\n```\n\n```text\n[Route(\"api/my_controller_name\")]\n```\n\n```text\nindex.html\n```\n\n```text\n./\n```\n\n```text\n<script type='module' src='src/App.jsx'></script>\n```\n\n```text\n<script type='module' src='./src/App.jsx'></script>\n```\n\n========================================\n\nComments:\n- Can I ask how you got to this solution? Not only is this not documented anywhere, but from everything I found, Vite already by default should work in `spa` mode, with base set to `&#47;`. I'm running into the same problem and I'm just having a hard time understanding why Vite acts like it's set up for a `mpa`. Edit: just to clarify, this seems to work, but I'm having some side-effects that might or might not be related to this & I'm feeling a little uneasy accepting this as the right way to solve this issue :/\n- This worked for me. I'm migrating from CRA to vite. After publishing app seemed to work fine, until user reloaded / refreshed page on a sub route (/products/1) and was met by blank page. Difference from original question. I never got 404 'Not Found' errors. Just standard ok httpstatus codes.","metadata":{"transformedAt":"2026-08-18T18:33:46.396Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":98,"estimatedTokens":671}}65{"id":"stack-75375772","source":"stackoverflow","questionId":75375772,"title":"Routes not working properly in React using Vite (ON BUILD)","tags":["reactjs","react-router-dom","vite","netlify"],"text":"Title: Routes not working properly in React using Vite (ON BUILD)\nTags: reactjs, react-router-dom, vite, netlify\nSource: Stack Overflow\n\nQuestion:\nOn my website, I have a few routes that are made using React-Router, that point to a few different pages on the website itself. It all works fine in Development mode, but the build version is where the problems occur. When I upload my webiste to Netlify to test it, the index page (*path=\"/\"*) works fine, but other pages (say for example the about page (*path=\"/about\"*)) throw a 404 error when I refresh them. I have also tried using a different hosting provider but on some it didn't even load the index page, or it did, but not the other pages.\n\nUpon some further research and reading through the Vite documentation, I found that the problem might be that I don't configure Vite, to check for the routes, but I don't know how to do that (or at least properly).\n\nI should also mention that I am quite new to React, so I am sorry if the question is not well put.\n\nHere is the code for the router in the app.js file:\n\n```\nfunction App() {\n return (\n <>\n }>\n \n \n \n } />\n } />\n } />\n } />\n } />\n } />\n } />\n \n \n \n \n \n )\n}\n```\n\nI have tried with re-ordering the router, but that didn't seem to change anything...\n\n========================================\n\nTop Answer:\nI was also having the same issues in my app while deploying on vercel.\nIt doesn't matter where you are deploying this actually.\nIf you have a Link tag that you are using from whatever library, make sure to point it to the NavLink provided by react-router-dom using the as prop. And also use the property `to` instead of `href`.\n\nMake this change everywhere you have a Link Tag and you will be all good.\n\n```\nLOGIN\n```\n\n========================================\n\nCode:\n```text\nfunction App() {\n  return (\n    <>\n      <Suspense fallback={<RhombLoad />}>\n        <Router>\n          <Header />\n          <Routes>\n            <Route path=\"/\" element={<Home />} />\n            <Route path=\"/storitve\" element={<Storitve />} />\n            <Route path=\"/onas\" element={<Onas />} />\n            <Route path=\"/reference\" element={<Reference />} />\n            <Route path=\"/zaposlovanje\" element={<Zaposlovanje />} />\n            <Route path=\"/kontakt\" element={<Kontakt />} />\n            <Route path=\"*\" element={<ErrorPage />} />\n          </Routes>\n          <Footer />\n        </Router>\n      </Suspense>\n    </>\n  )\n}\n```\n\n```text\n_redirects\n```\n\n```text\ndist\n```\n\n```text\n_redirects\n```\n\n```text\n/* /index.html 200\n```\n\n```text\n<Link as={NavLink} to=\"/login\">LOGIN</Link>\n```\n\n```text\nto\n```\n\n```text\nhref\n```\n\n```text\n{\n\"rewrites\": [\n    {\n        \"source\": \"/(.*)\",\n        \"destination\": \"/\"\n    }\n  ]\n}\n```\n\n```text\n<base href=\"/\" />\n```\n\n```text\n{\n  \"navigationFallback\": {\n    \"rewrite\": \"/index.html\",\n    \"exclude\": [\"/assets/*\", \"/*.css\", \"/*.js\", \"/*.png\", \"/*.jpg\", \"/*.svg\"]\n  }\n}\n```\n\n```text\nindex.html\n```\n\n```text\nstaticwebapp.config.json\n```\n\n```text\n/index.html\n```\n\n========================================\n\nComments:\n- Check the CRA deployment docs specific to Netlify.\n- You need to configure Netlify to know that your other routes exist\n- Yes! That was it, I did this then and it worked, additionally, I have also changed the React-Dom's BrowserRouter to HashRouter because upon testing on different hosting providers with a friend this solved additional issues where some of those (hosting providers) weren't able to properly load pages on refresh. Thank you for your answer!","metadata":{"transformedAt":"2026-08-18T18:33:46.396Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":149,"estimatedTokens":878}}66{"id":"stack-76752732","source":"stackoverflow","questionId":76752732,"title":"error while deploying nuxt 3 in pre-rendered mode","tags":["vue.js","vite","nuxt3.js"],"text":"Title: error while deploying nuxt 3 in pre-rendered mode\nTags: vue.js, vite, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nHi I'm trying to build my nuxt 3 app in pre-rendered mode (SSG mode), and I have add these configs in my `nuxt.config.ts` file\n\n```\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n devtools: { enabled: true },\n\n runtimeConfig: {\n public: {\n WEBSITE_NAME_EN: process.env.WEBSITE_NAME_EN,\n WEBSITE_ADDRESS: process.env.WEBSITE_ADDRESS,\n API_BASE_URL: process.env.API_BASE_URL,\n },\n },\n\n ssr: true,\n nitro: {\n baseURL: \"http://localhost:8000\",\n prerender: {\n crawlLinks: true,\n },\n },\n routeRules: {\n \"/**\": { swr: true },\n \"/dashboard/**\": { ssr: false },\n },\n});\n```\n\nand my `package.json` file content\n\n```\n{\n \"name\": \"nuxt-app\",\n \"private\": true,\n \"scripts\": {\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev\",\n \"generate\": \"nuxt generate\",\n \"preview\": \"nuxt preview\",\n \"postinstall\": \"nuxt prepare\"\n },\n \"devDependencies\": {\n \"@ckeditor/ckeditor5-vue\": \"^5.1.0\",\n \"@fortawesome/fontawesome-free\": \"^6.4.0\",\n \"@nuxt/devtools\": \"latest\",\n \"@nuxtjs/tailwindcss\": \"^6.8.0\",\n \"@pinia/nuxt\": \"^0.4.11\",\n \"@types/node\": \"^18.16.19\",\n \"@vee-validate/rules\": \"^4.10.8\",\n \"@vime/core\": \"^5.4.1\",\n \"@vime/vue-next\": \"^5.4.1\",\n \"@vueuse/nuxt\": \"^10.2.1\",\n \"axios\": \"^1.4.0\",\n \"nuxt\": \"^3.6.5\",\n \"pinia\": \"^2.1.4\",\n \"sass\": \"^1.64.1\",\n \"sass-loader\": \"^13.3.2\",\n \"swiper\": \"^10.0.4\",\n \"v-lazy-image\": \"^2.1.1\",\n \"vee-validate\": \"^4.10.8\",\n \"vue-toastification\": \"^2.0.0-rc.5\"\n }\n}\n```\n\nbut when I run `yarn build` command it produces these errors\n\n```\nℹ ✓ built in 7.26s 11:57:59 AM\n✔ Server built in 7284ms 11:57:59 AM\n✔ Generated public .output/public nitro 11:57:59 AM\nℹ Initializing prerenderer nitro 11:57:59 AM\nℹ Prerendering 1 initial routes with crawler nitro 11:58:06 AM\n ├─ / (144ms) (Error: [404] Page not found: /http://localhost:8000) nitro 11:58:07 AM\n nitro 11:58:07 AM\nErrors prerendering:\n ├─ / (404) nitro 11:58:07 AM\n nitro 11:58:07 AM\n\n ERROR Exiting due to prerender errors. 11:58:07 AM\n\n at prerender (/E:/Workspace/personal-website-frontend-v2/node_modules/nitropack/dist/shared/nitro.1db3349c.mjs:189:11)\n at runMicrotasks ()\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\n at async /E:/Workspace/personal-website-frontend-v2/node_modules/nuxt/dist/index.mjs:2641:7\n at async build (/E:/Workspace/personal-website-frontend-v2/node_modules/nuxt/dist/index.mjs:3794:5)\n at async Object.invoke (/E:/Workspace/personal-website-frontend-v2/node_modules/nuxi/dist/chunks/build.mjs:59:5)\n at async _main (/E:/Workspace/personal-website-frontend-v2/node_modules/nuxi/dist/cli.mjs:49:20)\n\nerror Command failed with exit code 1.\ninfo Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.\n```\n\nI have a 404 page at this address `/pages/404.vue` but it still gives me this error, so what is the problem and how can I fix it?\n\nI couldn't find any answer, and the problem seems so weird to me\n\nEDIT: I even made a new project and I add `nuxt.config.ts` content to that but still, the same error exist\n\n========================================\n\nTop Answer:\nI've added `failOnError: false` to `prerender` object in `nuxt.config.ts` file and the build was successful but the error still exists and I couldn't find any answer for it.\n\nNow my `nuxt.config.ts` content are like this:\n\n```\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n devtools: { enabled: true },\n\n runtimeConfig: {\n public: {\n WEBSITE_NAME_EN: process.env.WEBSITE_NAME_EN,\n WEBSITE_ADDRESS: process.env.WEBSITE_ADDRESS,\n API_BASE_URL: process.env.API_BASE_URL,\n },\n },\n\n ssr: true,\n nitro: {\n baseURL: \"http://localhost:8000\",\n prerender: {\n crawlLinks: true,\n failOnError: false, \n },\n },\n routeRules: {\n \"/**\": { swr: true },\n \"/dashboard/**\": { ssr: false },\n },\n});\n```\n\n========================================\n\nCode:\n```js\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n  devtools: { enabled: true },\n\n  runtimeConfig: {\n    public: {\n      WEBSITE_NAME_EN: process.env.WEBSITE_NAME_EN,\n      WEBSITE_ADDRESS: process.env.WEBSITE_ADDRESS,\n      API_BASE_URL: process.env.API_BASE_URL,\n    },\n  },\n\n  ssr: true,\n  nitro: {\n    baseURL: \"http://localhost:8000\",\n    prerender: {\n      crawlLinks: true,\n    },\n  },\n  routeRules: {\n    \"/**\": { swr: true },\n    \"/dashboard/**\": { ssr: false },\n  },\n});\n```\n\n```js\n{\n  \"name\": \"nuxt-app\",\n  \"private\": true,\n  \"scripts\": {\n    \"build\": \"nuxt build\",\n    \"dev\": \"nuxt dev\",\n    \"generate\": \"nuxt generate\",\n    \"preview\": \"nuxt preview\",\n    \"postinstall\": \"nuxt prepare\"\n  },\n  \"devDependencies\": {\n    \"@ckeditor/ckeditor5-vue\": \"^5.1.0\",\n    \"@fortawesome/fontawesome-free\": \"^6.4.0\",\n    \"@nuxt/devtools\": \"latest\",\n    \"@nuxtjs/tailwindcss\": \"^6.8.0\",\n    \"@pinia/nuxt\": \"^0.4.11\",\n    \"@types/node\": \"^18.16.19\",\n    \"@vee-validate/rules\": \"^4.10.8\",\n    \"@vime/core\": \"^5.4.1\",\n    \"@vime/vue-next\": \"^5.4.1\",\n    \"@vueuse/nuxt\": \"^10.2.1\",\n    \"axios\": \"^1.4.0\",\n    \"nuxt\": \"^3.6.5\",\n    \"pinia\": \"^2.1.4\",\n    \"sass\": \"^1.64.1\",\n    \"sass-loader\": \"^13.3.2\",\n    \"swiper\": \"^10.0.4\",\n    \"v-lazy-image\": \"^2.1.1\",\n    \"vee-validate\": \"^4.10.8\",\n    \"vue-toastification\": \"^2.0.0-rc.5\"\n  }\n}\n```\n\n```js\nℹ ✓ built in 7.26s                                                                                                                                                                                                            11:57:59 AM\n✔ Server built in 7284ms                                                                                                                                                                                                      11:57:59 AM\n✔ Generated public .output/public                                                                                                                                                                                       nitro 11:57:59 AM\nℹ Initializing prerenderer                                                                                                                                                                                              nitro 11:57:59 AM\nℹ Prerendering 1 initial routes with crawler                                                                                                                                                                            nitro 11:58:06 AM\n  ├─ / (144ms) (Error: [404] Page not found: /http://localhost:8000)                                                                                                                                                     nitro 11:58:07 AM\n                                                                                                                                                                                                                         nitro 11:58:07 AM\nErrors prerendering:\n  ├─ / (404)                                                                                                                                                                                                             nitro 11:58:07 AM\n                                                                                                                                                                                                                         nitro 11:58:07 AM\n\n ERROR  Exiting due to prerender errors.                                                                                                                                                                                       11:58:07 AM\n\n  at prerender (/E:/Workspace/personal-website-frontend-v2/node_modules/nitropack/dist/shared/nitro.1db3349c.mjs:189:11)\n  at runMicrotasks (<anonymous>)\n  at processTicksAndRejections (node:internal/process/task_queues:96:5)\n  at async /E:/Workspace/personal-website-frontend-v2/node_modules/nuxt/dist/index.mjs:2641:7\n  at async build (/E:/Workspace/personal-website-frontend-v2/node_modules/nuxt/dist/index.mjs:3794:5)\n  at async Object.invoke (/E:/Workspace/personal-website-frontend-v2/node_modules/nuxi/dist/chunks/build.mjs:59:5)\n  at async _main (/E:/Workspace/personal-website-frontend-v2/node_modules/nuxi/dist/cli.mjs:49:20)\n\nerror Command failed with exit code 1.\ninfo Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\npackage.json\n```\n\n```text\nyarn build\n```\n\n```text\n/pages/404.vue\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nfront-end\n```\n\n```text\nback-end\n```\n\n```text\nthrottle\n```\n\n```text\n404 and 429\n```\n\n```text\nthrottle\n```\n\n```text\nthrottle\n```\n\n```text\nthrottle\n```\n\n```js\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n  devtools: { enabled: true },\n\n  runtimeConfig: {\n    public: {\n      WEBSITE_NAME_EN: process.env.WEBSITE_NAME_EN,\n      WEBSITE_ADDRESS: process.env.WEBSITE_ADDRESS,\n      API_BASE_URL: process.env.API_BASE_URL,\n    },\n  },\n\n  ssr: true,\n  nitro: {\n    baseURL: \"http://localhost:8000\",\n    prerender: {\n      crawlLinks: true,\n      failOnError: false, \n    },\n  },\n  routeRules: {\n    \"/**\": { swr: true },\n    \"/dashboard/**\": { ssr: false },\n  },\n});\n```\n\n```text\nfailOnError: false\n```\n\n```text\nprerender\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nnuxt.config.ts\n```\n\n========================================\n\nComments:\n- Same problem happening to me...\n- @massimoi Please check the marked answer with the green tick, it might can solve your problem\n- how did setting throttle on a laravel based backend solve the building process of a nuxt spa frontend?\n- In SSG mode Nuxt tries to send requests for fetching all the routes content, e.g. imagine we have 200 routes that need to be fetched from API, so in SSG mode when all requests are sent, the `throttle` will throw an error, and not gonna let Nuxt to fetch all routes content, so build is gonna fail like this\n- Actually, it doesn't matter is SSG or SSR mode when you send a lot of requests synchronously `throttle` will stop you from doing that and the build is gonna fail\n- maybe a bit late to the party, but nuxt has a concurrency limit that you can set while it generates the pages. This helped me in a similar situation to not get rate limited during the build. The downside is that it can increase the build time. More info here: github.com/nuxt/nuxt/issues/15543#issuecomment-1840508045","metadata":{"transformedAt":"2026-08-18T18:33:46.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":332,"estimatedTokens":2623}}67{"id":"stack-70728985","source":"stackoverflow","questionId":70728985,"title":"vite does not build tailwind css","tags":["html","css","tailwind-css","vite"],"text":"Title: vite does not build tailwind css\nTags: html, css, tailwind-css, vite\nSource: Stack Overflow\n\nQuestion:\nI installed tailwind and other tools using `npm install -D tailwindcss postcss autoprefixer vite`\n\nI created tailwind and postcss config files using `npx tailwindcss init -p`\n\n`tailwind.config.js` contains:\n\n```\nmodule.exports = {\n content: [],\n theme: {\n extend: {},\n },\n plugins: [],\n}\n```\n\n`postcss.config.js` contains:\n\n```\nmodule.exports = {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n}\n```\n\nMy CSS file exits in css\\tailwind.css and contains:\n\n```\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\nThe CSS file is linked to my HTMl page using ``\n\nWhen I run vite, my app starts without build errors but tailwind output is not generated.\n\n========================================\n\nTop Answer:\nThis works for me. Once you've done what Tailwindcss says in its docs, in your `vite.config.js` (I tried this on JavaScript file. I am not sure if this works on TypeScript in the same way) import tailwindcss:\n\n```\nimport tailwindcss from 'tailwindcss'\n```\n\nThen add tailwindcss as a PostCSS plugin like this:\n\n```\ncss: {\n postcss: {\n plugins: [tailwindcss],\n },\n}\n```\n\nOnce you've done that your `vite.config.js` will look like this:\n\n```\n/*Other imports*/\nimport tailwindcss from 'tailwindcss'\n\nexport default defineConfig({\n plugins: [],\n resolve: {\n /*something*/\n },\n css: {\n postcss: {\n plugins: [tailwindcss],\n },\n },\n});\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n  content: [],\n  theme: {\n    extend: {},\n  },\n  plugins: [],\n}\n```\n\n```text\nmodule.exports = {\n  plugins: {\n    tailwindcss: {},\n    autoprefixer: {},\n  },\n}\n```\n\n```text\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n```text\nnpm install -D tailwindcss postcss autoprefixer vite\n```\n\n```text\nnpx tailwindcss init -p\n```\n\n```text\ntailwind.config.js\n```\n\n```text\npostcss.config.js\n```\n\n```text\n<link href=\"/css/tailwind.css\" rel=\"stylesheet\" >\n```\n\n```js\nmodule.exports = {\n  content: [\n    \"./index.html\",\n    \"./src/**/*.{js,ts,jsx,tsx}\",\n  ],\n  theme: {\n    extend: {},\n  },\n  plugins: [],\n}\n```\n\n```html\n// Open terminal\nnpm run dev\n```\n\n```html\n<h1 class=\"text-3xl text-blue-700\">Testing</h1>\n```\n\n```js\nimport tailwindcss from 'tailwindcss'\n```\n\n```js\ncss: {\n  postcss: {\n    plugins: [tailwindcss],\n  },\n}\n```\n\n```js\n/*Other imports*/\nimport tailwindcss from 'tailwindcss'\n\nexport default defineConfig({\n  plugins: [],\n  resolve: {\n    /*something*/\n  },\n  css: {\n    postcss: {\n      plugins: [tailwindcss],\n    },\n  },\n});\n```\n\n```text\nvite.config.js\n```\n\n```text\nvite.config.js\n```\n\n========================================\n\nComments:\n- Have you actually used any of html classes? And you also need to configure `content` property to tell Tailwind where to find the files with classes\n- looks like the OP already has done all that things\n- @Nikita no, he did not tell Tailwind where to look for class names to include (see the `content: [ &#47;&#47; add your sources here ]` list\n- Thank a ton. Found this answer after 2 days and it worked like a charm. When using backend integration feature of vite, it is required to set `css.postcss.plugins` property to `tailwindcss` in vite.config.js file.\n- thanks, this saved me! might be useful to have the `import { defineConfig } from 'vite'` at the top of your `vite.config.js` example :-)\n- working for me with a vite react project, thanks\n- I could not find this *anywhere* in the documentation. thank you! I'm sure it's on the interwebs somewhere but I didn't see it.","metadata":{"transformedAt":"2026-08-18T18:33:46.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":199,"estimatedTokens":896}}68{"id":"stack-72753092","source":"stackoverflow","questionId":72753092,"title":"How to proxy on Svelte-kit in dev mode","tags":["svelte","vite","sveltekit"],"text":"Title: How to proxy on Svelte-kit in dev mode\nTags: svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am trying to redirect for local development my requests to `/api/**` to my backend server.\n\nSo a request to `http://localhost:3000/api/upload` goes to `http://localhost:8080/api/upload`.\n\nI cannot find any `svelte.config.js` configuration, to get this to work for dev. Also `svelte-kit dev` does not provide this configuration (or I cannot find it).\n\nDoes anyone know how to do so in svelte-kit?\n\n========================================\n\nTop Answer:\nHere's the Typescript version (for those that need that).\n\n**vite.config.ts** (usually found at root)\n\n```\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\n\n// Docs: https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [svelte()],\n server: {\n proxy: {\n '/api': 'http://localhost:8080'\n }\n }\n})\n```\n\n========================================\n\nCode:\n```text\n/api/**\n```\n\n```text\nhttp://localhost:3000/api/upload\n```\n\n```text\nhttp://localhost:8080/api/upload\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nsvelte-kit dev\n```\n\n```js\nconst config = {\n    // ...\n    server: {\n        proxy: {\n            '/api': 'http://localhost:8080',\n        },\n    },\n};\n```\n\n```text\nvite.config.js\n```\n\n```text\nserver.proxy\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\n\n// Docs: https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [svelte()],\n  server: {\n    proxy: {\n      '/api': 'http://localhost:8080'\n    }\n  }\n})\n```\n\n========================================\n\nComments:\n- In 2022 it's moved to `vite.config.js`, as you can see in svelte.kit docs.\n- @gyurielf the answer says exactly this, so your comment adds nothing.\n- @Coreus: That is because I updated it accordingly.\n- Do not edit the answer based whether you use single or double quotes. People's preferences are different and such edits are thus as biased as the answer.\n- I only see javascript","metadata":{"transformedAt":"2026-08-18T18:33:46.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":100,"estimatedTokens":507}}69{"id":"stack-72128718","source":"stackoverflow","questionId":72128718,"title":"Test suite failed to run import.meta.env.VITE_*","tags":["vue.js","jestjs","vite","vue-test-utils"],"text":"Title: Test suite failed to run import.meta.env.VITE_*\nTags: vue.js, jestjs, vite, vue-test-utils\nSource: Stack Overflow\n\nQuestion:\nAfter adding the environment variable `import.meta.env.VITE_*` in my code, the tests with vue-test-utils started to fail, with the error:\n\n```\nJest suite failed to run\nerror TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node12', or 'nodenext'.\n```\n\nI have searched for some available fixes but none have worked so far.\n\n**EDIT**\n\njest.config.js file:\n\n```\nmodule.exports = {\n preset: \"ts-jest\",\n globals: {},\n testEnvironment: \"jsdom\",\n transform: {\n \"^.+\\\\.vue$\": \"@vue/vue3-jest\",\n \"^.+\\\\js$\": \"babel-jest\"\n },\n moduleFileExtensions: [\"vue\", \"js\", \"json\", \"jsx\", \"ts\", \"tsx\", \"node\"],\n moduleNameMapper: {\n \"\\\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$\":\n \"/tests/unit/__mocks__/fileMock.js\",\n \"^@/(.*)$\": \"/src/$1\"\n }\n}\n```\n\ntsconfig.json file:\n\n```\n{\n \"extends\": \"@vue/tsconfig/tsconfig.web.json\",\n \"include\": [\"env.d.ts\", \"src/**/*\", \"src/**/*.vue\", \"tests\"],\n \"compilerOptions\": {\n \"module\": \"esnext\",\n \"experimentalDecorators\": true,\n \"baseUrl\": \".\",\n \"paths\": {\n \"@/*\": [\"./src/*\"]\n }\n },\n\n \"references\": [\n {\n \"path\": \"./tsconfig.vite-config.json\"\n }\n ]\n}\n```\n\nWhen including `module: \"esnext\"`, the warning below is displayed and the error remains.\n\nValidation Warning:\n\nUnknown option \"module\" with value \"commonjs\" was found. This is\nprobably a typing mistake. Fixing it will remove this message.\n\nConfiguration Documentation: https://jestjs.io/docs/configuration\n\n========================================\n\nTop Answer:\nPersonally I route all my `import.meta.env` values through a single file (src/constants.ts or src/constants.js)\n\n```\n// src/constants.(js|ts)...\n\nconst {\n MODE: ENVIRONMENT,\n} = import.meta.env;\n\nexport {\n ENVIRONMENT\n};\n```\n\nThen in my jest tests I just mock the constants file:\n\n```\n// example.test.(js|ts)\njest.mock('src/constants', () => ({\n ENVIRONMENT: 'development',\n}));\n```\n\nIMHO this is better also because you'll likely want to mock the value anyway.\n\nIf you want to mock things at the global level you can do what @FahadJaved talks about in the comments. It would look something like this:\n\n```\n// jest.config.(js|ts)\nmoduleNameMapper: {\n // other things...\n 'src/constants': '/__mocks__/constantsMock.ts',\n },\n```\n\n```\n// __mocks__/constantsMock.ts\n\nexport const ENVIRONMENT = 'development';\n\n// or... \n\njest.mock('src/constants', () => ({\n ENVIRONMENT: 'development',\n}));\n```\n\nJust be sure your imports always use the exact path that gets mocked, `src/constants`. You may have to configure **`tsconfig.json`** to allow always using `src/constants` in your imports (no relative paths with `../`, etc.).\n\n```\n\"compilerOptions\": {\n \"baseUrl\": \"./\",\n \"paths\": {\n \"src/*\": [\"src/*\"]\n },\n // ...\n },\n // ...\n```\n\n========================================\n\nCode:\n```text\nJest suite failed to run\nerror TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node12', or 'nodenext'.\n```\n\n```text\nmodule.exports = {\n  preset: \"ts-jest\",\n  globals: {},\n  testEnvironment: \"jsdom\",\n  transform: {\n    \"^.+\\\\.vue$\": \"@vue/vue3-jest\",\n    \"^.+\\\\js$\": \"babel-jest\"\n  },\n  moduleFileExtensions: [\"vue\", \"js\", \"json\", \"jsx\", \"ts\", \"tsx\", \"node\"],\n  moduleNameMapper: {\n    \"\\\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$\":\n      \"<rootDir>/tests/unit/__mocks__/fileMock.js\",\n    \"^@/(.*)$\": \"<rootDir>/src/$1\"\n  }\n}\n```\n\n```text\n{\n  \"extends\": \"@vue/tsconfig/tsconfig.web.json\",\n  \"include\": [\"env.d.ts\", \"src/**/*\", \"src/**/*.vue\", \"tests\"],\n  \"compilerOptions\": {\n    \"module\": \"esnext\",\n    \"experimentalDecorators\": true,\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@/*\": [\"./src/*\"]\n    }\n  },\n\n  \"references\": [\n    {\n      \"path\": \"./tsconfig.vite-config.json\"\n    }\n  ]\n}\n```\n\n```text\nimport.meta.env.VITE_*\n```\n\n```text\nmodule: \"esnext\"\n```\n\n```text\nmodule.exports = {\n  ...\n  plugins: [\"babel-plugin-transform-import-meta\"]\n}\n```\n\n```text\n{\n  ...\n  \"compilerOptions\": {\n    \"module\": \"esnext\",\n    ...\n    \"types\": [\n      \"node\"\n    ]\n  },\n  ...\n}\n```\n\n```text\n...\nimport EnvironmentPlugin from \"vite-plugin-environment\"\n...\nexport default defineConfig({\n  plugins: [..., EnvironmentPlugin(\"all\")],\n  ...\n})\n```\n\n```text\nvite-plugin-environment\n```\n\n```text\nbabel-plugin-transform-import-meta\n```\n\n```text\nimport.meta.env.*\n```\n\n```text\nprocess.env.*\n```\n\n```text\n// src/constants.(js|ts)...\n\nconst {\n  MODE: ENVIRONMENT,\n} = import.meta.env;\n\nexport {\n  ENVIRONMENT\n};\n```\n\n```text\n// example.test.(js|ts)\njest.mock('src/constants', () => ({\n  ENVIRONMENT: 'development',\n}));\n```\n\n```text\n// jest.config.(js|ts)\nmoduleNameMapper: {\n    // other things...\n    'src/constants': '<rootDir>/__mocks__/constantsMock.ts',\n  },\n```\n\n```text\n// __mocks__/constantsMock.ts\n\nexport const ENVIRONMENT = 'development';\n\n// or... \n\njest.mock('src/constants', () => ({\n  ENVIRONMENT: 'development',\n}));\n```\n\n```json\n\"compilerOptions\": {\n        \"baseUrl\": \"./\",\n        \"paths\": {\n            \"src/*\": [\"src/*\"]\n        },\n        // ...\n    },\n    // ...\n```\n\n```text\nimport.meta.env\n```\n\n```text\nsrc/constants\n```\n\n```text\ntsconfig.json\n```\n\n```text\nsrc/constants\n```\n\n```text\n../\n```\n\n```text\nnpm install --save-dev dotenv cross-env\n```\n\n```js\n...\nimport { loadEnv } from 'vite'\n...\nexport default defineConfig(({ command, mode }) => { \n  const env = loadEnv(mode, process.cwd(), '');\n  return {\n    plugins:[react()],\n    server: {\n      host:true\n    },\n    define: {\n      'process.env.YOUR_STRING_VARIABLE': \n      JSON.stringify(env.YOUR_STRING_VARIABLE),\n      'process.env.APP_USE_AVT': env.APP_USE_AVT,\n    },\n  };\n});\n```\n\n```text\nvite.config.js\n```\n\n```text\nconst {\n      MODE: ENVIRONMENT,\n    } \n\n= import.meta.env;\n```\n\n```text\njest.mock('../your/envConstants.ts', () => ({\n  MODE: 'YOUR_MODE',\n}));\n```\n\n```js\n#env.app.ts\n\nexport const getLoginMode = () => {\n    return import.meta.env.LOGIN_MODE;\n};\n```\n\n```js\n#env.jest.ts\n\nexport const getLoginMode = () => {\n    return process.env.LOGIN_MODE;\n};\n```\n\n```js\n#env.ts\n\nexport * from \"./env.app\";\n```\n\n```js\n#component\n\nimport { getLoginMode } from \"path_to_env/env\";\nconst loginMode = getLoginMode();\n```\n\n```js\n#jest.config.ts\n\nmoduleNameMapper: {\n    \"^@/utility/vite-env/env$\": \"<rootDir>/src/utility/vite-env/env.jest.ts\",\n};\n```\n\n```text\nprocess.env\n```\n\n```text\nimport.meta.env\n```\n\n```text\nenv.app.ts\n```\n\n```text\nimport.meta.env\n```\n\n```text\nenv.jest.ts\n```\n\n```text\nprocess.env\n```\n\n```text\nenv.ts\n```\n\n```text\nimport.meta.env\n```\n\n```text\nmoduleNameMapper\n```\n\n```text\njest.config.ts\n```\n\n```text\nenv.jest.ts\n```\n\n```text\nenv.ts\n```\n\n```text\nprocess.env\n```\n\n```text\nenv.jest.ts\n```\n\n========================================\n\nComments:\n- One problem is that the ENV variable value is coming as undefined, when i run the code with jest\n- @manishkeer see my answer to solving this - it will ensure that the value is set when running jest.\n- changing the import.meta.env.* to process.env.* worked for me.\n- This solution worked for me when 45 minutes of failed babel/jest related software dev acrobatics failed. It was simple and replaces all the difficult \"modify your babel! install a plugin!\" type solutions with something simple and direct. I recommend it to others.\n- Does destructuring play nicely with vite's static replacement?\n- @jeff As far as I know - yes. I've been doing this approach for about six months without any issues. The app in all environments gets the right values set and exported from the constants file. And the jest tests work without having to do anything extra or special. :D\n- Well, I love you. Maybe 3 hours spent in this #$%&. Just your answer could save me. Thanks. I think this must be marked as the correct answer.\n- Best answer, imo\n- Simple and to-the-point solution to this problem. I also set all my environment variables in a single file so this solution worked like a charm. One thing I'd like to add is that you don't need to mock the same file again and again in every test file, you can create a module mapping using `moduleNameMapper` in the jest.config.js file and you're good to go :)\n- I've gotten to the stage where as soon as I see babel config files / plugins being mentioned I just skip right past. This is how simple and concise every answer should be!\n- @FahadJaved Please could you explain how you used `moduleNameMapper` in the way you mentioned? I have added a mock `beforeAll` in the jest.config file. Is that equivalent to your point?\n- @atomicDroid Please see my original answer for an update on how to use moduleNameMapper\n- This appears to work but I can't appear to reassign the environment variable? Even with beforeEach clearAllMocks","metadata":{"transformedAt":"2026-08-18T18:33:46.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":46,"totalLines":454,"estimatedTokens":2216}}70{"id":"stack-73010251","source":"stackoverflow","questionId":73010251,"title":"ReferenceError: $ is not defined, Jquery Import with vite","tags":["javascript","jquery","laravel","vite"],"text":"Title: ReferenceError: $ is not defined, Jquery Import with vite\nTags: javascript, jquery, laravel, vite\nSource: Stack Overflow\n\nQuestion:\nI tried with fresh install laravel 9.20 and with minimum configuration\n\n**in vite.config.js**\n\n```\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\n\nexport default defineConfig({\n plugins: [\n laravel({\n input: [\n 'resources/js/app.js',\n ],\n refresh: true,\n }),\n ],\n});\n```\n\n**in app.js**\n\n```\nimport './bootstrap';\n\nimport $ from \"jquery\"; \nwindow.$ = window.jQuery = $;\n\nimport '../sass/app.scss';\n```\n\ni have tried with this too\n\n```\nimport * as $ from \"jquery\";\nwindow.$ = window.jQuery = $;\n```\n\nload the assets in blade and i test with this script\n\n```\n@vite(['resources/js/app.js']);\n\n$(\"#alertbox\").alert(\"test\");\n```\n\nbut i get the following error in the console:\n\nUncaught ReferenceError: $ is not defined\n\nI can't make it work, please help\n\n========================================\n\nTop Answer:\nadd type = module in tag script\n\n```\n\n code....\n\n```\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\n\nexport default defineConfig({\n    plugins: [\n        laravel({\n            input: [\n                'resources/js/app.js',\n            ],\n            refresh: true,\n        }),\n    ],\n});\n```\n\n```text\nimport './bootstrap';\n\nimport $ from \"jquery\"; \nwindow.$ = window.jQuery = $;\n\nimport '../sass/app.scss';\n```\n\n```text\nimport * as $ from \"jquery\";\nwindow.$ = window.jQuery = $;\n```\n\n```text\n@vite(['resources/js/app.js']);\n\n$(\"#alertbox\").alert(\"test\");\n```\n\n```text\n<script>\n   setTimeout(function() {\n      console.log($);\n      $(\"#alertbox\").alert(\"test\");\n   }, 5000);\n</script>\n```\n\n```text\n<script type=\"module\" src=\"http://localhost/build/assets/app.342432.js\"></script>\n```\n\n```text\n@vite(['resources/js/app.js']);\n\n<script type=\"module\">\n   $(\"#alertbox\").alert(\"test\");\n</script>\n```\n\n```text\n$ is undefined\n```\n\n```text\napp.js\n```\n\n```text\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js\" integrity=\"sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\"></script>\n```\n\n```text\n<script type=\"module\">\n    code....\n</script>\n```\n\n```text\nimport $ from 'jquery';\nwindow.$ = $; // this worked for me\nimport 'datatables.net';\n```\n\n```text\n<script type=\"module\">\n    $(document).ready(function() {\n        $('#websites-table').DataTable({\n            // Your code\n        });       \n    });\n</script>\n```\n\n========================================\n\nComments:\n- Does this answer your question? How to import jquery using ES6 syntax?\n- I would suggest the person who posted this question to mark this answer as correct. It really helped!\n- Thank you for the explanation, I was wondering why I was getting the error despite setting things up correctly. I struggled for days with this error and I'm glad you curated this solution and explanation.\n- Some people are using webpack or vite, so this solution is probably not relevant.","metadata":{"transformedAt":"2026-08-18T18:33:46.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":169,"estimatedTokens":782}}71{"id":"stack-75640753","source":"stackoverflow","questionId":75640753,"title":"Vite + ESBuild error: No loader is configured for \".node\" files: node_modules/fsevents/fsevents.node","tags":["node.js","reactjs","vite","es6-modules","fsevents"],"text":"Title: Vite + ESBuild error: No loader is configured for \".node\" files: node_modules/fsevents/fsevents.node\nTags: node.js, reactjs, vite, es6-modules, fsevents\nSource: Stack Overflow\n\nQuestion:\nI am very new to ReactJS and Vite. I am working on some tutorials I have suddenly started getting below error. I have tried to re-install node_modules but didn't work.\n[ERROR] No loader is configured for \".node\" files: node_modules/fsevents/fsevents.node\n\n```\nnode_modules/fsevents/fsevents.js:13:23:\n 13 │ const Native = require(\"./fsevents.node\");\n ╵ ~~~~~~~~~~~~~~~~~\n```\n\n/advanced-react/node_modules/esbuild/lib/main.js:1604\nlet error = new Error(`${text}${summary}`);\n\n```\nError: Build failed with 1 error:\nnode_modules/fsevents/fsevents.js:13:23: ERROR: No loader is configured for \".node\" files: node_modules/fsevents/fsevents.node\n at failureErrorWithLog (/advanced-react/node_modules/esbuild/lib/main.js:1604:15)\n at /advanced-react/node_modules/esbuild/lib/main.js:1056:28\n at runOnEndCallbacks (/advanced-react/node_modules/esbuild/lib/main.js:1476:61)\n at buildResponseToResult (/advanced-react/node_modules/esbuild/lib/main.js:1054:7)\n at /advanced-react/node_modules/esbuild/lib/main.js:1166:14\n at responseCallbacks. (/advanced-react/node_modules/esbuild/lib/main.js:701:9)\n at handleIncomingPacket (/advanced-react/node_modules/esbuild/lib/main.js:756:9)\n at Socket.readFromStdout (/advanced-react/node_modules/esbuild/lib/main.js:677:7)\n at Socket.emit (node:events:513:28)\n at addChunk (node:internal/streams/readable:324:12) {\n errors: [\n {\n detail: undefined,\n id: '',\n location: {\n column: 23,\n file: 'node_modules/fsevents/fsevents.js',\n length: 17,\n line: 13,\n lineText: 'const Native = require(\"./fsevents.node\");',\n namespace: '',\n suggestion: ''\n },\n notes: [],\n pluginName: '',\n text: 'No loader is configured for \".node\" files: node_modules/fsevents/fsevents.node'\n }\n ],\n warnings: []\n}\n\nNode.js v18.12.1\n```\n\nBelow is the package.json\n\n```\n{\n \"name\": \"advanced_react\",\n \"private\": true,\n \"version\": \"0.0.0\",\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\"\n },\n \"dependencies\": {\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\"\n },\n \"devDependencies\": {\n \"@types/react\": \"^18.0.27\",\n \"@types/react-dom\": \"^18.0.10\",\n \"@vitejs/plugin-react\": \"^3.1.0\",\n \"vite\": \"^4.1.0\",\n \"node-loader\": \"^2.0.0\"\n },\n \"resolutions\": {\n \"**/**/fsevents\": \"^1.2.9\"\n }\n}\n```\n\nI am not able to figure out what I am missing in the config.\n\n========================================\n\nTop Answer:\nI had the same issue, and in my case I found that vscode had accidentally imported the mergeAlias method from vitejs somewhere in my project and that had been the issue.\n\n========================================\n\nCode:\n```text\nnode_modules/fsevents/fsevents.js:13:23:\n  13 │ const Native = require(\"./fsevents.node\");\n     ╵                        ~~~~~~~~~~~~~~~~~\n```\n\n```text\nError: Build failed with 1 error:\nnode_modules/fsevents/fsevents.js:13:23: ERROR: No loader is configured for \".node\" files: node_modules/fsevents/fsevents.node\n    at failureErrorWithLog (/advanced-react/node_modules/esbuild/lib/main.js:1604:15)\n    at /advanced-react/node_modules/esbuild/lib/main.js:1056:28\n    at runOnEndCallbacks (/advanced-react/node_modules/esbuild/lib/main.js:1476:61)\n    at buildResponseToResult (/advanced-react/node_modules/esbuild/lib/main.js:1054:7)\n    at /advanced-react/node_modules/esbuild/lib/main.js:1166:14\n    at responseCallbacks.<computed> (/advanced-react/node_modules/esbuild/lib/main.js:701:9)\n    at handleIncomingPacket (/advanced-react/node_modules/esbuild/lib/main.js:756:9)\n    at Socket.readFromStdout (/advanced-react/node_modules/esbuild/lib/main.js:677:7)\n    at Socket.emit (node:events:513:28)\n    at addChunk (node:internal/streams/readable:324:12) {\n  errors: [\n    {\n      detail: undefined,\n      id: '',\n      location: {\n        column: 23,\n        file: 'node_modules/fsevents/fsevents.js',\n        length: 17,\n        line: 13,\n        lineText: 'const Native = require(\"./fsevents.node\");',\n        namespace: '',\n        suggestion: ''\n      },\n      notes: [],\n      pluginName: '',\n      text: 'No loader is configured for \".node\" files: node_modules/fsevents/fsevents.node'\n    }\n  ],\n  warnings: []\n}\n\nNode.js v18.12.1\n```\n\n```text\n{\n  \"name\": \"advanced_react\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"preview\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^18.0.27\",\n    \"@types/react-dom\": \"^18.0.10\",\n    \"@vitejs/plugin-react\": \"^3.1.0\",\n    \"vite\": \"^4.1.0\",\n    \"node-loader\": \"^2.0.0\"\n  },\n  \"resolutions\": {\n    \"**/**/fsevents\": \"^1.2.9\"\n  }\n}\n```\n\n```text\n${text}${summary}\n```\n\n```text\noptimizeDeps: { exclude: [\"fsevents\"] },\n```\n\n```text\nfsevents\n```\n\n```text\noptimizeDeps\n```\n\n```text\nvite.config.js\n```\n\n```text\nimport {sortUserPlugins} from 'vite';\n```\n\n========================================\n\nComments:\n- For context, this is supposed to go into `vite.config.ts`\n- Some of us don't use TypeScript, so I assume your comment is only for those that do use it.\n- This made no change for me. Please add an explanation as to how this is supposed to fix the error and how it relates.\n- +1; it seems that any random accidental import from `vite` causes this issue - in my case, my IDE mistakenly had imported `import {send} from \"vite\";`\n- Same here with `import { createLogger } from 'vite';` imported in my file by VS Code when I wanted to console.log\n- Same here, in my case it was the `import { isCSSRequest } from 'vite';` line which caused trouble\n- Same. Searching for \"from 'vite'\" in VS Code can help to find the accidental wrong import","metadata":{"transformedAt":"2026-08-18T18:33:46.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":199,"estimatedTokens":1458}}72{"id":"stack-72005194","source":"stackoverflow","questionId":72005194,"title":"Vue 3 & Vite built application shows blank page","tags":["javascript","deployment","build","vuejs3","vite"],"text":"Title: Vue 3 & Vite built application shows blank page\nTags: javascript, deployment, build, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI have a problem trying to make a build of a new Vue3.js + Vite.js application. Once my application is finished i made the `npm run build` action in order to generate the final deployment files.\n\nProblem is that when I try to see the generated page, it only shows a white page.\n\nhttps://i.sstatic.net/55ZTb.png\n\nOpening the inspection tool I can see how the main generated javascript files are like not being found by the static index.html:\n\n```\nFailed to load resource: net::ERR_FAILED index.7b66f7af.js:1\n```\n\n========================================\n\nTop Answer:\nYou cannot run a Vite project by opening index.html by hand. You can see that the file path is currently in the webbrowsers url bar. Vite only allows the accesss to the required JavaScript files via `http://` or `https://`. (or some other defined protocols).\n\nIf you still call the index.html via `file://` you will get an CORS error or file not found error.\n\nTry to deploy your vite builds on a webserver which can be accessed via http/s.\n\nExample error when accessing react app via `file://`\n\n========================================\n\nCode:\n```text\nFailed to load resource: net::ERR_FAILED              index.7b66f7af.js:1\n```\n\n```text\nnpm run build\n```\n\n```text\nimport {\n  defineConfig\n} from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport vuetify from '@vuetify/vite-plugin'\n\nconst path = require('path')\n\nexport default defineConfig({\n  plugins: [\n    vue(),\n\n    vuetify({\n      autoImport: true,\n    }),\n  ],\n  define: {\n    'process.env': {}\n  },\n  resolve: {\n    alias: {\n      '@': path.resolve(__dirname, 'src'),\n    },\n  },\n  base: './',\n\n})\n```\n\n```text\nbase: './'\n```\n\n```text\nvite.config.js\n```\n\n```text\nbase: mode === 'production' ? '/nameExample/' : '/'\n```\n\n```text\nhttp://\n```\n\n```text\nhttps://\n```\n\n```text\nfile://\n```\n\n```text\nfile://\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\nimport { fileURLToPath, URL } from 'node:url'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue()],\n  // base: './',         // works, but can clash with createWebHistory\n  // base: '/',          // if the app is in root directory\n  base: '/webamy-app/',  // if the app is in sub path\n})\n```\n\n```text\n...\nconst router = createRouter({\n    // history: createWebHistory(),\n    history: createWebHistory(import.meta.env.BASE_URL),\n    routes,\n})\n```\n\n```text\nhttps://example.com/webamy-app/\n```\n\n```text\nhttps://example.com/\n```\n\n```text\nif (!userStore.$state.token) {\n  console.log('Not logged in')\n  await router.push({name: 'Auth/Login'})\n}\n```\n\n```text\nif (!userStore.$state.token) {\n  console.log('Not logged in')\n  setTimeout(async () => {\n    await router.push({name: 'Auth/Login'})\n  }, 1)\n}\n```\n\n========================================\n\nComments:\n- Not sure how this may help since there was no code initially.\n- Yep, all good now.\n- hello I added the base, but the page still produces white screen\n- This also fixes for page reload blank page in Vue 3 projects. Thanks!\n- Please use the proper formatting for code part.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:46.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":154,"estimatedTokens":872}}73{"id":"stack-75412767","source":"stackoverflow","questionId":75412767,"title":"How to tell Vite to exclude a subset of files in a directory from build?","tags":["javascript","vue.js","vite","rollup"],"text":"Title: How to tell Vite to exclude a subset of files in a directory from build?\nTags: javascript, vue.js, vite, rollup\nSource: Stack Overflow\n\nQuestion:\nI created a new Vue app using `npm create vue`. During runtime this app fetches a configuration and reads a string from it. This string represents the name of a component to render inside the app. Those dynamic components live inside a \"pluggable\" directory\n\n```\n.\n└── src\n ├── App.vue\n └── pluggables\n ├── ThisFoo.vue\n └── ThatBar.vue\n```\n\nSo basically what the App.vue file does is\n\n```\n\nimport { onMounted, shallowRef, defineAsyncComponent } from \"vue\";\n\nconst pluggableComponent = shallowRef();\n\nonMounted(() => {\n // fetch configuration\n const componentName = \"ThisFoo\"; // extract from configuration\n\n pluggableComponent.value = defineAsyncComponent(() => import(`./pluggables/${componentName}.vue`));\n});\n\n Pluggable below:\n \n\n```\n\nI have access to the configuration file during build time and know which components I need during runtime and which ones to consider as \"dead code\" based on this configuration. Is there a way to tell Vite to exclude the unused components from the build?\n\nE.g. exclude the whole pluggables directory but include the required components from the pluggables directory\n\nvite build --exclude ./src/pluggables/** --include ./src/pluggables/ThisFoo.vue\n\nor by creating a custom Vite build function I can call during CI/CD and pass in an array of component names.\n\n========================================\n\nTop Answer:\nI end up just using the `{ \"exclude\": [] }` in `tsconfig.json`. \n\nAnd it worked for me. *(Not sure if that is the proper way.)*\n*(using React + Typescript, not vue)*\n\n========================================\n\nCode:\n```text\n.\n└── src\n    ├── App.vue\n    └── pluggables\n        ├── ThisFoo.vue\n        └── ThatBar.vue\n```\n\n```text\n<script setup lang=\"ts\">\nimport { onMounted, shallowRef, defineAsyncComponent } from \"vue\";\n\nconst pluggableComponent = shallowRef();\n\nonMounted(() => {\n  // fetch configuration\n  const componentName = \"ThisFoo\"; // extract from configuration\n\n  pluggableComponent.value = defineAsyncComponent(() => import(`./pluggables/${componentName}.vue`));\n});\n</script>\n\n<template>\n  <div>Pluggable below:</div>\n  <component :is=\"pluggableComponent\" />\n</template>\n```\n\n```text\nnpm create vue\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\";\nimport * as path from \"path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst filesNeedToExclude = [\"src/pluggables/Comp1.vue\", \"src/pluggables/Comp2.vue\"];\n\nconst filesPathToExclude = filesNeedToExclude.map((src) => {\n  return fileURLToPath(new URL(src, import.meta.url));\n});\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue()],\n  resolve: {\n    alias: {\n      \"@\": path.resolve(__dirname, \"./src\"),\n    },\n  },\n\n  build: {\n    manifest: true,\n    rollupOptions: {\n      external: [\n        ...filesPathToExclude\n      ],\n    },\n  },\n});\n```\n\n```text\nimport { readdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\nfunction getPluggablesToExclude(): string[] {\n  const rawPluggablesToInclude = process.env.PLUGGABLES; // !! set this env variable in the CI pipeline !!\n\n  if (!rawPluggablesToInclude) { // if missing, exclude nothing\n    return [];\n  }\n\n  const pluggablesToInclude = rawPluggablesToInclude.split(',').map(component => `${component}.vue`);\n\n  const pluggablesDirectoryPath = join(__dirname, 'src', 'pluggables');\n  const filesInPluggablesDirectory = readdirSync(pluggablesDirectoryPath);\n\n  const filesToExclude = filesInPluggablesDirectory.filter(file => !pluggablesToInclude.includes(file));\n\n  return filesToExclude.map(file => join(pluggablesDirectoryPath, file));\n}\n\nexport default defineConfig({\n  plugins: [vue()],\n  build: {\n    rollupOptions: {\n      external: [\n        ...getPluggablesToExclude()\n      ],\n    },\n  },\n})\n```\n\n```text\n{ \"exclude\": [] }\n```\n\n```text\ntsconfig.json\n```\n\n========================================\n\nComments:\n- Likely should be a glob that excludes these names. See vitejs.dev/guide/features.html#glob-import-caveats\n- But which is the correct option in the vite.config file for `import.meta.glob`? Most samples I see do it inside the code but just to import multiple files at once. I want to exclude specific files during build time\n- Actually, these files will be built into separate chunks right? So even if some of them are dead code, they still will not affect your main bundle size. So what is your reason for excluding them?\n- @Duannx why are they not affecting the build size? They live in the build directory :S I want to exclude them because customers should not be able to see components other customers might be using\n- thanks for your answer. What do you thing about this one? stackoverflow.com/a/75494333/19698303 Any suggestions for improvements?\n- I am assuming this answer does not work when bundling a library right? this didn't work for me.\n- @StephaniBishop did you find a solution for library mode?\n- Looking for a fix too.\n- Does not work for me also, when specifying directories. Does this only work on individual files?\n- This should work. But there is a better but harder way which is using regex in the list. You can use a negative regex to check the file name does not in the array so it will be marked as external. Here is the regex generated from chat GPT :) Test it before using `^(?!${fileNames.join(\"|\")}$).*$`","metadata":{"transformedAt":"2026-08-18T18:33:46.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":177,"estimatedTokens":1382}}74{"id":"stack-74992987","source":"stackoverflow","questionId":74992987,"title":"Vite - how to change code in node_modules folder to debug/find errors","tags":["node-modules","vite"],"text":"Title: Vite - how to change code in node_modules folder to debug/find errors\nTags: node-modules, vite\nSource: Stack Overflow\n\nQuestion:\nComing from Webpack I was able to change code in the `node_modules` folder in order to add a `console.log` statement or something like this to find errors.\nSometimes I use external libraries incorrectly and it's easier to be able to alter lines/files in the `node_modules` folder to find out what my mistakes are.\n\nWith Vite, this is not possible. I can change whatever I want in the `node_modules` folder by my browser still uses the original libraries code.\nIs there a way that allows me to change files so Vite will recognize the changes and use my new files?\n\nNote: it's not about pull requests or permanent changes, it's only about an `console.log(typeof X)` and stuff like that for a single use.\n\nBascially the same question as this one Changing code in node_modules does not work in hot reload regardless of the bundler\n\n========================================\n\nTop Answer:\nRestart Vite dev server with the `--force` flag to re-bundle the deps. This has the same effect as manually deleting the `node_modules/.vite` directory.\n\nSee File System Cache in Dependency Pre-Bundling for more information.\n\n========================================\n\nCode:\n```text\nnode_modules\n```\n\n```text\nconsole.log\n```\n\n```text\nnode_modules\n```\n\n```text\nnode_modules\n```\n\n```text\nconsole.log(typeof X)\n```\n\n```bash\nrm -rf ./node_modules/.vite\n```\n\n```bash\nrm -rf node_modules/.vite; npm run dev\n```\n\n```text\nvite-shim-foobar\n```\n\n```text\n--force\n```\n\n```text\nnode_modules/.vite\n```\n\n========================================\n\nComments:\n- thank you, this works, but I always have to restart the bundler for any change. But at least this way I'm able to include a log\n- Note you may also need to force-clear your browser cache.\n- Thank you, `--force` flag wasnt working for me and I was losing my mind!","metadata":{"transformedAt":"2026-08-18T18:33:46.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":71,"estimatedTokens":481}}75{"id":"stack-70818545","source":"stackoverflow","questionId":70818545,"title":"How to include HTML partials using Vite?","tags":["templates","rollup","rollupjs","vite"],"text":"Title: How to include HTML partials using Vite?\nTags: templates, rollup, rollupjs, vite\nSource: Stack Overflow\n\nQuestion:\nIs it possible to include snippets of shared HTML using Vite (vanilla)? I'm looking for a way to have the HTML prerendered without injecting via JS.\n\nSomething like:\n\n```\n\n \n { include 'meta-tags' }\n \n \n { include 'nav' }\n \n\n### Hello World\n\n \n\n```\n\n========================================\n\nTop Answer:\nYou could use the `vite-plugin-html` that enables EJS templates in `index.html`:\n\n```\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport { createHtmlPlugin } from 'vite-plugin-html'\n\nexport default defineConfig({\n plugins: [\n createHtmlPlugin({\n entry: 'main.js',\n\n /**\n * Data that needs to be injected into the index.html ejs template\n */\n inject: {\n data: {\n metaTags: `\n `,\n nav: `\n Google | \n Apple\n `,\n },\n },\n }),\n ],\n})\n```\n\n```\n\n \n \n \n \n \n \n\n### Hello World\n\n \n\n```\n\ndemo\n\n========================================\n\nCode:\n```html\n<html>\n  <head>\n    { include 'meta-tags' }\n  </head>\n  <body> \n    { include 'nav' }\n    <h1>Hello World</h1>\n  <body>\n</html>\n```\n\n```js\n// vite.config.js\nimport { resolve } from 'path';\nimport handlebars from 'vite-plugin-handlebars';\n\nexport default {\n  plugins: [\n    handlebars({\n      partialDirectory: resolve(__dirname, 'partials'),\n    }),\n  ],\n};\n```\n\n```html\n<!-- index.html -->\n{{> header }}\n\n<h1>The Main Page</h1>\n```\n\n```html\n<header><a href=\"/\">My Website</a></header>\n\n<h1>The Main Page</h1>\n```\n\n```text\nvite-plugin-handlebars\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport { createHtmlPlugin } from 'vite-plugin-html'\n\nexport default defineConfig({\n  plugins: [\n    createHtmlPlugin({\n      entry: 'main.js',\n\n      /**\n       * Data that needs to be injected into the index.html ejs template\n       */\n      inject: {\n        data: {\n          metaTags: `<meta charset=\"UTF-8\" />\n          <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />`,\n          nav: `<nav>\n            <a href=\"https://google.com\">Google</a> | \n            <a href=\"https://apple.com\">Apple</a>\n          </nav>`,\n        },\n      },\n    }),\n  ],\n})\n```\n\n```html\n<!-- index.html -->\n<html>\n  <head>\n    <%- metaTags %>\n  </head>\n  <body>\n    <%- nav %>\n    <h1>Hello World</h1>\n  <body>\n</html>\n```\n\n```text\nvite-plugin-html\n```\n\n```text\nindex.html\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport path from \"path\";\nimport fs from \"fs\";\n\nfunction renderTemplate(template, locals) {\n  const result = template.replace(/{{\\s*([^}\\s]+)\\s*}}/g, (match, key) => {\n    return locals[key] !== undefined ? locals[key] : \"\";\n  });\n  return result;\n}\n\nfunction parseLocals(localsString) {\n  if (!localsString) {\n    return {};\n  }\n  try {\n    const trimmedString = localsString.replace(/^\\s*|\\s*$/g, \"\");\n    const strippedString = trimmedString.replace(/^'([\\s\\S]*)'$/, \"$1\");\n    const result = JSON.parse(strippedString);\n    return result;\n  } catch (error) {\n    console.error(\"Error parsing locals:\", error);\n    console.error(\"Problematic string:\", localsString);\n    return {};\n  }\n}\n\nfunction processIncludes(html, parentDir, parentLocals = {}) {\n  const includeRegex =\n    /<include\\s+src=\"(.+?)\"(?:\\s+locals='([\\s\\S]*?)')?(?:\\s+locals=\"([\\s\\S]*?)\")?\\s*><\\/include>/g;\n\n  let match;\n  let newHtml = html;\n\n  while ((match = includeRegex.exec(newHtml)) !== null) {\n    const [includeTag, src, singleQuoteLocals, doubleQuoteLocals] = match;\n    const filePath = path.resolve(parentDir, src);\n\n    let content = \"\";\n    try {\n      content = fs.readFileSync(filePath, \"utf-8\");\n    } catch (err) {\n      console.error(`Error reading file: ${filePath}`, err);\n      continue;\n    }\n\n    let locals = { ...parentLocals };\n    const localsString = singleQuoteLocals || doubleQuoteLocals;\n    if (localsString) {\n      const parsedLocals = parseLocals(localsString);\n      locals = { ...locals, ...parsedLocals };\n    }\n\n    content = renderTemplate(content, locals);\n    content = processIncludes(content, path.dirname(filePath), locals);\n    newHtml = newHtml.replace(includeTag, content);\n  }\n  return newHtml;\n}\n\nfunction htmlIncludePlugin() {\n  return {\n    name: \"html-include-plugin\",\n    transformIndexHtml(html, { filename }) {\n      const result = processIncludes(html, path.dirname(filename));\n      return result;\n    },\n  };\n}\n\nexport default defineConfig({\n  root: \"./src\",\n  build: {\n    outDir: \"../dist\",\n    emptyOutDir: true,\n  },\n  plugins: [htmlIncludePlugin()],\n});\n```\n\n```text\n<include src=\"./your-html-fragment.html\" />\n```\n\n```text\n<include src=\"./your-html-fragment.html\" locals=\"{ \"key\": \"value\", \"another-key\": \"another-value\" }\" />\n```\n\n```text\n{{ key }}\n```\n\n```text\n// vite.config.ts\nimport { defineConfig } from 'vite'\nimport htmlInclude from 'vite-plugin-html-include'\n\nexport default defineConfig({\n  plugins: [htmlInclude()]\n})\n```\n\n```html\n<!-- index.html -->\n<include file=\"components/card.html\" $title=\"Hello\">\n  <p>This is the main content</p>\n</include>\n```\n\n```html\n<!-- components/card.html -->\n<div class=\"card\">\n  <h2>{{$title}}</h2>\n  <slot></slot>\n</div>\n```\n\n```text\n<div class=\"card\">\n  <h2>Hello</h2>\n  <p>This is the main content</p>\n</div>\n```\n\n========================================\n\nComments:\n- why does it need a `entry` js?","metadata":{"transformedAt":"2026-08-18T18:33:46.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":298,"estimatedTokens":1325}}76{"id":"stack-71552229","source":"stackoverflow","questionId":71552229,"title":"Vite - How do I use a wildcard in Rollupjs build.rollupOptions.external?","tags":["rollupjs","vite"],"text":"Title: Vite - How do I use a wildcard in Rollupjs build.rollupOptions.external?\nTags: rollupjs, vite\nSource: Stack Overflow\n\nQuestion:\nI'm using Vite to build a library and I get the following error when building the library:\n\n```\nRollup failed to resolve import \"node:path\"\n```\n\nBy adding the failed import to the Rollup options I'm able to fix the error but the build continues to complain for each `node:*` import. In the end I've had to add each one individually to the `build.rollupOptions.external`:\n\n```\nbuild: {\n rollupOptions: {\n external: [ \n 'node:path', \n 'node:https',\n 'node:http',\n 'node:zlib',\n ... \n ],\n},\n```\n\nWhile this solves the issue it is time consuming to list each `node` import individually. Is there instead a way to use some sort of wildcard syntax to automatically resolve all `node` imports?\n\n```\nbuild: {\n rollupOptions: {\n external: [ \n 'node:*' // i.e. this syntax does not work, is there something similar that would work?\n ],\n},\n```\n\n========================================\n\nCode:\n```text\nRollup failed to resolve import \"node:path\"\n```\n\n```js\nbuild: {\n  rollupOptions: {\n    external: [            \n      'node:path',           \n      'node:https',\n      'node:http',\n      'node:zlib',\n      ... \n    ],\n},\n```\n\n```js\nbuild: {\n  rollupOptions: {\n    external: [             \n      'node:*' // i.e. this syntax does not work, is there something similar that would work?\n    ],\n},\n```\n\n```text\nnode:*\n```\n\n```text\nbuild.rollupOptions.external\n```\n\n```text\nnode\n```\n\n```text\nnode\n```\n\n```js\n/^node:.*/\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  build: {\n    rollupOptions: {\n      external: [\n        /^node:.*/,\n      ]\n    }\n  }\n})\n```\n\n```text\nbuild.rollupOptions.external\n```\n\n```text\nRegExp\n```\n\n```text\nnode:\n```\n\n```text\nexternal\n```\n\n========================================\n\nComments:\n- Did now know, should have checked the docs again, thanks XD\n- I found this answer while looking for a method to filter out all external dependencies. To filter all of them out, put `&#47;node_modules&#47;` into the array.","metadata":{"transformedAt":"2026-08-18T18:33:46.397Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":122,"estimatedTokens":527}}77{"id":"stack-72658907","source":"stackoverflow","questionId":72658907,"title":"How do I copy a static folder to both \"dev\" and \"build\" in Vite?","tags":["javascript","vue.js","vite"],"text":"Title: How do I copy a static folder to both \"dev\" and \"build\" in Vite?\nTags: javascript, vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to upgrade my Webpack based Vue.js project to Vite. I have folder structure like this:\n\n```\n- src/\n - static/\n - tests/\n```\n\nIn Webpack, I was using CopyWebPackPlugin like this:\n\n```\nnew CopyWebpackPlugin([\n {\n from: path.resolve(__dirname, '../static'),\n to: '',\n ignore: ['.*']\n }\n]),\n```\n\nAnd copied all files inside the static folder to make it available on both dev and build.\n\nI'd like to do the same via Vite but can't figure out what how to implement it.\n\nI tried the following code but it didn't work.\n\n```\nviteStaticCopy({\n targets: [\n {\n src: path.resolve(__dirname, '../static'),\n dest: '/'\n }\n ]\n})\n```\n\n========================================\n\nCode:\n```text\n- src/\n - static/\n - tests/\n```\n\n```js\nnew CopyWebpackPlugin([\n  {\n    from: path.resolve(__dirname, '../static'),\n    to: '',\n    ignore: ['.*']\n  }\n]),\n```\n\n```js\nviteStaticCopy({\n  targets: [\n    {\n      src: path.resolve(__dirname, '../static'),\n      dest: '/'\n    }\n  ]\n})\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport { viteStaticCopy } from 'vite-plugin-static-copy'\nimport path from 'path'\n\nexport default defineConfig({\n  plugins: [\n    viteStaticCopy({\n      targets: [\n        {\n          src: path.resolve(__dirname, './static') + '/[!.]*', // 1️⃣\n          dest: './', // 2️⃣\n        },\n      ],\n    }),\n  ]\n})\n```\n\n```text\nCopyWebpackPlugin\n```\n\n```text\nvite-plugin-static-copy\n```\n\n```text\nignore\n```\n\n```text\nsrc\n```\n\n```text\ndest\n```\n\n```text\n'./'\n```\n\n```text\ndist\n```\n\n========================================\n\nComments:\n- This answer doesn't appear to answer the OP's question of how to handle copying files in dev. Even in the demo provided, the console reads that the files are collected by are not copied over until a build is ran.\n- This worked for me, although on Windows, I had to use `normalizePath`, e.g. `src: normalizePath(path.resolve(__dirname, \"lib&#47;scss\") + \"&#47;*.scss\"),` to make it work. This is mentioned in the docs of npmjs.com/package/vite-plugin-static-copy","metadata":{"transformedAt":"2026-08-18T18:33:46.397Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":124,"estimatedTokens":534}}78{"id":"stack-71534594","source":"stackoverflow","questionId":71534594,"title":"Change Vite proxy location automatically in dev vs prod builds?","tags":["typescript","devops","http-proxy","vite"],"text":"Title: Change Vite proxy location automatically in dev vs prod builds?\nTags: typescript, devops, http-proxy, vite\nSource: Stack Overflow\n\nQuestion:\nIn my single page application I'm developing I'm using Vite and in my `vite.config.ts` file I have the following proxy:\n\n```\nproxy: {\n '/v1': {\n target: 'https://127.0.0.1:8080',\n changeOrigin: true,\n secure: false\n }\n}\n```\n\nIs there a way to change this target depending on whether it is in the production environment? Something like:\n\n```\nproxy: {\n '/v1': {\n target: isDev ? 'https://127.0.0.1:8080' : 'https://api.example.com',\n changeOrigin: isDev,\n secure: !isDev\n }\n}\n```\n\nThat is, in my local environment I want to develop against my local server, such that my fetch API calls like `fetch(\"/v1/get-posts\")` get forwarded to `https://127.0.0.1:8080/v1/get-posts`, but in my production build (which I create via `vite build`), they will instead be forwarded to: `https://api.example.com/v1/get-posts`\n\nCan this be done, and if so, how?\n\n========================================\n\nTop Answer:\nUnlike **create-react-app**, **Vite** does not provide the proxying configurations after the build, but only for development.\n\nSo, in order to support the build, you have to manually check for the environment variable to see if you're in production or development as follows:\n\nfor example, this is the baseUrl property in redux-toolkit-query, or fetch(), or even axios(), whatever you're using\n\n```\n// for example, this is the baseUrl property in redux-toolkit-query, or fetch(), or even axios(), whatever you're using\nimport.meta.env.MODE === 'development' ? `api/v1` : HOST + '/v1'\n```\n\nAssuming this is your vite.config.js file (as an example, it doesn't have to be exactly like mine):\n\n```\nprocess.env = { ...process.env, ...loadEnv(mode, process.cwd()) }\nreturn defineConfig({\n plugins: [react()],\n server: {\n proxy: {\n '/api': {\n target: process.env.VITE_mainAPI_host,\n changeOrigin: true,\n rewrite: (path) => path.replace(/^\\/api/, ''),\n```\n\n========================================\n\nCode:\n```text\nproxy: {\n  '/v1': {\n    target: 'https://127.0.0.1:8080',\n    changeOrigin: true,\n    secure: false\n  }\n}\n```\n\n```text\nproxy: {\n  '/v1': {\n    target: isDev ? 'https://127.0.0.1:8080' : 'https://api.example.com',\n    changeOrigin: isDev,\n    secure: !isDev\n  }\n}\n```\n\n```text\nvite.config.ts\n```\n\n```text\nfetch(\"/v1/get-posts\")\n```\n\n```text\nhttps://127.0.0.1:8080/v1/get-posts\n```\n\n```text\nvite build\n```\n\n```text\nhttps://api.example.com/v1/get-posts\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport { fileURLToPath } from 'url'\nimport vue from '@vitejs/plugin-vue'\n\nconst defaultConfig = {\n  plugins: [vue()],\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url))\n    }\n  }\n}\n\nexport default defineConfig(({ command, mode }) => {\n  if (command === 'serve') {\n            👇\n    const isDev = mode === 'development'\n\n    return {\n      ...defaultConfig,\n      server: {\n        proxy: {\n          '/v1': {\n            target: isDev ? 'https://127.0.0.1:8080' : 'https://api.example.com',\n            changeOrigin: isDev,\n            secure: !isDev\n          }\n        }\n      }\n    }\n  } else {\n    return defaultConfig\n  }\n})\n```\n\n```text\nmode\n```\n\n```text\nisDev\n```\n\n```text\nmode === 'development'\n```\n\n```js\n// for example, this is the baseUrl property in redux-toolkit-query, or fetch(), or even axios(), whatever you're using\nimport.meta.env.MODE === 'development' ? `api/v1` : HOST + '/v1'\n```\n\n```js\nprocess.env = { ...process.env, ...loadEnv(mode, process.cwd()) }\nreturn defineConfig({\n    plugins: [react()],\n    server: {\n      proxy: {\n        '/api': {\n          target: process.env.VITE_mainAPI_host,\n          changeOrigin: true,\n          rewrite: (path) => path.replace(/^\\/api/, ''),\n```\n\n```text\nserver: { proxy: {} }\n```\n\n```text\naxios.defaults.baseURL = isDev ? 'DEV_URL' : 'PROD_URL'\n```\n\n========================================\n\nComments:\n- @JamesP Indeed, hosting the Vite server might not be recommended in some production environments. Setting up a proxy can be done in many ways, but the solution you pick will likely depend on how your app is hosted. If you don't have control of the host or proxy settings (e.g., hosting on GitHub), you can't setup your own proxy on that host. Otherwise, if you're on a custom server, you could setup just about any proxy server (e.g., nginx, express, koa, etc.) adjacent to your app.","metadata":{"transformedAt":"2026-08-18T18:33:46.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":183,"estimatedTokens":1113}}79{"id":"stack-76264731","source":"stackoverflow","questionId":76264731,"title":"Multiple entry points in Vite for dev server mode?","tags":["vite"],"text":"Title: Multiple entry points in Vite for dev server mode?\nTags: vite\nSource: Stack Overflow\n\nQuestion:\nIs it possible to get multiple html entry points to work in Vite when running it as a dev server (with `vite --host`)? I'm currently using this post's solution Multiple entry points in Vite, but it only works for when building the site to a `dist` folder.\n\n========================================\n\nCode:\n```text\nvite --host\n```\n\n```text\ndist\n```\n\n```text\n├── package.json\n├── vite.config.js\n├── index.html\n├── main.js\n└── nested\n    ├── index.html\n    └── nested.js\n```\n\n========================================\n\nComments:\n- Also, it turns out the trailing slash is important. Navigating to `&#47;nested` didn't work for me, but `&#47;nested&#47;` worked.\n- Yeah, me too. I face same thing, trailing slash is important.","metadata":{"transformedAt":"2026-08-18T18:33:46.397Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":33,"estimatedTokens":206}}80{"id":"stack-70682803","source":"stackoverflow","questionId":70682803,"title":"Typescript errors when using a suffix (?raw, ?url etc","tags":["typescript","vite"],"text":"Title: Typescript errors when using a suffix (?raw, ?url etc\nTags: typescript, vite\nSource: Stack Overflow\n\nQuestion:\nI get a typescript error in my vite project when I try to import an SVG with a suffix (?component). How can I configure typescript to ignore these suffixes?\n\n`TS2307: Cannot find module './desktop-mark.svg?component' or its corresponding type declarations.`\n\n```\nimport DesktopLogoMark from './desktop-mark.svg?component';\n```\n\n========================================\n\nCode:\n```text\nimport DesktopLogoMark from './desktop-mark.svg?component';\n```\n\n```text\nTS2307: Cannot find module './desktop-mark.svg?component' or its corresponding type declarations.\n```\n\n```text\ndeclare module \"*?raw\"\n{\n    const content: string;\n    export default content;\n}\n```\n\n```text\ndeclarations.d.ts\n```\n\n========================================\n\nComments:\n- Why do you need the suffix?\n- This was the only way I could get the SVG imports to work. Here is the post: stackoverflow.com/questions/70309561/&hellip;\n- See: vitejs.dev/guide/features.html#client-types\n- 🙏 thanks, this works: ``` declare module \"*?component\" { const content: string; export default content; } ```","metadata":{"transformedAt":"2026-08-18T18:33:46.398Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":43,"estimatedTokens":294}}81{"id":"stack-77022419","source":"stackoverflow","questionId":77022419,"title":"How is browser able to use typescript file directly in Vite index.html?","tags":["javascript","html","node.js","typescript","vite"],"text":"Title: How is browser able to use typescript file directly in Vite index.html?\nTags: javascript, html, node.js, typescript, vite\nSource: Stack Overflow\n\nQuestion:\nRecently I've been playing around with Vite. One thing that intrigues me is that it's ability to use typescript file directly in the index.html, e.g.\n\n```\n\n```\n\nFrom the docs, I understand that Vite will transpile the original code from Typescript into Javascript (I inspected that the contents of `main.ts` are indeed transformed). But how can the browser run the Javascript code inside a `*.ts` file?\n\nI tried to replicate it by creating a simple static server with an `index.html` containing the script tag like above. Yet, the browser will throw an error:\n\n```\nFailed to load module script: Expected a JavaScript module script but the server responded with a MIME type of \"video/mp2t\". Strict MIME type checking is enforced for module scripts per HTML spec.\n```\n\nSo how is this possible with Vite?\n\n========================================\n\nTop Answer:\nEDIT: The accepted answer is actually correct, as OP wasn't wondering what Vite does during *Production* builds but rather *Development* builds, which is that *Development* serves the transpiled results from memory (modifying `Content-Type` headers to server the right filetype, overriding file extensions hinting as necessary) while *Production* persistently changes URLs in generated artifacts.\n\nMy answer below explains what happens with Vite inputs during final, *Production*-mode transpilations, while the accepted answer explains how Vite gets away with transpiling files in-memory and modifying content headers to serve the in-memory transpiled files during *Development*-mode.\n\nUnless I'm misunderstanding something, I think the answer that has been accepted doesn't actually match what was being questioned. I think the OP is wondering how you can refer to a \"TypeScript\" file in a Vite project's HTML root file (`index.html`) in order to transpile and run the referenced TypeScript code. An example being:\n\n```\n\n```\n\nTL;DR is that the browser never runs TypeScript code -- Vite transforms the URL above into something like:\n\n```\n\n```\n\n...how can the browser run the Javascript code inside a *.ts file?\n\nIt (fortunately) doesn't have to. You partially answered your own question here:\n\n...Vite will transpile the original code from Typescript into Javascript.\n\nThe browser is *not* being served raw TypeScript directly. Not only does Vite transform your assets, it also transforms your `index.html`'s links to any other external resources.\n\nTry running `npm run build` or `vite build`, and then visit your output directory and inspect the generated `index.html` file yourself.\n\nA \"JavaScript-first\" module bundler (like Webpack) creates a \"dependency graph\" of your modules. Basically, you provide an entry point, and the bundler traverses all imports (recursively) and does fancy things (i.e. bundling, tree-shaking, and any other transformation).\n\nVite, on the other hand, is what I'd call an \"HTML-first\" bundler. Where Webpack would opt to use JavaScript files (and sometimes other files) as entry points, Vite allows for HTML files to be an entry point. The same thing happens here, with the difference that instead of JavaScript imports, Vite instead traverses things like a `link` tag's `href` attribute, or an `img` tag's `src` attribute.\n\nIn both cases, once asset bundling and transformation has occurred, the dependency graph generally looks different -- and file types themselves may have changed. For example, multiple files merged together would no longer require multiple imports, and TypeScript files may now be JavaScript files. Bundlers account for that by dynamically changing import URLs and strategy based on the context.\n\nHope that helps!\n\n========================================\n\nCode:\n```html\n<script type=\"module\" src=\"/src/main.ts\"></script>\n```\n\n```text\nFailed to load module script: Expected a JavaScript module script but the server responded with a MIME type of \"video/mp2t\". Strict MIME type checking is enforced for module scripts per HTML spec.\n```\n\n```text\nmain.ts\n```\n\n```text\n*.ts\n```\n\n```text\nindex.html\n```\n\n```text\n*.ts\n```\n\n```text\nContent-Type: text/javascript\n```\n\n```html\n<script type=\"module\" src=\"./index.ts\"></script>\n```\n\n```html\n<script type=\"module\" src=\"/index.[content_hash].js\"></script>\n```\n\n```text\nContent-Type\n```\n\n```text\nindex.html\n```\n\n```text\nindex.html\n```\n\n```text\nnpm run build\n```\n\n```text\nvite build\n```\n\n```text\nindex.html\n```\n\n```text\nlink\n```\n\n```text\nhref\n```\n\n```text\nimg\n```\n\n```text\nsrc\n```\n\n========================================\n\nComments:\n- The accepted answer addresses my question. Your answer is referring to the condition when Vite bundles for production, where the script url in index.html becomes `index.[content_hash].js`. In dev mode, the script url is still pointing to the `index.ts`. You can try to inspect the script tag in the DOM when you are in the dev server. Vite uses a completely different approach between its dev server (no bundling) and production (with bundling).\n- Ah! You're right! I considered writing a small aside about `mode: development` in Vite, but I didn't read you specifying a mode in your question. I figured it'd be a given that the processes that happen in production happen (almost) exactly the same as they do in development, but, instead of persisting the transpiled results in storage, they only happen *in-memory*. Which is why, as the selected answer pointed out, the `webpack-dev-server` can simply override the `Content-Type` header of what would be a `*.ts` file and instead serve it as a JavaScript file.","metadata":{"transformedAt":"2026-08-18T18:33:46.398Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":142,"estimatedTokens":1415}}82{"id":"stack-74154404","source":"stackoverflow","questionId":74154404,"title":"What does \"~\" (tilde) mean in the import ... from \"~/\"","tags":["javascript","vite"],"text":"Title: What does \"~\" (tilde) mean in the import ... from \"~/\"\nTags: javascript, vite\nSource: Stack Overflow\n\nQuestion:\nI just spotted \"~/\" in some of js imports\n\n```\nimport { Foo, Bar, Baz } from \"~/types/schema\"\n```\n\nThis is mildly confusing because \"~\" usually meant the `$HOME` directory. And for the life of me - I can't google the answer.\n\nThe only answer I found was this What is the ~ (tilde) doing in this javascript import?\ndealing with `import {IDispatch} from '~react-redux~redux';` which uses the tilde sign, but not as in the path `~something` instead of `~/something`)\n\n========================================\n\nCode:\n```js\nimport { Foo, Bar, Baz } from \"~/types/schema\"\n```\n\n```text\n$HOME\n```\n\n```text\nimport {IDispatch} from '~react-redux~redux';\n```\n\n```text\n~something\n```\n\n```text\n~/something\n```\n\n```text\n~\n```\n\n```text\nnode_modules\n```\n\n```text\nresolvealias\n```\n\n```text\n~\n```\n\n```text\nsourceCodeDir\n```\n\n```text\nsourceCodeDir\n```\n\n```text\npaths\n```\n\n========================================\n\nComments:\n- Does this answer your question? What is the ~ (tilde) doing in this javascript import?\n- Thanks for checking, but no, it doesn't. I've seen this answer before. Added a paragraph explaining how it is different.\n- No problem! this might be relevant too\n- Your answer suggests that simply using Webpack or Vite at all would *automatically* resolve `~` to some directory in your project, but that's not correct. The `~` is resolved by an explicit configuration (Webpack's `resolve.alias` or Vite's `resolve.alias`). The alias is **not** \"predefined\" by Webpack like the answer you linked to would indicate. If `~` resolves correctly without your own config, then likely something else in your tech stack (e.g., Vite Ruby, as you've cited in your answer) is configuring the alias.\n- demo - Webpack does not preconfigure path alias\n- demo - Vite does not preconfigure path alias\n- @tony19 thank you for the review, you are right! I updated the answer - please let me know if it's clearer now.\n- @tony19 @Greg Is it `sourceCodeDir` or is it `resolve.alias`??\n- @AlxVallejo It depends on the tool you're using. webpack has one, vite has another. Is the answer not clear on that?","metadata":{"transformedAt":"2026-08-18T18:33:46.398Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":79,"estimatedTokens":549}}83{"id":"stack-79540647","source":"stackoverflow","questionId":79540647,"title":"How to define custom colors and use them in dark, light mode without using :dark?","tags":["reactjs","typescript","tailwind-css","vite","tailwind-css-4"],"text":"Title: How to define custom colors and use them in dark, light mode without using :dark?\nTags: reactjs, typescript, tailwind-css, vite, tailwind-css-4\nSource: Stack Overflow\n\nQuestion:\nI am using **Tailwind CSS v4** and want to define **custom colors** that automatically switch between **light** and **dark** modes. Instead of using the `dark:` prefix for every class, I want to manage color changes through CSS variables in my React project.\n\nHere’s what I’m trying to achieve:\n\n- Define custom colors (e.g., `primary`, `baseColor`, `textColor`).\n\n- Automatically switch these values based on light or dark mode.\n\n- Avoid using `dark:` in every class for better maintainability.\n\nI’ve tried adding CSS variables via `:root` and the `dark` class but want to ensure I’m following best practices for Tailwind v4.\n\nHow can I configure **tailwind.config.ts** and global CSS to achieve this?\n\n========================================\n\nCode:\n```text\ndark:\n```\n\n```text\nprimary\n```\n\n```text\nbaseColor\n```\n\n```text\ntextColor\n```\n\n```text\ndark:\n```\n\n```text\n:root\n```\n\n```text\ndark\n```\n\n```js\ndocument.querySelector('button').addEventListener('click', () => {\n  document.documentElement.classList.toggle('dark');\n});\n```\n\n```html\n<script src=\"https://unpkg.com/@tailwindcss/browser\"></script>\n<style type=\"text/tailwindcss\">\n/* changed the behavior of dark: (default: based on prefers-color-scheme) to work based on the presence of the .dark parent class */\n@custom-variant dark (&:where(.dark, .dark *));\n\n@theme {\n  --color-pink: #eb6bd8;\n}\n\n@layer theme {\n  :root, :host {\n    @variant dark {\n      --color-pink: #8e0d7a;\n    }\n  }\n}\n</style>\n\n<button class=\"size-20 bg-pink dark:text-white\">Click Here</button>\n<div class=\"w-50 h-12 bg-purple-200 dark:bg-purple-900 dark:text-white\">\n  Lorem Ipsum\n</div>\n```\n\n```js\ntailwind.config = {\n  darkMode: 'class', // from v3.4.1 can use 'selector' instead of this\n  theme: {\n    extend: {\n      colors: {\n        pink: 'var(--color-pink)',\n      },\n    },\n  },\n};\n\ndocument.querySelector('button').addEventListener('click', () => {\n  document.documentElement.classList.toggle('dark');\n});\n```\n\n```html\n<script src=\"https://cdn.tailwindcss.com\"></script>\n<style type=\"text/tailwindcss\">\n:root {\n  --color-pink: #eb6bd8;\n}\n\n.dark:root {\n  --color-pink: #8e0d7a;\n}\n</style>\n\n<button class=\"size-20 bg-pink dark:text-white\">Click Here</button>\n<div class=\"w-50 h-12 bg-purple-200 dark:bg-purple-900 dark:text-white\">\n  Lorem Ipsum\n</div>\n```\n\n```text\ndark:\n```\n\n```text\n@variant dark\n```\n\n```text\nbg-pink\n```\n\n```text\n@custom-variant\n```\n\n```text\n@variant\n```\n\n```text\n@theme\n```\n\n```text\ndark:\n```\n\n```text\n.system\n```\n\n```text\ndark:\n```\n\n```text\n.system\n```\n\n```text\n.dark\n```\n\n```text\ndark:\n```\n\n```text\n.dark { ... }\n```\n\n```text\nbg-pink\n```\n\n========================================\n\nComments:\n- Possible duplicated: How to use custom color themes in TailwindCSS v4 - Related: TailwindCSS v4 dark theme by class not working without dark tag\n- How to manually toggle dark mode in TailwindCSS v4\n- Tailwind doesn't overwrite standard CSS (as far as I understand) so you could just use `background-color: light-dark(var(--bg-light), var(--bg-dark));`\n- This approach makes us use the namespace, e.g. as you have `--color-pink`. But what if I want to have utility class like `button-background-color`. If I use the suggested approach I will have to do: `--color-button-background-color`. But then this will also become available as `text-button-background-color` right? (due to namespaces). Which does not make much sense, does it? i.e. to have text color named as background color.\n- Yes. Although I like the new concept, many people prefer usage-based naming, and in those cases it does make sense that the color shouldn't work across different utilities (text, bg, etc.). In v4, there is an undocumented but working feature that allows the color only within the desired utility: github.com/tailwindlabs/tailwindcss.com/pull/2247\n- But what would be the official (documented) way if I want to use approach like I mentioned e.g. `button-background-color` (without it affecting other utility classes like text) and then also override it for dark theme?\n- Basically, you could create a custom `button-*` utility where you declare your own unique namespace and list all its properties; you can also define the dark variant there. The answer would be a bit long to explain in a comment - maybe I can a playground instead. --- UP --- I was a bit overzealous - this would probably require an additional plugin as well: play.tailwindcss.com/NvurAtvsJC?file=css\n- The idea of declaring namespaces sounded good in my head, but unfortunately, it's not possible to assign different values to multiple properties. Maybe the functionality could be extended with a plugin. In the meantime, you can declare your own utilities - although it seems like quite a bit of work: play.tailwindcss.com/nVw4kmzEoM?file=css\n- Thanks but in your last example, why did you put `button-background-color` under `theme` you did not use any namespace did you?\n- The variable is declared - it's nothing more than a `:root` variable for now. You're right, maybe it's a bit over the top; I just modified the original code. Yes, until there’s a way to assign different CSS properties under the `--button-*` namespace value, it sounds like an unnecessary declaration. play.tailwindcss.com/F5nHpuQDRO?file=css (UP)\n- I decided to explore this topic a little bit further, I think you might be interested here, and in the response the person suggests we should wrap the `@variant dark` inside `*{...}` which this answer does not have.\n- I think you gave me a good review. I also highlighted this version in another reply. I believe using the theme layer is a more refined way to achieve the goal.\n- do you plan to update your answer with the solution you provided in the comment before your last comment? It might be useful to some. I have used it here, though it seems I have to use the @utility separately for each class right (the way I have it)?\n- @gmoniava Yes, thank you for bringing it to my attention again. I definitely want to include it in the answer. I think I'll write the necessary update today.\n- @gmoniava - I tried to capture the essence of your example, where instead of the usual `--property-name` or `--utility-property-name` structure, you wanted to create a configuration using the `--component-name-property` pattern. I believe this deviates quite a bit from the main focus of the current question - and from TailwindCSS's core concept, which might be confusing for beginners - enough that I'll address it in a separate question. You can check it out here: stackoverflow.com/q/79690477/15167500 - If you want, feel free to write your own answer or edit it in.\n- Just note. I would love to see some special syntax implemented via a plugin that could extend the usage of `--value` better, so fewer utilities would need to be written. e.g.: Example#1 or Example#2\n- Related: In v3, using `:root` was sufficient - so from v4 why do I now need to use both `@theme` and `@layer theme`? - `@theme` vs `@layer theme` vs `:root`\n- Related: Should I use `@theme` or `@theme inline`?","metadata":{"transformedAt":"2026-08-18T18:33:46.398Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":25,"totalLines":193,"estimatedTokens":1798}}84{"id":"stack-72071621","source":"stackoverflow","questionId":72071621,"title":"Vite preview is working but I can not see it running when opening index.html","tags":["javascript","html","es6-modules","vite"],"text":"Title: Vite preview is working but I can not see it running when opening index.html\nTags: javascript, html, es6-modules, vite\nSource: Stack Overflow\n\nQuestion:\nI dont know if I'm doint it wrong here, but I started a vanilla.js project with vite, I did my code, and everything is working with: `npm run dev` (which runs `vite` command).\n\nBut when I run `npm run build` and I open `/dist/index.html` the page is not working.\n\nProbably I'm doing something wrong.\n\nI know that when I run `npm run build && npm run preview` it works. But I'm trying to make it work by only opening the `index.html` file, because AFAIK, that's the only way I could host it on Github pages.\n\n========================================\n\nTop Answer:\nI added this on my `vite.config.js`.\n\n\r\n\r\n\n```\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n base: './'\n});\n```\n\n\r\n\r\n\r\n\nIt happens becouse our navigator doesnt recognize the path `/heres-the-file-or-paths` so i needed to add the `./` at the beginning of our path when are importing `.js` and `.css` files. The same for icons and others.\n\nThis makes that the build process ends with and `index.html` like this with our imports paths working. `href=\"./the-rest-of-the-path-here\"`\n\n\r\n\r\n\n```\n\n \n \n \n \n Vite + React\n \n \n \n \n \n \n \n\n```\n\n\r\n\r\n\r\n\nI hope this can help you.\n\n========================================\n\nCode:\n```text\nnpm run dev\n```\n\n```text\nvite\n```\n\n```text\nnpm run build\n```\n\n```text\n/dist/index.html\n```\n\n```text\nnpm run build && npm run preview\n```\n\n```text\nindex.html\n```\n\n```js\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n  base: '/roulette-simulation/'\n});\n```\n\n```text\nvite.config.js\n```\n\n```js\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n  base: './'\n});\n```\n\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n    <head>\n        <meta charset=\"UTF-8\" />\n        <link rel=\"icon\" type=\"image/svg+xml\" href=\"./vite.svg\" />\n        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n        <title>Vite + React</title>\n        <script type=\"module\" crossorigin src=\"./assets/index.b3824f6c.js\"></script>\n        <link rel=\"stylesheet\" href=\"./assets/index.3fce1f81.css\">\n    </head>\n    <body>\n        <div id=\"root\"></div>\n        \n    </body>\n</html>\n```\n\n```text\nvite.config.js\n```\n\n```text\n/heres-the-file-or-paths\n```\n\n```text\n./\n```\n\n```text\n.js\n```\n\n```text\n.css\n```\n\n```text\nindex.html\n```\n\n```text\nhref=\"./the-rest-of-the-path-here\"\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm run preview\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\nimport { fileURLToPath, URL } from 'node:url'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue()],\n  // base: './',         // works, but can clash with createWebHistory\n  // base: '/',          // if the app is in root directory\n  base: '/webamy-app/',  // if the app is in sub path\n})\n```\n\n```text\n...\nconst router = createRouter({\n    // history: createWebHistory(),\n    history: createWebHistory(import.meta.env.BASE_URL),\n    routes,\n})\n```\n\n```text\nhttps://example.com/webamy-app/\n```\n\n```text\nhttps://example.com/\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport { viteSingleFile } from \"vite-plugin-singlefile\";\n\n// https://vite.dev/config/\nexport default defineConfig({\n  plugins: [react(), viteSingleFile({ removeViteModuleLoader: true })],\n  build: {\n    minify: true,\n  },\n});\n```\n\n========================================\n\nComments:\n- You need a server to serve the `index.html`. That's what `npm run preview` does for you. You don't need to be able to open your `index.html` without a server for it to run on GitHub pages.\n- Thanks @tony19. I was missing the vite.config file.. Now its working as expected.\n- Please consider adding an explanation about how it is different than the accepted own-answer.\n- I tryed the accepted own-answer, but it doesnt workt to me. Testing by myself adding `base` prop to the vite.config file i mannaged to get this solution. i had to add the specific base path `.&#47;` becouse adding something like `&#47;testing-folder&#47;` or `&#47;` i kept getting the same error `cannot found the module index.something.js` what was in the assets folder after the build.\n- Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made.","metadata":{"transformedAt":"2026-08-18T18:33:46.398Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":218,"estimatedTokens":1164}}85{"id":"stack-75236041","source":"stackoverflow","questionId":75236041,"title":"vite: use \"keep-names\" esbuild flag for production build","tags":["vite","minify","esbuild","terser"],"text":"Title: vite: use \"keep-names\" esbuild flag for production build\nTags: vite, minify, esbuild, terser\nSource: Stack Overflow\n\nQuestion:\none of our third party libraries requires us to preserve specific function names. in webpack we did that with `terser.keep_fnames`. esbuild has https://esbuild.github.io/api/#keep-names so we'd like to use that but we cannot find how to enable this option for a vite production build.\n\naccording to the docs esbuild is used for minification. how do we enable this flag (or a comparable option)? note that we'd like to not use terser, as its much slower than esbuild.\n\nthere is an undocumented `config.esbuild` prop. that seems to be used in the current master code:\nhttps://github.com/vitejs/vite/blob/f72fdc7c995db502ca89f0057cfc1fcd6660212f/packages/vite/src/node/plugins/esbuild.ts#L352\n\nbut when i tried adding `config.esbuild.keepNames` to the config object (as object fields of course) it didnt do anything.\n\n========================================\n\nTop Answer:\n```\nesbuild: {\n minifyIdentifiers: false\n},\n```\n\nseems to have done it for me\n\n========================================\n\nCode:\n```text\nterser.keep_fnames\n```\n\n```text\nconfig.esbuild\n```\n\n```text\nconfig.esbuild.keepNames\n```\n\n```js\nesbuild: {\n    minifyIdentifiers: false,\n    keepNames: true,\n  },\n```\n\n```js\n//doesnt work\n  await viewer.model\n    .getPropertyDb()\n    .executeUserFunction(function userFunction() { ... }, {\n      dbIds,\n      propertyNames,\n      includeRevitCategory,\n    });\n\n// works\n  function userFunction() {\n    // ...\n  }\n  await viewer.model\n    .getPropertyDb()\n    .executeUserFunction(userFunction, {\n      dbIds,\n      propertyNames,\n      includeRevitCategory,\n    });\n```\n\n```js\nbuild: {\n    minify: 'terser',\n    terserOptions: {\n      mangle: {\n        reserved: ['userFunction'],\n      },\n    },\n```\n\n```text\nuserFunction\n```\n\n```text\nterser\n```\n\n```text\nkeep_fnames: true\n```\n\n```text\nterserOptions\n```\n\n```text\ndefineConfig\n```\n\n```text\nuserFunction\n```\n\n```text\nuserFunction\n```\n\n```text\nterser\n```\n\n```text\nvite.config\n```\n\n```text\nnpm add -D terser\n```\n\n```text\nesbuild: {\n    minifyIdentifiers: false\n},\n```\n\n========================================\n\nComments:\n- Using minify: \"terser\" with terserOptions worked for me, as well.","metadata":{"transformedAt":"2026-08-18T18:33:46.398Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":130,"estimatedTokens":569}}86{"id":"stack-67407879","source":"stackoverflow","questionId":67407879,"title":"registering socket IO to vite for sveltekit","tags":["javascript","socket.io","svelte","vite","sveltekit"],"text":"Title: registering socket IO to vite for sveltekit\nTags: javascript, socket.io, svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have written a few apps using svelte and sapper and thought I would give sveltekit a go.\nAll in all it works, but I am now running into the issue of registering a worker on ther server.\n\nBasically I am trying to add socket.io to my app because I want to be able to send and receive data from the server. With sapper this wasn't really an issue because you had the `server.js` file where you could connect socket.io to the polka/express server. But I cannot find any equivalent in sveltekit and vite.\n\nI experimented a bit and I can create a new socket.io server in a route, but that will lead to a bunch of new problems, such as it being on a separate port and causing cors issues.\n\nSo I am wondering is this possible with sveltekit and how do you get access to the underlying server?\n\n========================================\n\nTop Answer:\nThe @sveltejs/adapter-node also builds express/polka compatible middleware which is exposed as `build/middelwares.js` which you can import into a custom `/server.cjs`:\n\n```\nconst {\n assetsMiddleware,\n prerenderedMiddleware,\n kitMiddleware,\n} = require(\"./build/middlewares.js\");\n\n... \n\napp.use(assetsMiddleware, prerenderedMiddleware, kitMiddleware);\n```\n\nThe node adaptor also has an entryPoint option, which allows bundling the custom server into the build, but I ran into issues using this approach.\n\nAdapters are not used during development (aka `npx svelte-kit dev`).\n\nBut using the `svelte.config.js` you're able to inject socket.io into the vite server:\n\n```\n...\n kit: {\n ...\n vite: {\n plugins: [\n {\n name: \"sveltekit-socket-io\",\n configureServer(server) {\n const io = new Server(server.httpServer);\n ...\n },\n },\n ],\n },\n },\n```\n\n**Note:** the dev server needs to be restarted to apply changes in the server code.\n\nYou could use entr to automate that.\n\n========================================\n\nCode:\n```text\nserver.js\n```\n\n```js\nconst {\n  assetsMiddleware,\n  prerenderedMiddleware,\n  kitMiddleware,\n} = require(\"./build/middlewares.js\");\n\n... \n\napp.use(assetsMiddleware, prerenderedMiddleware, kitMiddleware);\n```\n\n```js\n...\n  kit: {\n    ...\n    vite: {\n      plugins: [\n        {\n          name: \"sveltekit-socket-io\",\n          configureServer(server) {\n            const io = new Server(server.httpServer);\n            ...\n          },\n        },\n      ],\n    },\n  },\n```\n\n```text\nbuild/middelwares.js\n```\n\n```text\n/server.cjs\n```\n\n```text\nnpx svelte-kit dev\n```\n\n```text\nsvelte.config.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.398Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":111,"estimatedTokens":646}}87{"id":"stack-74168824","source":"stackoverflow","questionId":74168824,"title":"Vite not prepending base path to anything in public directory","tags":["javascript","html","reactjs","typescript","vite"],"text":"Title: Vite not prepending base path to anything in public directory\nTags: javascript, html, reactjs, typescript, vite\nSource: Stack Overflow\n\nQuestion:\nI have a simple Vite project using React and TypeScript. The deployment target is GitLab pages. The GitLab pages URL is like so: `https://.gitlab.io/` so in `vite.config.ts` I have to set `base: \"//\"` like so:\n\n`vite.config.ts`\n\n```\nimport { build, defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n base: \"/vite-ts-test/\" // (my project is called `vite-ts-test` as shown above)\n\nEverything works (the base URL is prepended to everything) except for anything in my root projects `/public` directory for static assets.\n\nFor example, I have `vite.svg` (the vite logo) stored in `/public` as a static asset and when built and previewed (`npm run build && npm run preview`) I get this (here's a snippet):\n(note: lines numbered for clarity)\n\n```\n1 \n2 \n3 \n4 \n5 \n6 \n7 \n8 \n```\n\nThe problem is line 3 in the `img` tag `src` attribute, it says `/vite.svg` when the actual path is `/vite-ts-test/vite.svg`.\nLine 6 gets it right, however this is not a static asset and isn't in `/public` in my project.\n\nAny help appreciated, thanks.\n\n========================================\n\nTop Answer:\npath: /public/images/somepic.jpg\n\nI use this in Vite Vue.\n\n```\n\n```\n\nI think in React it should look like this.\n\n```\n\n```\n\n========================================\n\nCode:\n```text\nimport { build, defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  base: \"/vite-ts-test/\" // <---------- base set here\n})\n```\n\n```text\n1 <div>\n2     <a href=\"https://vitejs.dev\" target=\"_blank\">\n3         <img src=\"/vite.svg\" class=\"logo\" alt=\"Vite logo\">\n4     </a>\n5     <a href=\"https://reactjs.org\" target=\"_blank\">\n6         <img src=\"/vite-ts-test/assets/react.35ef61ed.svg\" class=\"logo react\" alt=\"React logo\">\n7     </a>\n8 </div>\n```\n\n```text\nhttps://<username>.gitlab.io/<projectname>\n```\n\n```text\nvite.config.ts\n```\n\n```text\nbase: \"/<projectname>/\"\n```\n\n```text\nvite.config.ts\n```\n\n```text\nvite-ts-test\n```\n\n```text\n/public\n```\n\n```text\nvite.svg\n```\n\n```text\n/public\n```\n\n```text\nnpm run build && npm run preview\n```\n\n```text\nimg\n```\n\n```text\nsrc\n```\n\n```text\n/vite.svg\n```\n\n```text\n/vite-ts-test/vite.svg\n```\n\n```text\n/public\n```\n\n```text\nimport viteImg from \"/vite.svg\"\n\nfunction App() {\n  return (\n      <img src={viteImg} className=\"App-Logo\" alt=\"Logo\">\n  )\n}\n```\n\n```text\nfunction App() {\n  return (\n      <img src=\"/vite.svg\" className=\"App-Logo\" alt=\"Logo\">\n  )\n}```\n```\n\n```text\n<img :src=\"'images/somepic.jpg'\" alt=\"\">\n```\n\n```text\n<img src={'images/somepic.jpg'} alt=\"\">\n```\n\n========================================\n\nComments:\n- Did you end up solving it?","metadata":{"transformedAt":"2026-08-18T18:33:46.398Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":167,"estimatedTokens":722}}88{"id":"stack-70544851","source":"stackoverflow","questionId":70544851,"title":"Why bundle NPM packages if they will be bundled by consuming project?","tags":["javascript","typescript","npm","rollup","vite"],"text":"Title: Why bundle NPM packages if they will be bundled by consuming project?\nTags: javascript, typescript, npm, rollup, vite\nSource: Stack Overflow\n\nQuestion:\nI’m building a TypeScript package to be published on NPM. I’ll be consuming this package in future web development projects likely using Vite. When I build a future website with this module, does it matter if it’s already bundled? Won’t Rollup (used by Vite to build the website) bundle the code regardless of whether the code on NPM is bundled (like in a lib.esm.js file)? Why not just use TSC (TypeScript Compiler) to compile TS to JS for NPM and then let the consuming project (whether Rollup or Webpack or Parcel) bundle it optimizing for the browser?\n\nWhat am I missing that other NPM authors know?\n\nNote, I’m authoring this package as strictly an ESM Module (type: module) so I’m not worrying about CJS.\n\n========================================\n\nCode:\n```text\nmain\n```\n\n```text\nreact-markdown\n```\n\n========================================\n\nComments:\n- Socratic: Why even compile to JS if the consumer is using TypeScript? (e.g. Deno)\n- @jsejcksn, great point. For my use case, I'm bundling this code for the browser so JS is required.\n- @jsejcksn I've been down this path. It was a nightmare. Neither TypeScript nor IDEs cope too well with TypeScript (except for type definitions) in `node_modules`.","metadata":{"transformedAt":"2026-08-18T18:33:46.398Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":28,"estimatedTokens":342}}89{"id":"stack-73180945","source":"stackoverflow","questionId":73180945,"title":"JetStream CSS and JS not working and showing @vite(['resources/css/app.css', 'resources/js/app.js'])","tags":["laravel","vite","laravel-jetstream"],"text":"Title: JetStream CSS and JS not working and showing @vite(['resources/css/app.css', 'resources/js/app.js'])\nTags: laravel, vite, laravel-jetstream\nSource: Stack Overflow\n\nQuestion:\n**I installed livewire ,laravel mix and jetstream on laravel 8. But the Jetsream's css and js is not working and shows a message in header that '*@vite(['resources/css/app.css', 'resources/js/app.js'])*' **\n\nhttps://i.sstatic.net/dKv3v.png\n\n**App.blade.php**\n\n```\ngetLocale()) }}\">\n \n \n \n \n\n {{ config('app.name', 'Laravel') }}\n\n \n \n\n \n @livewireStyles\n\n \n @vite(['resources/css/app.css', 'resources/js/app.js'])\n \n \n \n\n \n @livewire('navigation-menu')\n\n \n @if (isset($header))\n \n \n {{ $header }}\n \n \n @endif\n\n \n \n {{ $slot }}\n \n \n\n @stack('modals')\n\n @livewireScripts\n \n\n```\n\n========================================\n\nTop Answer:\ngo to (`app.blade.php`, `guest.blade.php`) and remove `@vite` like this\n\n```\n@vite(['resources/css/app.css', 'resources/js/app.js']) => Remove this and add following \n\n```\n\n========================================\n\nCode:\n```text\n<html lang=\"{{ str_replace('_', '-', app()->getLocale()) }}\">\n    <head>\n        <meta charset=\"utf-8\">\n        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n        <meta name=\"csrf-token\" content=\"{{ csrf_token() }}\">\n\n        <title>{{ config('app.name', 'Laravel') }}</title>\n\n        <!-- Fonts -->\n        <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap\">\n\n        <!-- Styles -->\n        @livewireStyles\n\n        <!-- Scripts -->\n        @vite(['resources/css/app.css', 'resources/js/app.js'])\n    </head>\n    <body class=\"font-sans antialiased\">\n        <x-jet-banner />\n\n        <div class=\"min-h-screen bg-gray-100\">\n            @livewire('navigation-menu')\n\n            <!-- Page Heading -->\n            @if (isset($header))\n                <header class=\"bg-white shadow\">\n                    <div class=\"max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8\">\n                        {{ $header }}\n                    </div>\n                </header>\n            @endif\n\n            <!-- Page Content -->\n            <main>\n                {{ $slot }}\n            </main>\n        </div>\n\n        @stack('modals')\n\n        @livewireScripts\n    </body>\n</html>\n```\n\n```text\n<!DOCTYPE html>\n<html lang=\"{{ str_replace('_', '-', app()->getLocale()) }}\">\n    <head>\n        <meta charset=\"utf-8\">\n        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n        <meta name=\"csrf-token\" content=\"{{ csrf_token() }}\">\n\n        <title>{{ config('app.name', 'Laravel') }}</title>\n\n        <!-- Fonts -->\n        <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap\">\n\n          <!-- Styles -->\n          <link rel=\"stylesheet\" href=\"{{ asset('css/app.css') }}\">\n          @livewireStyles\n      \n          <!-- Scripts -->\n          <script src=\"{{ asset('js/app.js') }}\" defer></script>\n      \n    </head>\n    <body>\n        <div class=\"font-sans text-gray-900 antialiased\">\n            {{ $slot }}\n        </div>\n        @livewireScripts\n    </body>\n</html>\n```\n\n```text\n<link rel=\"stylesheet\" href=\"{{ asset('css/app.css') }}\">\n    <script src=\"{{ asset('js/app.js') }}\" defer></script>\n    \n    {{-- @vite(['resources/css/app.css', 'resources/js/app.js']) --}}\n```\n\n```text\n\"/js/app.js\": \"/js/app.js\",\n\"/css/app.css\": \"/css/app.css\"\n```\n\n```text\n@vite(['resources/css/app.css', 'resources/js/app.js']) => Remove this and add following \n\n<link rel=\"stylesheet\" href=\"{{ asset('css/app.css') }}\">\n<script src=\"{{ asset('js/app.js') }}\" defer></script>\n```\n\n```text\napp.blade.php\n```\n\n```text\nguest.blade.php\n```\n\n```text\n@vite\n```\n\n```text\nsail restart\n```\n\n```text\n<link rel=\"stylesheet\" href=\"{{ asset('css/app.css') }}\">\n    <script src=\"{{ asset('js/app.js') }}\" defer></script>\n```\n\n```text\nRemoving @vite(['resources/css/app.css', 'resources/js/app.js'])\n```\n\n```text\n[Below Laravel 9]\n```\n\n```text\n'url' => env('APP_URL', 'http://localhost'),\n // 'asset_url' => env('ASSET_URL', '/'),\n 'asset_url' => env('APP_URL', '/'),\n```\n\n```text\nnpm run dev\n```\n\n```text\n<link rel=\"stylesheet\" href=\"/build/assets/app.YOUR_FILE_NAME.css\">\n<script src=\"/build/assets/app.YOUR_FILE_NAME.js\"></script>\n```\n\n```text\n@production\n    @php $path = public_path('build\\assets'); @endphp\n\n@if (file_exists($path))\n    @foreach (scandir($path) as $file)\n        @if (strpos($file, '.css'))\n            <link rel=\"stylesheet\" href=\"{{ asset('build/assets/' . $file) }}\">\n        @endif\n        @if (strpos($file, '.js'))\n            @push('scripts')\n                <script src=\"{{ asset('build/assets/' . $file) }}\"></script>\n            @endpush()\n        @endif\n    @endforeach\n@endif\n@else\n@vite(['resources/css/app.css', 'resources/js/app.js'])\n@endproduction\n```\n\n```text\n@stack('scripts') </body>\n```\n\n========================================\n\nComments:\n- Thanks for the workaround. However, it will be good to know why the @vite directive is not working as expected.\n- by the way why @vite is used ?\n- tnx worked for mine... i think this happens because of using newer versions of Jetstream with an older version of laravel\n- Sorry, after, run php artisan config:clear to reload config settings","metadata":{"transformedAt":"2026-08-18T18:33:46.398Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":241,"estimatedTokens":1320}}90{"id":"stack-72266050","source":"stackoverflow","questionId":72266050,"title":"Vite react proxy sends requests to different endpoints depending on current location","tags":["javascript","node.js","reactjs","vite","node-http-proxy"],"text":"Title: Vite react proxy sends requests to different endpoints depending on current location\nTags: javascript, node.js, reactjs, vite, node-http-proxy\nSource: Stack Overflow\n\nQuestion:\nAfter switch to vite, I am trying to mimic `proxy: \"http://localhost:5000\"` which I previously used in `package.json`\n\nHere is my vite config\n\n```\nexport default defineConfig({\n plugins: [react()],\n server: {\n proxy: {\n \"/api\": {\n target: \"http://localhost:5000\",\n changeOrigin: true,\n secure: false,\n },\n },\n },\n});\n```\n\nI have react app running on port 3000. When I send a request in the root url (`http://localhost:3000`) everything works fine\n\n`const { data } = await axios.get(\"api/user/me\");`\n\n- Well, not really fine. Even though proper data is returned in response, in the console request gets sent to `http://localhost:3000/api/user/me` instead of `http://localhost:5000/api/user/me`. Can anyone explain this behaviour?\n\nThe main problem is that when I navigate to another page (e.g. `http://localhost:3000/dashboard`), then the same request gets sent to `http://localhost:3000/dashboard/api/user/me`.\n\nWhat am I doing wrong? I want to send requests to `http://localhost:5000`, no matter the location\n\nI found a workaround by specifying FE url before every request `const { data } = await axios.get(\"http://localhost:3000/api/user/me\");`, but still is there a way to mimic `package.json` proxy behaviour?\n\n========================================\n\nTop Answer:\nI have same issue and I menage to solve with absolute path in axios call like this: **axios('/api/user/me')**. Before that I configure Vite in vite.config.js like this:\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n//https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n server: {\n proxy: {\n '/api': {\n target: 'http://localhost:5001/',\n changeOrigin: true,\n },\n },\n },\n})\n```\n\nFor some reason my server can't start at port 5000 that's why I set port to 5001.\n\n========================================\n\nCode:\n```js\nexport default defineConfig({\n  plugins: [react()],\n  server: {\n    proxy: {\n      \"/api\": {\n        target: \"http://localhost:5000\",\n        changeOrigin: true,\n        secure: false,\n      },\n    },\n  },\n});\n```\n\n```text\nproxy: \"http://localhost:5000\"\n```\n\n```text\npackage.json\n```\n\n```text\nhttp://localhost:3000\n```\n\n```text\nconst { data } = await axios.get(\"api/user/me\");\n```\n\n```text\nhttp://localhost:3000/api/user/me\n```\n\n```text\nhttp://localhost:5000/api/user/me\n```\n\n```text\nhttp://localhost:3000/dashboard\n```\n\n```text\nhttp://localhost:3000/dashboard/api/user/me\n```\n\n```text\nhttp://localhost:5000\n```\n\n```text\nconst { data } = await axios.get(\"http://localhost:3000/api/user/me\");\n```\n\n```text\npackage.json\n```\n\n```js\naxios.defaults.baseURL = `http://localhost:5000`\n```\n\n```text\nexport const emailApi = axios.create({baseURL: \"http://localhost:<yourPortNumber>\"})\n```\n\n```text\nexpress().use(cors({origin: <viteLocalServer>}))\n```\n\n```text\nemailApi\n```\n\n```text\nemailApi\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n//https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  server: {\n    proxy: {\n      '/api': {\n        target: 'http://localhost:5001/',\n        changeOrigin: true,\n      },\n    },\n  },\n})\n```\n\n```text\n// https://vite.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  server: {\n    proxy: {\n      '/api': {\n        target: 'http://localhost:4000',\n        changeOrigin: true,\n        rewrite: (path) => path.replace(/^\\/api/, ''),\n      },\n    },\n  },\n})\n```\n\n```text\nconst handleSubmit = async (e) => {\n        e.preventDefault();\n        //console.log(data);\n        axios.post('/api/register', data).then((response) => {\n            console.log(response);\n            toast.success(\"Data has been saved successfully\");\n        }).catch((error) => {toast.error(error.response.data)});\n        \n    }\n```\n\n========================================\n\nComments:\n- For your main problem of running the code on a dashboard url or somewhere else, just use an absolute path: `axios.get(\"&#47;api&#47;user&#47;me\")`.\n- \"*in the console request gets sent to `http:&#47;&#47;localhost:3000&#47;api&#47;user&#47;me`*\" - that sounds normal: that's the current origin. I don't know vite, but if that is a **server** configuration, I'd expect the *server* that runs at `localhost:3000` to proxy the request - the client doesn't care.\n- Where do I add this? First time user of VITE\n- I suggest the top-level component (App.tsx | jsx), so that this change takes affect before other components are rendered\n- How is this different to the answer OP already posted almost a year ago? Also, if you're using a reverse-proxy, you don't need CORS\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:46.398Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":198,"estimatedTokens":1253}}91{"id":"stack-76793582","source":"stackoverflow","questionId":76793582,"title":"pnpm & vue & vite monorepo - resolve import of alias path inside a workspace package","tags":["typescript","vue.js","vite","monorepo","pnpm"],"text":"Title: pnpm & vue & vite monorepo - resolve import of alias path inside a workspace package\nTags: typescript, vue.js, vite, monorepo, pnpm\nSource: Stack Overflow\n\nQuestion:\nI'm building a monorepo of UI applications using shared components and style using pnpm, typescript, vue, and vite.\n\nWhile trying to leverage pnpm's workspace ecosystem to ease the development experience and deployment, I'm struggling with using alias paths when importing a package into an app.\n\nThis is my folder structure:\n\n```\nsrc/\n |\n |- apps/\n | |- app1/\n | | |- env/\n | | |- node_modules/\n | | |- src/\n | | | |- plugins/\n | | | | |- some-logic.ts\n | | | |- styles/\n | | | | |- app.scss\n | | | |- views/\n | | | | |- HomeView.vue\n | | | ...\n | | | |- App.vue\n | | | |- main.ts\n | | |\n | | |- index.html\n | | |- package.json\n | | |- tsconfig.json\n | | |- vite.config.ts\n |\n |- packages/\n | |- shared-ui/\n | | |- node_modules/\n | | |- src/\n | | | |- components/\n | | | | |- Header.vue\n | | | |- plugins/\n | | | | |- another-logic.ts\n | | | |- styles/\n | | | | |- header.scss\n | | |- package.json\n | | |- tsconfig.json\n |\n |- node_modules/\n ...\n |- package.json\n |- pnpm-lock.yaml\n |- pnpm-workspace.yaml\n |- tsconfig.base.json\n ...\n |- package.json\n |- pnpm-lock.yaml\n |- pnpm-workspace.yaml\n |- tsconfig.base.json\n```\n\nMy `HomeView.vue` in my application is importing the `Header.vue` component of my shared-ui package:\n\n```\n\n import stuff from '@/plugins/some-logic.ts'\n import Header from '@namespace/shared-ui/src/components/Header.vue';\n \n stuff();\n \n \n \n \n \n \n \n \n \n @import '@/styles/app.scss';\n \n```\n\nAs you can see above, `@/` acts as a path alias for the `src` folder of the application. This works as expected. The problem starts under the `Header` component:\n\n```\n\n import moreStuff from '@/plugins/another-logic.ts' // doesn't work\n \n \n moreStuff();\n \n \n \n \n ...\n \n \n \n \n // @import '@/styles/header.scss'; // doesn't work\n @import '../styles/header.scss'; // works\n \n```\n\nMy guess is since the entry point of vite is `src/apps/app1/`, and in the vite's config, I've created an alias of `@` to `src/`, it's trying to resolve the `@` of the package as well, and leads to wrong import as described below:\n\n```\nimport/no-unresolved Unable to resolve path to module '@/plugins/another-logic.ts'\n import/no-unresolved [vite] Internal server error: [sass] ENOENT: no such file or directory, open '/namespace/apps/app1/src/styles/header.scss'\n```\n\n**root package.json**\n\n```\n{\n \"name\": \"namespace\",\n \"private\": true,\n \"type\": \"module\",\n \"packageManager\": \"pnpm@8.6.9\",\n \"browserslist\": [\n \"> 1%\",\n \"last 2 versions\",\n \"not dead\",\n \"not ie **pnpm-workspace.yaml**\n\n```\npackages:\n - 'apps/*'\n - 'packages/*'\n```\n\n**tsconfig.base.json**\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"es6\",\n \"module\": \"esnext\",\n \"moduleResolution\": \"node\",\n \"esModuleInterop\": true,\n \"isolatedModules\": true,\n \"strict\": true,\n \"jsx\": \"preserve\",\n \"experimentalDecorators\": true,\n \"noEmit\": false,\n \"skipLibCheck\": true,\n \"allowSyntheticDefaultImports\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"useDefineForClassFields\": true,\n \"sourceMap\": true,\n \"lib\": [\n \"esnext\",\n \"dom\",\n \"dom.iterable\",\n \"scripthost\"\n ]\n },\n \"references\": [\n {\n \"path\": \"./packages/shared-ui\"\n }\n ],\n \"exclude\": [\n \"**/node_modules\",\n \"packages/**/dist\"\n ]\n}\n```\n\n**apps/app1/package.json**\n\n```\n{\n \"name\": \"@namespace/app1\",\n \"private\": true,\n \"type\": \"module\",\n \"packageManager\": \"pnpm@8.6.9\",\n \"scripts\": {\n \"serve\": \"vite\"\n },\n \"dependencies\": {\n \"@namespace/shared-ui\": \"workspace:*\",\n \"@vee-validate/zod\": \"~4.10.8\",\n \"axios\": \"~1.4.0\",\n \"pinia\": \"~2.1.4\",\n \"vee-validate\": \"~4.10.8\",\n \"vite-plugin-vuetify\": \"~1.0.2\",\n \"vue\": \"~3.3.4\",\n \"vue-router\": \"~4.2.4\",\n \"vuetify\": \"~3.3.6\",\n \"zod\": \"~3.21.4\"\n },\n \"devDependencies\": {\n \"@vitejs/plugin-vue\": \"~4.2.3\",\n \"sass\": \"~1.64.1\",\n \"vite-tsconfig-paths\": \"~4.2.0\"\n }\n }\n```\n\n**apps/app1/tsconfig.json**\n\n```\n{\n \"extends\": \"../../tsconfig.base.json\",\n \"compilerOptions\": {\n \"baseUrl\": \"./\",\n \"outDir\": \"./dist/\",\n \"paths\": {\n \"@/*\": [\n \"src/*\"\n ]\n },\n \"typeRoots\": [\n \"./node_modules/@types\",\n \"./src/types\"\n ]\n },\n \"include\": [\n \"src/**/*.ts\",\n \"src/**/*.d.ts\",\n \"src/**/*.tsx\",\n \"src/**/*.vue\",\n \"vite.config.ts\"\n ]\n }\n```\n\n**apps/app1/vite.config.ts**\n\n```\nimport { type UserConfigExport, defineConfig } from 'vite';\n import eslint from 'vite-plugin-eslint';\n import vuetify from 'vite-plugin-vuetify';\n import tsconfigPaths from 'vite-tsconfig-paths';\n \n import vue from '@vitejs/plugin-vue';\n \n export default defineConfig(({ mode }) => {\n const isDevelopment = mode === 'development';\n const config: UserConfigExport = {\n root: `${process.cwd()}/`,\n envDir: `${process.cwd()}/env/`,\n plugins: [tsconfigPaths(), eslint(), vue(), vuetify()],\n resolve: {\n alias: {\n '@/': `${process.cwd()}/src/`,\n vue: 'vue/dist/vue.esm-bundler.js'\n }\n }\n };\n \n if (isDevelopment) {\n config.server = {\n host: true,\n port: Number(process.env.PORT)\n };\n }\n \n return config;\n });\n```\n\n**packages/shared-ui/package.json**\n\n```\n{\n \"name\": \"@namespace/shared-ui\",\n \"private\": true,\n \"type\": \"module\",\n \"packageManager\": \"pnpm@8.6.9\",\n \"dependencies\": {\n \"axios\": \"~1.4.0\"\n },\n \"devDependencies\": {\n \"@vee-validate/zod\": \"~4.10.8\",\n \"vee-validate\": \"~4.10.8\",\n \"vue\": \"~3.3.4\",\n \"vuetify\": \"~3.3.6\",\n \"zod\": \"~3.21.4\"\n }\n }\n```\n\n**packages/shared-ui/tsconfig.json**\n\n```\n{\n \"extends\": \"../../tsconfig.base.json\",\n \"compilerOptions\": {\n \"baseUrl\": \"./\",\n \"outDir\": \"./dist/\",\n \"paths\": {\n \"@/*\": [\n \"src/*\"\n ]\n },\n \"typeRoots\": [\n \"./node_modules/@types\",\n \"./src/types\"\n ]\n },\n \"include\": [\n \"src/**/*.ts\",\n \"src/**/*.d.ts\",\n \"src/**/*.tsx\",\n \"src/**/*.vue\"\n ]\n }\n```\n\n========================================\n\nTop Answer:\nmy case with nextJS where\n\n```\n```\n# pnpm-workspace.yaml\npackages:\n - app\n - packages/*\n```\n```\n\nI replaced:\n\n```\n\"@/*\": [\"src/*\"] -> \"@/*\": [\"src/*\"]\n\n and in /app/tsconfig.json added:\n\"@/*\": [\"../packages//src/*\"]\n```\n\nIt should translate to a vue & vite monorepo.\n\n========================================\n\nCode:\n```text\nsrc/\n    |\n    |- apps/\n    |   |- app1/\n    |   |   |- env/\n    |   |   |- node_modules/\n    |   |   |- src/\n    |   |   |   |- plugins/\n    |   |   |   |   |- some-logic.ts\n    |   |   |   |- styles/\n    |   |   |   |   |- app.scss\n    |   |   |   |- views/\n    |   |   |   |   |- HomeView.vue\n    |   |   |   ...\n    |   |   |   |- App.vue\n    |   |   |   |- main.ts\n    |   |   |\n    |   |   |- index.html\n    |   |   |- package.json\n    |   |   |- tsconfig.json\n    |   |   |- vite.config.ts\n    |\n    |- packages/\n    |   |- shared-ui/\n    |   |   |- node_modules/\n    |   |   |- src/\n    |   |   |   |- components/\n    |   |   |   |   |- Header.vue\n    |   |   |   |- plugins/\n    |   |   |   |   |- another-logic.ts\n    |   |   |   |- styles/\n    |   |   |   |   |- header.scss\n    |   |   |- package.json\n    |   |   |- tsconfig.json\n    |\n    |- node_modules/\n    ...\n    |- package.json\n    |- pnpm-lock.yaml\n    |- pnpm-workspace.yaml\n    |- tsconfig.base.json\n    ...\n    |- package.json\n    |- pnpm-lock.yaml\n    |- pnpm-workspace.yaml\n    |- tsconfig.base.json\n```\n\n```js\n<script setup lang=\"ts\">\n    import stuff from '@/plugins/some-logic.ts'\n    import Header from '@namespace/shared-ui/src/components/Header.vue';\n    \n    stuff();\n    </script>\n    \n    <template>\n        <div class=\"container\">\n            <Header />\n        </div>\n    </template>\n    \n    <style lang=\"scss\">\n    @import '@/styles/app.scss';\n    </style>\n```\n\n```js\n<script setup lang=\"ts\">\n    import moreStuff from '@/plugins/another-logic.ts' // doesn't work\n    \n    \n    moreStuff();\n    </script>\n    \n    <template>\n        <div class=\"header\">\n            ...\n        </div>\n    </template>\n    \n    <style lang=\"scss\">\n    // @import '@/styles/header.scss'; // doesn't work\n    @import '../styles/header.scss'; // works\n    </style>\n```\n\n```bash\nimport/no-unresolved    Unable to resolve path to module '@/plugins/another-logic.ts'\n    import/no-unresolved    [vite] Internal server error: [sass] ENOENT: no such file or directory, open '/namespace/apps/app1/src/styles/header.scss'\n```\n\n```json\n{\n      \"name\": \"namespace\",\n      \"private\": true,\n      \"type\": \"module\",\n      \"packageManager\": \"pnpm@8.6.9\",\n      \"browserslist\": [\n        \"> 1%\",\n        \"last 2 versions\",\n        \"not dead\",\n        \"not ie <= 11\"\n      ],\n      \"devDependencies\": {\n        \"@types/node\": \"~20.3.3\",\n        \"@typescript-eslint/eslint-plugin\": \"~5.61.0\",\n        \"@typescript-eslint/parser\": \"~5.61.0\",\n        \"eslint\": \"~8.44.0\",\n        \"eslint-config-prettier\": \"~8.8.0\",\n        \"eslint-import-resolver-typescript\": \"~3.5.5\",\n        \"eslint-plugin-import\": \"~2.27.5\",\n        \"eslint-plugin-prettier\": \"~4.2.1\",\n        \"eslint-plugin-vue\": \"~9.15.1\",\n        \"prettier\": \"~2.8.8\",\n        \"ts-node\": \"~10.9.1\",\n        \"typescript\": \"~5.1.6\",\n        \"vite\": \"~4.3.9\",\n        \"vite-plugin-eslint\": \"~1.8.1\",\n        \"vue-eslint-parser\": \"~9.3.1\"\n      }\n    }\n```\n\n```yaml\npackages:\n      - 'apps/*'\n      - 'packages/*'\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"target\": \"es6\",\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"esModuleInterop\": true,\n    \"isolatedModules\": true,\n    \"strict\": true,\n    \"jsx\": \"preserve\",\n    \"experimentalDecorators\": true,\n    \"noEmit\": false,\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"useDefineForClassFields\": true,\n    \"sourceMap\": true,\n    \"lib\": [\n      \"esnext\",\n      \"dom\",\n      \"dom.iterable\",\n      \"scripthost\"\n    ]\n  },\n  \"references\": [\n    {\n      \"path\": \"./packages/shared-ui\"\n    }\n  ],\n  \"exclude\": [\n    \"**/node_modules\",\n    \"packages/**/dist\"\n  ]\n}\n```\n\n```json\n{\n      \"name\": \"@namespace/app1\",\n      \"private\": true,\n      \"type\": \"module\",\n      \"packageManager\": \"pnpm@8.6.9\",\n      \"scripts\": {\n        \"serve\": \"vite\"\n      },\n      \"dependencies\": {\n        \"@namespace/shared-ui\": \"workspace:*\",\n        \"@vee-validate/zod\": \"~4.10.8\",\n        \"axios\": \"~1.4.0\",\n        \"pinia\": \"~2.1.4\",\n        \"vee-validate\": \"~4.10.8\",\n        \"vite-plugin-vuetify\": \"~1.0.2\",\n        \"vue\": \"~3.3.4\",\n        \"vue-router\": \"~4.2.4\",\n        \"vuetify\": \"~3.3.6\",\n        \"zod\": \"~3.21.4\"\n      },\n      \"devDependencies\": {\n        \"@vitejs/plugin-vue\": \"~4.2.3\",\n        \"sass\": \"~1.64.1\",\n        \"vite-tsconfig-paths\": \"~4.2.0\"\n      }\n    }\n```\n\n```json\n{\n      \"extends\": \"../../tsconfig.base.json\",\n      \"compilerOptions\": {\n        \"baseUrl\": \"./\",\n        \"outDir\": \"./dist/\",\n        \"paths\": {\n          \"@/*\": [\n            \"src/*\"\n          ]\n        },\n        \"typeRoots\": [\n          \"./node_modules/@types\",\n          \"./src/types\"\n        ]\n      },\n      \"include\": [\n        \"src/**/*.ts\",\n        \"src/**/*.d.ts\",\n        \"src/**/*.tsx\",\n        \"src/**/*.vue\",\n        \"vite.config.ts\"\n      ]\n    }\n```\n\n```js\nimport { type UserConfigExport, defineConfig } from 'vite';\n    import eslint from 'vite-plugin-eslint';\n    import vuetify from 'vite-plugin-vuetify';\n    import tsconfigPaths from 'vite-tsconfig-paths';\n    \n    import vue from '@vitejs/plugin-vue';\n    \n    export default defineConfig(({ mode }) => {\n        const isDevelopment = mode === 'development';\n        const config: UserConfigExport = {\n            root: `${process.cwd()}/`,\n            envDir: `${process.cwd()}/env/`,\n            plugins: [tsconfigPaths(), eslint(), vue(), vuetify()],\n            resolve: {\n                alias: {\n                    '@/': `${process.cwd()}/src/`,\n                    vue: 'vue/dist/vue.esm-bundler.js'\n                }\n            }\n        };\n    \n        if (isDevelopment) {\n            config.server = {\n                host: true,\n                port: Number(process.env.PORT)\n            };\n        }\n    \n        return config;\n    });\n```\n\n```json\n{\n      \"name\": \"@namespace/shared-ui\",\n      \"private\": true,\n      \"type\": \"module\",\n      \"packageManager\": \"pnpm@8.6.9\",\n      \"dependencies\": {\n        \"axios\": \"~1.4.0\"\n      },\n      \"devDependencies\": {\n        \"@vee-validate/zod\": \"~4.10.8\",\n        \"vee-validate\": \"~4.10.8\",\n        \"vue\": \"~3.3.4\",\n        \"vuetify\": \"~3.3.6\",\n        \"zod\": \"~3.21.4\"\n      }\n    }\n```\n\n```json\n{\n      \"extends\": \"../../tsconfig.base.json\",\n      \"compilerOptions\": {\n        \"baseUrl\": \"./\",\n        \"outDir\": \"./dist/\",\n        \"paths\": {\n          \"@/*\": [\n            \"src/*\"\n          ]\n        },\n        \"typeRoots\": [\n          \"./node_modules/@types\",\n          \"./src/types\"\n        ]\n      },\n      \"include\": [\n        \"src/**/*.ts\",\n        \"src/**/*.d.ts\",\n        \"src/**/*.tsx\",\n        \"src/**/*.vue\"\n      ]\n    }\n```\n\n```text\nHomeView.vue\n```\n\n```text\nHeader.vue\n```\n\n```text\n@/\n```\n\n```text\nsrc\n```\n\n```text\nHeader\n```\n\n```text\nsrc/apps/app1/\n```\n\n```text\n@\n```\n\n```text\nsrc/\n```\n\n```text\n@\n```\n\n```text\nvite\n```\n\n```text\nrollup\n```\n\n```text\n```\n# pnpm-workspace.yaml\npackages:\n  - app\n  - packages/*\n```\n```\n\n```text\n\"@/*\": [\"src/*\"] -> \"@<package_name>/*\": [\"src/*\"]\n\n and in /app/tsconfig.json added:\n\"@<package_name>/*\": [\"../packages/<package_name>/src/*\"]\n```\n\n========================================\n\nComments:\n- I don't see `plugins` in the file tree\n- If it says `Unable to resolve path to module '@&#47;plugins&#47;another-logic.ts'` show where it is\n- I didn't mention in my question, but I already adjust this solution. Do I have to build @/ui package?","metadata":{"transformedAt":"2026-08-18T18:33:46.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":703,"estimatedTokens":3362}}92{"id":"stack-66732739","source":"stackoverflow","questionId":66732739,"title":"Internationalization for vue 3 vite with i18n","tags":["vue.js","vuex","vuejs3","vite","vue-i18n"],"text":"Title: Internationalization for vue 3 vite with i18n\nTags: vue.js, vuex, vuejs3, vite, vue-i18n\nSource: Stack Overflow\n\nQuestion:\nI'm currently trying to internationalize my vue 3 vite project with \"@intlify/vite-plugin-vue-i18n\". The problem I am facing here, is that i currently have to import and setup the t variable for every component to use it. \n\n**example component:**\n\n```\n\n t('translation')\n\nimport { useI18n } from 'vue-i18n'\nexport default {\n setup(){\n const {t} = useI18n();\n return {t}\n },\n};\n\n```\n\nMy question is, if its possible, what is the best way to make the variable \"t\" global? I cant find any examples/help on this, since they all import it into every component. All help would be appreciated! :)\nFor reference, here are the relevant files.\n\n```\nexport default defineConfig({\n plugins: [\n vue(),\n vueI18n({\n include: path.resolve(__dirname, './src/locales/**')\n })\n ]\n})\n```\n\n**main.ts:**\n\n```\nimport i18n from './i18n';\nconst app = createApp(App);\napp.use(i18n);\napp.mount(\"#app\");\n```\n\n**i18n.js:**\n\n```\nimport { createI18n } from 'vue-i18n'\nimport messages from '@intlify/vite-plugin-vue-i18n/messages'\n\nexport default createI18n({\n legacy: false,\n locale: 'no',\n messages\n})\n```\n\n========================================\n\nTop Answer:\nI have an additional example to show of accessing the global composer instance in vue-i18n **v9**:\n\n*i18n.js*\n\n```\nimport { createI18n } from 'vue-i18n';\nimport en from './locales/en';\nimport fr from './locales/fr';\n\nconst i18n = createI18n({\n legacy: false,\n locale: 'en',\n fallbackLocale: 'en',\n messages: {\n en,\n fr,\n },\n});\n\nexport default i18n;\n```\n\n*main.js*\n\n```\nimport i18n from './i18n.js';\n\n...\n\napp.use(i18n);\n```\n\nThen you can import the instance into any file, such as vue-router's beforeEnter hook or vuex, etc.\n\n```\nimport i18n from '../i18n.js';\n\nconsole.log('i18n', i18n.global);\n\n// to change locale:\ni18n.global.locale.value = 'en';\n```\n\nYou access it via `i18n.global`. it is the same instance that is returned via `useI18n()` from the 'vue-i18n' package.\n\nEDIT: here is my current router.beforeEach function:\n\n```\nconst routes = [\n {\n path: '/',\n redirect: 'lang'\n },\n {\n path: '/:lang',\n name: 'lang',\n component: HomePage,\n },\n {\n path: '/:lang/content/:contentId',\n name: 'guide.content',\n component: () => import('@/views/ContentRoot.vue'),\n children: [\n {\n path: '',\n name: 'guide.content.root',\n component: ContentPage,\n },\n {\n path: 'video',\n name: 'guide.content.video',\n component: ShowVideo,\n },\n ],\n },\n {\n path: '/:catchAll(.*)',\n component: () => import('@/views/404.vue'),\n hidden: true,\n },\n];\n\nrouter.beforeEach((to, from, next) => {\n const locale = to.params.lang; // Retrieve the current locale set in the URL\n\n // Check if the locale the user is trying to access is authorized.\n // In a larger application that supports lots of languages, you may want to store\n // all the locales in a separate array\n if (!['en', 'es'].includes(locale)) {\n return next(i18n.global.locale.value);\n }\n\n // Changing the language from the URL (either manually or with a link) is possible this way\n i18n.global.locale.value = locale;\n\n return next();\n});\n```\n\nand here is my localeswitcher component:\n\n```\n\nimport { watch } from 'vue';\nimport { IonSelect, IonSelectOption } from '@ionic/vue';\nimport { useRoute, useRouter } from 'vue-router';\nimport i18n from '@/i18n';\n\nconst route = useRoute();\nconst router = useRouter();\n\nwatch(() => i18n.global.locale.value, () => {\n router.replace({\n name: route.name,\n params: {\n lang: i18n.global.locale.value,\n },\n });\n});\n\n \n English\n Spanish\n \n\n```\n\nIt's Ionic in this example, but you can easily port that to a `` and ``\n\n========================================\n\nCode:\n```html\n<template>\n  t('translation')\n</template>\n\n<script>\nimport { useI18n } from 'vue-i18n'\nexport default {\n  setup(){\n    const {t} = useI18n();\n    return {t}\n  },\n};\n</script>\n```\n\n```js\nexport default defineConfig({\n  plugins: [\n    vue(),\n    vueI18n({\n      include: path.resolve(__dirname, './src/locales/**')\n    })\n  ]\n})\n```\n\n```js\nimport i18n from './i18n';\nconst app = createApp(App);\napp.use(i18n);\napp.mount(\"#app\");\n```\n\n```js\nimport { createI18n } from 'vue-i18n'\nimport messages from '@intlify/vite-plugin-vue-i18n/messages'\n\nexport default createI18n({\n  legacy: false,\n  locale: 'no',\n  messages\n})\n```\n\n```html\n<template>\n  {{$t('translation')}}\n</template>\n```\n\n```js\nmounted() {\n  console.log(this.$t('translation'))\n}\n```\n\n```js\nimport { createI18n } from 'vue-i18n'\nimport messages from '@intlify/vite-plugin-vue-i18n/messages'\n\nexport default createI18n({\n  legacy: false,\n  locale: 'no',\n  globalInjection: true,\n  messages\n})\n```\n\n```js\n<script>\n\nimport { defineComponent, onMounted, watch } from \"vue\";\nimport { useI18n } from \"vue-i18n\";\nimport { useStore } from \"vuex\";\n\n\nexport default defineComponent({\n  name: \"app\",\n  data() {\n    return {};\n  },\n\n  setup() {\n    const i18n = useI18n();\n    const store = useStore();\n\n    watch(()=>store.getters.currentLang,(newVal) => { //watch the getter\n      i18n.locale.value = store.getters.currentLang;\n    },{\n      immediate:true\n    });\n  },\n});\n</script>\n```\n\n```text\napp.use(i18n)\n```\n\n```text\n$t\n```\n\n```text\nglobalInjection: true,\n```\n\n```text\nApp.vue\n```\n\n```text\nimport { createI18n } from 'vue-i18n';\nimport en from './locales/en';\nimport fr from './locales/fr';\n\nconst i18n = createI18n({\n    legacy: false,\n    locale: 'en',\n    fallbackLocale: 'en',\n    messages: {\n        en,\n        fr,\n    },\n});\n\nexport default i18n;\n```\n\n```text\nimport i18n from './i18n.js';\n\n...\n\napp.use(i18n);\n```\n\n```text\nimport i18n from '../i18n.js';\n\nconsole.log('i18n', i18n.global);\n\n// to change locale:\ni18n.global.locale.value = 'en';\n```\n\n```text\nconst routes = [\n    {\n        path: '/',\n        redirect: 'lang'\n    },\n    {\n        path: '/:lang',\n        name: 'lang',\n        component: HomePage,\n    },\n    {\n        path: '/:lang/content/:contentId',\n        name: 'guide.content',\n        component: () => import('@/views/ContentRoot.vue'),\n        children: [\n            {\n                path: '',\n                name: 'guide.content.root',\n                component: ContentPage,\n            },\n            {\n                path: 'video',\n                name: 'guide.content.video',\n                component: ShowVideo,\n            },\n        ],\n    },\n    {\n        path: '/:catchAll(.*)',\n        component: () => import('@/views/404.vue'),\n        hidden: true,\n    },\n];\n\nrouter.beforeEach((to, from, next) => {\n    const locale = to.params.lang; // Retrieve the current locale set in the URL\n\n    // Check if the locale the user is trying to access is authorized.\n    // In a larger application that supports lots of languages, you may want to store\n    // all the locales in a separate array\n    if (!['en', 'es'].includes(locale)) {\n        return next(i18n.global.locale.value);\n    }\n\n    // Changing the language from the URL (either manually or with a link) is possible this way\n    i18n.global.locale.value = locale;\n\n    return next();\n});\n```\n\n```text\n<script setup>\nimport { watch } from 'vue';\nimport { IonSelect, IonSelectOption } from '@ionic/vue';\nimport { useRoute, useRouter } from 'vue-router';\nimport i18n from '@/i18n';\n\nconst route = useRoute();\nconst router = useRouter();\n\nwatch(() => i18n.global.locale.value, () => {\n    router.replace({\n        name: route.name,\n        params: {\n            lang: i18n.global.locale.value,\n        },\n    });\n});\n</script>\n\n<template>\n    <ion-select v-model=\"$i18n.locale\" class=\"w-20\" aria-label=\"Locale\">\n        <ion-select-option value=\"en\">English</ion-select-option>\n        <ion-select-option value=\"es\">Spanish</ion-select-option>\n    </ion-select>\n</template>\n```\n\n```text\ni18n.global\n```\n\n```text\nuseI18n()\n```\n\n```text\n<select>\n```\n\n```text\n<option>\n```\n\n========================================\n\nComments:\n- How can we change locale when action triggered??\n- I found that you can use `$i18n.locale = 'es'` for example to change to spanish\n- Yes in options api or template you could do that\n- wow i just found this years later and it solved my issue setting up a new project","metadata":{"transformedAt":"2026-08-18T18:33:46.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":445,"estimatedTokens":2036}}93{"id":"stack-76211877","source":"stackoverflow","questionId":76211877,"title":"The xxxx library may need to update its package.json or typings.ts","tags":["reactjs","typescript","vite"],"text":"Title: The xxxx library may need to update its package.json or typings.ts\nTags: reactjs, typescript, vite\nSource: Stack Overflow\n\nQuestion:\nI have a public component library call `rd-component`, when I used this component `\"rd-component\": \"^0.1.47\"` in the new project, the visual studio code show error like this:\n\n```\nCould not find a declaration file for module 'rd-component'. '/Users/John/source/reddwarf/frontend/ppt-web/node_modules/.pnpm/rd-component@0.1.47_@types+node@20.1.1_react-dom@18.2.0_react-redux@8.0.5_react@18.2.0_vite@4.3.2/node_modules/rd-component/dist/rd-component.es.js' implicitly has an 'any' type.\n There are types at '/Users/John/source/reddwarf/frontend/ppt-web/node_modules/rd-component/dist/index.d.ts', but this result could not be resolved when respecting package.json \"exports\". The 'rd-component' library may need to update its package.json or typings.ts(7016)\n```\n\nwhat should I do to fixed this issue? this is the public rd-component's `package.json`:\n\n```\n{\n \"name\": \"rd-component\",\n \"version\": \"0.1.47\",\n \"type\": \"module\",\n \"description\": \"Reddwarf public component lib\",\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/rd-component.umd.js\",\n \"module\": \"./dist/rd-component.es.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": \"./dist/rd-component.es.js\",\n \"require\": \"./dist/rd-component.umd.js\"\n },\n \"./dist/style.css\": {\n \"import\": \"./dist/style.css\",\n \"require\": \"./dist/style.css\"\n }\n },\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"tsc && vite build\",\n \"watch\": \"vite build --watch\",\n \"lint\": \"eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0\",\n \"preview\": \"vite preview\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^20.1.0\",\n \"@types/react\": \"^18.2.0\",\n \"@types/redux-logger\": \"^3.0.9\",\n \"axios\": \"^1.3.4\",\n \"js-wheel\": \"https://github.com/jiangxiaoqiang/js-wheel.git\",\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\",\n \"react-redux\": \"^8.0.5\",\n \"redux\": \"^4.2.1\",\n \"redux-logger\": \"^3.0.6\",\n \"uuid\": \"^9.0.0\",\n \"vite\": \"^4.3.5\"\n },\n \"dependencies\": {\n \"@reduxjs/toolkit\": \"^1.9.5\",\n \"@vitejs/plugin-react\": \"^4.0.0\",\n \"antd\": \"^5.4.6\",\n \"vite-plugin-dts\": \"^2.3.0\"\n }\n}\n```\n\nI have already read some answers told that add typings, but it seems the legacy typescript configuration.\n\n========================================\n\nCode:\n```text\nCould not find a declaration file for module 'rd-component'. '/Users/John/source/reddwarf/frontend/ppt-web/node_modules/.pnpm/rd-component@0.1.47_@types+node@20.1.1_react-dom@18.2.0_react-redux@8.0.5_react@18.2.0_vite@4.3.2/node_modules/rd-component/dist/rd-component.es.js' implicitly has an 'any' type.\n  There are types at '/Users/John/source/reddwarf/frontend/ppt-web/node_modules/rd-component/dist/index.d.ts', but this result could not be resolved when respecting package.json \"exports\". The 'rd-component' library may need to update its package.json or typings.ts(7016)\n```\n\n```text\n{\n    \"name\": \"rd-component\",\n    \"version\": \"0.1.47\",\n    \"type\": \"module\",\n    \"description\": \"Reddwarf public component lib\",\n    \"files\": [\n        \"dist\"\n    ],\n    \"main\": \"./dist/rd-component.umd.js\",\n    \"module\": \"./dist/rd-component.es.js\",\n    \"types\": \"./dist/index.d.ts\",\n    \"exports\": {\n        \".\": {\n            \"import\": \"./dist/rd-component.es.js\",\n            \"require\": \"./dist/rd-component.umd.js\"\n        },\n        \"./dist/style.css\": {\n            \"import\": \"./dist/style.css\",\n            \"require\": \"./dist/style.css\"\n        }\n    },\n    \"scripts\": {\n        \"dev\": \"vite\",\n        \"build\": \"tsc && vite build\",\n        \"watch\": \"vite build --watch\",\n        \"lint\": \"eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0\",\n        \"preview\": \"vite preview\"\n    },\n    \"devDependencies\": {\n        \"@types/node\": \"^20.1.0\",\n        \"@types/react\": \"^18.2.0\",\n        \"@types/redux-logger\": \"^3.0.9\",\n        \"axios\": \"^1.3.4\",\n        \"js-wheel\": \"https://github.com/jiangxiaoqiang/js-wheel.git\",\n        \"react\": \"^18.2.0\",\n        \"react-dom\": \"^18.2.0\",\n        \"react-redux\": \"^8.0.5\",\n        \"redux\": \"^4.2.1\",\n        \"redux-logger\": \"^3.0.6\",\n        \"uuid\": \"^9.0.0\",\n        \"vite\": \"^4.3.5\"\n    },\n    \"dependencies\": {\n        \"@reduxjs/toolkit\": \"^1.9.5\",\n        \"@vitejs/plugin-react\": \"^4.0.0\",\n        \"antd\": \"^5.4.6\",\n        \"vite-plugin-dts\": \"^2.3.0\"\n    }\n}\n```\n\n```text\nrd-component\n```\n\n```text\n\"rd-component\": \"^0.1.47\"\n```\n\n```text\npackage.json\n```\n\n```json\n{\n  \"exports\": {\n    \".\": {\n      // Specify types first\n      \"types\": \"./dist/index.d.ts\",\n      \"import\": \"./dist/rd-component.es.js\",\n      \"require\": \"./dist/rd-component.umd.js\"\n    },\n    \"./dist/style.css\": {\n      \"import\": \"./dist/style.css\",\n      \"require\": \"./dist/style.css\"\n    }\n  },\n}\n```\n\n```text\ntypes\n```\n\n```text\npackage.json\n```\n\n```text\nexports\n```\n\n```text\n\"types\"\n```\n\n```text\n\"types\": \"./dist/index.d.ts\"\n```\n\n```text\nexports.\".\"\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.399Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":180,"estimatedTokens":1225}}94{"id":"stack-75654933","source":"stackoverflow","questionId":75654933,"title":"Mantine Modal not showing","tags":["css","reactjs","vite","mantine"],"text":"Title: Mantine Modal not showing\nTags: css, reactjs, vite, mantine\nSource: Stack Overflow\n\nQuestion:\nI created a React App using Vite and installed `Mantine v6.0.0`. When I call the following function to open a Mantine modal the view dims however the modal is not visible.\n\n```\nconst openModal = () => modals.openConfirmModal({\n title: 'Please confirm your action',\n children: (\n \n This action is so important that you are required to confirm it with a modal. Please click\n one of these buttons to proceed.\n \n ),\n labels: { confirm: 'Confirm', cancel: 'Cancel' },\n onCancel: () => console.log('Cancel'),\n onConfirm: () => console.log('Confirmed'),\n });\n```\n\n========================================\n\nTop Answer:\nThis saved me hours, thanks.\n\nIn case you encounter the same issue when using Storybook with Mantine, make sure you don't have the below `parameters` in your `meta` object:\n\n```\nparameters: {\n layout: \"centered\",\n },\n```\n\nThe root cause is the same, the above parameter adds `display: flex` to the body of the iframe.\n\n========================================\n\nCode:\n```text\nconst openModal = () => modals.openConfirmModal({\n    title: 'Please confirm your action',\n    children: (\n      <Text size=\"sm\">\n        This action is so important that you are required to confirm it with a modal. Please click\n        one of these buttons to proceed.\n      </Text>\n    ),\n    labels: { confirm: 'Confirm', cancel: 'Cancel' },\n    onCancel: () => console.log('Cancel'),\n    onConfirm: () => console.log('Confirmed'),\n  });\n```\n\n```text\nMantine v6.0.0\n```\n\n```css\nbody {\n  display: flex\n}\n```\n\n```text\nindex.css\n```\n\n```text\nparameters: {\n    layout: \"centered\",\n  },\n```\n\n```text\nparameters\n```\n\n```text\nmeta\n```\n\n```text\ndisplay: flex\n```\n\n```text\nimport '@mantine/notifications/styles.layer.css';\n```\n\n========================================\n\nComments:\n- Thankyou for coming back and updating this, been stuck for about 2 hours!\n- this did it for me, thank you!\n- It saves me a bunch of time, thanks!","metadata":{"transformedAt":"2026-08-18T18:33:46.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":97,"estimatedTokens":502}}95{"id":"stack-77173608","source":"stackoverflow","questionId":77173608,"title":"How to remove @license comments from source during npm build (will add manually)?","tags":["reactjs","vite","minify","bundling-and-minification","preact"],"text":"Title: How to remove @license comments from source during npm build (will add manually)?\nTags: reactjs, vite, minify, bundling-and-minification, preact\nSource: Stack Overflow\n\nQuestion:\nI am developing a Vite-React webapp to be used by me only, and heres my simple build command in **package.json**: `\"build\": \"vite build --emptyOutDir --base=./\"`.\n\nIt uses the Google Firebase libraries that contains several submodules wherein each has the exact same @license comment leading to 48 times the **same repeated text contributing to 80% of my build** since everything else I have gzipped anyway.\nNow I have no issue with **manually**, thankfully, and carefully adding all unique licenses wherever appropriate, but at first I wish to remove licenses during the build.\n\nI realize the \"@license\" is probably the marker the minifier looks for, and I searched around but could not find a way to turn it off.\nPlease advise. And Thanks!\n\n========================================\n\nTop Answer:\nYou need to configure `terser` through your `vite.config.js`:\n\n```\nexport default defineConfig({\n build: {\n terserOptions: {\n format: {\n comments: false\n }\n }\n }\n});\n```\n\n`comments` (default `\"some\"`) -- by default it keeps JSDoc-style comments that contain \"@license\", \"@copyright\", \"@preserve\" or start with `!`, pass `true` or `\"all\"` to preserve all comments, `false` to omit comments in the output, a regular expression string (e.g. `/^!/`) or a function.\n\nTerser's Docs\n\n========================================\n\nCode:\n```text\n\"build\": \"vite build --emptyOutDir --base=./\"\n```\n\n```text\nexport default defineConfig({\n  // ...\n  build: {\n    // ...\n  },\n  esbuild: { legalComments: 'none' },\n})\n```\n\n```text\nesbuild\n```\n\n```js\nexport default defineConfig({\n  build: {\n    terserOptions: {\n      format: {\n        comments: false\n      }\n    }\n  }\n});\n```\n\n```text\nterser\n```\n\n```text\nvite.config.js\n```\n\n```text\ncomments\n```\n\n```text\n\"some\"\n```\n\n```text\n!\n```\n\n```text\ntrue\n```\n\n```text\n\"all\"\n```\n\n```text\nfalse\n```\n\n```text\n/^!/\n```\n\n========================================\n\nComments:\n- Strip comments in your build? I don't know why anyone would need comments in the build since it's all minified and/or obfuscated. Source maps don't have to be inline either.\n- @kelsny exactly! and still license comments **do** exist in the build if the build tool finds a comment prefixed with \"@license\" and thereafter skips such comments from minification, Its not obfuscated, and I just wish to remove the duplicates, thats all.\n- Thanks you pointed me in the right direction. During build I found that Terser is no longer default build tool, and so I will have to configure esbuild instead.\n- So I didnt find any esbuild config options that Vite exposes in its settings, nor any other easy way, and also Terser is listed to be a better minifier, so I installed that. thx\n- Does this still work? My comments are not removed. In fact nearly all options are totally ignored. I made sure to add `minify: 'terser'`\n- @RobinSchambach It looks like Vite ignores (for reasons) terserOptions when building ES modules in lib mode, as discussed in github.com/vitejs/vite/issues/5167. A workaround is the @rollup/plugin-terser which forces terser to run anyway.","metadata":{"transformedAt":"2026-08-18T18:33:46.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":112,"estimatedTokens":808}}96{"id":"stack-75294174","source":"stackoverflow","questionId":75294174,"title":"Vite pwa plugin not working in development environment for react apps","tags":["reactjs","service-worker","vite","vite-plugin-pwa"],"text":"Title: Vite pwa plugin not working in development environment for react apps\nTags: reactjs, service-worker, vite, vite-plugin-pwa\nSource: Stack Overflow\n\nQuestion:\nI'v already migrated from webpack to vite and used vite pwa plugin to register a service worker.\n\nMy problem is that when I try to use a custom path for service worker, Vite will work fine in production, but in development cause 404 error.\n\nhere is my VitePwa vite.config.js:\n\n```\nVitePWA({\n srcDir: 'src',\n filename: 'sw.js',\n devOptions: {\n enabled: true,\n },\n strategies: 'injectManifest',\n injectManifest: {\n injectionPoint: undefined\n }\n }),\n```\n\nI already got that, in the development environment, vite pwa plugin is looking for sw.js in the public directory but I want it to get it from src\n\n========================================\n\nTop Answer:\nI had a problem here where my remote development environment wasn't working, but the reload prompt was working locally via `npm run build` and `npm run preview`.\n\nThe problem for me was that the remote environment didn't have HTTPS, so everything worked but the `useRegisterSW` function silently failed.\n\nEnabled HTTPS and now it's working.\n\nI'm using VitePWA with Vue3/Vite, but it's extremely similar across React/Vue etc. I have a minimal repo if anyone wants to see it https://github.com/agm1984/vue-vite-pwa-minimal-update-prompt\n\n========================================\n\nCode:\n```text\nVitePWA({\n      srcDir: 'src',\n      filename: 'sw.js',\n      devOptions: {\n        enabled: true,\n      },\n      strategies: 'injectManifest',\n      injectManifest: {\n        injectionPoint: undefined\n      }\n    }),\n```\n\n```text\ndevOptions: {\n        enabled: true,\n        type: 'module',\n      },\n```\n\n```text\nimport { registerSW } from 'virtual:pwa-register';\n\nif ('serviceWorker' in navigator) {\n  registerSW();\n}\n```\n\n```text\nvitePwaPlugin\n```\n\n```text\ndevOptions\n```\n\n```text\nvitePwaPlugin\n```\n\n```text\ndev-sw.js?dev-sw\n```\n\n```text\n/// <reference types=\"vite-plugin-pwa/client\" />\n```\n\n```text\nglobal.d.ts\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm run preview\n```\n\n```text\nuseRegisterSW\n```\n\n========================================\n\nComments:\n- Interesting choice that they decided to not enable the plugin in development by default. Spent 30 minutes because of this.\n- I'm on three hours already - still not working\n- Your repo is the best resource I have found to quickly set up a fully functional example! Though I don't understand why calling updateServiceWorker() does not also reload the page (which I had to do myself with a location.reload() in a 1000ms setTimeout). What is the point of updating the service worker without reloading the page? Or why not instead update the service worker on BeforeUnloadEvent?\n- @user3803848 thanks!, If I remember correctly, the serviceworker has an internal function that handles the reload. In my example code, there is a function `updateServiceWorker` that you call to reload, so the actual window.reload part is handled by the library there. Maybe it works slightly differently in React compared to Vue.\n- actually it seems to depend on the device, also the type declaration file for updateServiceWorker confuses me: `export function useRegisterSW(options?: RegisterSWOptions): { &#47;** * Reloads the current window to allow the service worker take the control. * @param reloadPage From version 0.13.2+ this param is not used anymore. *&#47; updateServiceWorker: (reloadPage?: boolean) => Promise }` param not used anymore, but it still automatically reloads on android... so I do this as a failsafe: `updateServiceWorker(true).then(() => { setTimeout(location.reload, 500) })`","metadata":{"transformedAt":"2026-08-18T18:33:46.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":114,"estimatedTokens":912}}97{"id":"stack-75841925","source":"stackoverflow","questionId":75841925,"title":"Why is docker-compose throwing vite not found during the build?","tags":["reactjs","docker","npm","docker-compose","vite"],"text":"Title: Why is docker-compose throwing vite not found during the build?\nTags: reactjs, docker, npm, docker-compose, vite\nSource: Stack Overflow\n\nQuestion:\nI have a React frontend app built with Vite. I'm getting the following error when I'm running my Docker\n\n```\n[+] Running 1/1\n ⠿ Container client-client-1 Recreated 0.2s\nAttaching to client-client-1\nclient-client-1 |\nclient-client-1 | > client@0.0.0 dev\nclient-client-1 | > vite\nclient-client-1 |\nclient-client-1 | sh: 1: vite: not found\nclient-client-1 exited with code 127\n```\n\nBelow you can see my Dockerfile:\n\n```\nFROM node\n\nWORKDIR /usr/src/app\n\nCOPY ./package.json .\n\nRUN npm i\n\nCOPY . .\n\nCMD [\"npm\", \"run\", \"dev\"]\n```\n\nI tried to add a command to install vite during the build of the docker container but it didn't work.\nYou check my docker-compose file below\n\n```\nversion: '3.9'\n\nservices:\n client:\n build: .\n ports:\n - 5173:5173\n volumes:\n - .:/usr/src/app\n```\n\nHere is my package.json\n\n```\n{\n \"name\": \"client\",\n \"private\": true,\n \"version\": \"0.0.0\",\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"tsc && vite build\",\n \"preview\": \"vite preview\",\n \"lint\": \"eslint .\",\n \"lint:fix\": \"eslint --fix .\"\n },\n \"dependencies\": {\n \"eslint\": \"^8.36.0\",\n \"eslint-config-airbnb\": \"^19.0.4\",\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\"\n },\n \"devDependencies\": {\n \"@testing-library/jest-dom\": \"^5.16.5\",\n \"@testing-library/react\": \"^14.0.0\",\n \"@types/react\": \"^18.0.28\",\n \"@types/react-dom\": \"^18.0.11\",\n \"@typescript-eslint/eslint-plugin\": \"^5.54.1\",\n \"@typescript-eslint/parser\": \"^5.54.1\",\n \"@vitejs/plugin-react\": \"^3.1.0\",\n \"eslint\": \"^8.35.0\",\n \"eslint-config-airbnb\": \"^19.0.4\",\n \"eslint-config-airbnb-typescript\": \"^17.0.0\",\n \"eslint-config-prettier\": \"^8.7.0\",\n \"eslint-plugin-import\": \"^2.27.5\",\n \"eslint-plugin-jsx-a11y\": \"^6.7.1\",\n \"eslint-plugin-prettier\": \"^4.2.1\",\n \"eslint-plugin-react\": \"^7.32.2\",\n \"eslint-plugin-react-hooks\": \"^4.6.0\",\n \"jsdom\": \"^21.1.0\",\n \"prettier\": \"^2.8.4\",\n \"typescript\": \"^4.9.3\",\n \"vite\": \"^4.2.0\"\n }\n}\n```\n\n========================================\n\nCode:\n```text\n[+] Running 1/1\n ⠿ Container client-client-1  Recreated                                                                0.2s\nAttaching to client-client-1\nclient-client-1  |\nclient-client-1  | > client@0.0.0 dev\nclient-client-1  | > vite\nclient-client-1  |\nclient-client-1  | sh: 1: vite: not found\nclient-client-1 exited with code 127\n```\n\n```text\nFROM node\n\nWORKDIR /usr/src/app\n\nCOPY ./package.json .\n\nRUN npm i\n\nCOPY . .\n\n\nCMD [\"npm\", \"run\", \"dev\"]\n```\n\n```yaml\nversion: '3.9'\n\nservices:\n  client:\n    build: .\n    ports:\n      - 5173:5173\n    volumes:\n      - .:/usr/src/app\n```\n\n```text\n{\n  \"name\": \"client\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"tsc && vite build\",\n    \"preview\": \"vite preview\",\n    \"lint\": \"eslint .\",\n    \"lint:fix\": \"eslint --fix .\"\n  },\n  \"dependencies\": {\n    \"eslint\": \"^8.36.0\",\n    \"eslint-config-airbnb\": \"^19.0.4\",\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\"\n  },\n  \"devDependencies\": {\n    \"@testing-library/jest-dom\": \"^5.16.5\",\n    \"@testing-library/react\": \"^14.0.0\",\n    \"@types/react\": \"^18.0.28\",\n    \"@types/react-dom\": \"^18.0.11\",\n    \"@typescript-eslint/eslint-plugin\": \"^5.54.1\",\n    \"@typescript-eslint/parser\": \"^5.54.1\",\n    \"@vitejs/plugin-react\": \"^3.1.0\",\n    \"eslint\": \"^8.35.0\",\n    \"eslint-config-airbnb\": \"^19.0.4\",\n    \"eslint-config-airbnb-typescript\": \"^17.0.0\",\n    \"eslint-config-prettier\": \"^8.7.0\",\n    \"eslint-plugin-import\": \"^2.27.5\",\n    \"eslint-plugin-jsx-a11y\": \"^6.7.1\",\n    \"eslint-plugin-prettier\": \"^4.2.1\",\n    \"eslint-plugin-react\": \"^7.32.2\",\n    \"eslint-plugin-react-hooks\": \"^4.6.0\",\n    \"jsdom\": \"^21.1.0\",\n    \"prettier\": \"^2.8.4\",\n    \"typescript\": \"^4.9.3\",\n    \"vite\": \"^4.2.0\"\n  }\n}\n```\n\n```text\nversion: '3.9'\n\nservices:\n  client:\n    build: .\n    ports:\n      - 5173:5173\n    volumes:\n      - .:/usr/src/app\n      - /usr/src/app/node_modules\n```\n\n========================================\n\nComments:\n- You’ve not listed your package.json so just checking, is vite listed as a dependency in your package.json dependencies?\n- Yes, it's listed everything is working correctly locally. ``` { \"name\": \"client\", \"private\": true, \"version\": \"0.0.0\", \"type\": \"module\", \"scripts\": { \"dev\": \"vite\", \"build\": \"tsc && vite build\", \"preview\": \"vite preview\", \"lint\": \"eslint .\", \"lint:fix\": \"eslint --fix .\" }, \"dependencies\": { \"eslint\": \"^8.36.0\", \"eslint-config-airbnb\": \"^19.0.4\", \"react\": \"^18.2.0\", \"react-dom\": \"^18.2.0\" }, \"devDependencies\": { \"prettier\": \"^2.8.4\", \"typescript\": \"^4.9.3\", \"vite\": \"^4.2.0\" } } ```\n- Your `volumes:` block is hiding everything in the image, including the `&#47;usr&#47;src&#47;app&#47;node_modules` directory. Delete that block.\n- Removing the volumes works but it means that the docker container won't be able to track the changes locally I will have to rebuild a new image each time there are changes\n- This worked for me. I don't understand how there are so many docker-vite tutorials out there but none reference this. node_modules needs its volume apparently? Did this behavior change recently or has it always worked like that? Anyway, I can confirm this works. Thanks\n- Or you can use a named volume instead of an anonymous volume.","metadata":{"transformedAt":"2026-08-18T18:33:46.399Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":204,"estimatedTokens":1324}}98{"id":"stack-70870735","source":"stackoverflow","questionId":70870735,"title":"React.js (Vite-based) SPA returns 404 when deployed to Vercel within mono-repository","tags":["reactjs","react-router","vite","vercel","turborepo"],"text":"Title: React.js (Vite-based) SPA returns 404 when deployed to Vercel within mono-repository\nTags: reactjs, react-router, vite, vercel, turborepo\nSource: Stack Overflow\n\nQuestion:\nI have boilerplate-like single-page application with `wouter`-based routing - application is functional in local environment. Goal I'm trying to archive is deployment of mentioned application to `vercel`, yet there is a problem in application routing - things are ok when I run application locally but it returns Not Found (404) errors when it's deployed to cloud.\n\nDeployment has no problem when it's run through `procfile`, Docker Container or \"bare-metal\" - but one it touches Vercel's Edge application do not care about routing at all.\n\nI have tried multiple routing libraries (`wouter`, `react-router`) and problem still existed and behaved without any difference.\n\nImplementation of routing is correct, and path rewrites which are required and recommended by Vercel are configured in `vercel.json` and are provided below.\n\n```\n{\n \"github\": {\n \"silent\": true\n },\n \"rewrites\": [\n {\n \"source\": \"(.*)\",\n \"destination\": \"/index.html\"\n }\n ]\n}\n```\n\nCommonly proposed solution for similar Vercel-related problems was following configuration yet this still do not change outcome at all.\n\n```\n{\n \"rewrites\": [{ \"source\": \"/(.*)\", \"destination\": \"/\" }]\n}\n```\n\nMy file structure is following, as my project is mono-repository managed by `turbo`.\n\n```\n.\n├── apps/\n│ └── web/\n│ ├── src\n│ └── package.json\n└── vercel.json\n```\n\n========================================\n\nTop Answer:\nTLDR\n\nAdd an empty 404.html in the **public** folder (you can put the title in the title tag) with this script in the head section\n\n```\n\n var pathSegmentsToKeep = 0;\n\n var l = window.location;\n l.replace(\n l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') +\n l.pathname.split('/').slice(0, 1 + pathSegmentsToKeep).join('/') + '/?/' +\n l.pathname.slice(1).split('/').slice(pathSegmentsToKeep).join('/').replace(/&/g, '~and~') +\n (l.search ? '&' + l.search.slice(1).replace(/&/g, '~and~') : '') +\n l.hash\n );\n \n```\n\nThen add this script to your index.html\n\n```\n\n (function(l) {\n if (l.search[1] === '/' ) {\n var decoded = l.search.slice(1).split('&').map(function(s) { \n return s.replace(/~and~/g, '&')\n }).join('?');\n window.history.replaceState(null, null,\n l.pathname.slice(0, -1) + decoded + l.hash\n );\n }\n }(window.location))\n \n```\n\nThis worked perfectly for me after deploying my app to render.com\n\nTo handle the \"real\" not found response, you can add this route\n\n```\nPage not found\n\n} />\n```\n\nFor more information you can visit this repo spa-github-pages\n\nCredits to @rafgraph\n\n========================================\n\nCode:\n```json\n{\n    \"github\": {\n        \"silent\": true\n    },\n    \"rewrites\": [\n        {\n            \"source\": \"(.*)\",\n            \"destination\": \"/index.html\"\n        }\n    ]\n}\n```\n\n```json\n{\n  \"rewrites\": [{ \"source\": \"/(.*)\", \"destination\": \"/\" }]\n}\n```\n\n```text\n.\n├── apps/\n│   └── web/\n│       ├── src\n│       └── package.json\n└── vercel.json\n```\n\n```text\nwouter\n```\n\n```text\nvercel\n```\n\n```text\nprocfile\n```\n\n```text\nwouter\n```\n\n```text\nreact-router\n```\n\n```text\nvercel.json\n```\n\n```text\nturbo\n```\n\n```text\n{\n  \"rewrites\": [{ \"source\": \"/(.*)\", \"destination\": \"/\" }]\n}\n```\n\n```text\n<script type=\"text/javascript\">\n  var pathSegmentsToKeep = 0;\n\n  var l = window.location;\n  l.replace(\n    l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') +\n    l.pathname.split('/').slice(0, 1 + pathSegmentsToKeep).join('/') + '/?/' +\n    l.pathname.slice(1).split('/').slice(pathSegmentsToKeep).join('/').replace(/&/g, '~and~') +\n    (l.search ? '&' + l.search.slice(1).replace(/&/g, '~and~') : '') +\n    l.hash\n  );\n    </script>\n```\n\n```text\n<script type=\"text/javascript\">\n  (function(l) {\n    if (l.search[1] === '/' ) {\n      var decoded = l.search.slice(1).split('&').map(function(s) { \n        return s.replace(/~and~/g, '&')\n      }).join('?');\n      window.history.replaceState(null, null,\n          l.pathname.slice(0, -1) + decoded + l.hash\n      );\n    }\n  }(window.location))\n    </script>\n```\n\n```text\n<Route path=\"*\" element={<p>Page not found</p>} />\n```\n\n```text\n{\n    \"github\": {\n        \"silent\": true\n    },\n    \"rewrites\": [\n        {\n            \"source\": \"(.*)\",\n            \"destination\": \"/index.html\"\n        }\n    ]\n}\n```\n\n```text\nvercel.json\n```\n\n```text\n$ROOT/$PROJECT/vercel.json\n```\n\n```text\n$ROOT/vercel.json\n```\n\n```text\n$ROOT/$PROJECT/vercel.json\n```\n\n```text\nvercel.json\n```\n\n```text\nvercel.json\n```\n\n```text\npackage.json\n```\n\n```text\nvercel.json\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- stackoverflow.com/questions/69701743/&hellip; The solution has ben soved in this Question!\n- Not exactly, I was not aware of that `vercel` can have a problems with monorepo structure. Question you provided is on completely different topic.\n- Mate you're wrong, You cannot put `vercel.json` in Project Root, because if you're using monorepo structure this will not work. It's supposed to be in **Application Directory (with package.json)**.\n- yea as @keinsell said, I put `vercel.json` in my application directory (mine is called `&#47;client`) and it worked :)\n- Sorry! I meant. Exactly next to the package.json.","metadata":{"transformedAt":"2026-08-18T18:33:46.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":257,"estimatedTokens":1318}}99{"id":"stack-73136479","source":"stackoverflow","questionId":73136479,"title":"Vite PostCSS module error when building app in Svelte","tags":["svelte","vite","postcss","autoprefixer"],"text":"Title: Vite PostCSS module error when building app in Svelte\nTags: svelte, vite, postcss, autoprefixer\nSource: Stack Overflow\n\nQuestion:\nI came across this strange error in Svelte; every time I ran `npm run dev`, this vite error would appear:\n\n```\n[vite] Internal server error: Failed to load PostCSS config (searchPath: /Users/Documents/Personal projects): [Failed to load PostCSS config] Failed to load PostCSS config (searchPath: /Users/Documents/Personal projects): [Failed to load PostCSS config] Failed to load PostCSS config (searchPath: /Users/Documents/Personal projects): [Error] Cannot find module 'autoprefixer'\n```\n\nI'm new to vite so it took me an hour of research, to figure out how to export the module, I was able to fix it by creating a `postcss.config.cjs` file and inside the file add:\n\n```\nmodule.exports = {\n autoprefixer: {}\n}\n```\n\nI hope this helps anyone that comes across the same/similar error.\n\n========================================\n\nTop Answer:\nI solved this issue by deleting the node_modules directory, and ran `npm i` again.\n\n========================================\n\nCode:\n```text\n[vite] Internal server error: Failed to load PostCSS config (searchPath: /Users/Documents/Personal projects): [Failed to load PostCSS config] Failed to load PostCSS config (searchPath: /Users/Documents/Personal projects): [Failed to load PostCSS config] Failed to load PostCSS config (searchPath: /Users/Documents/Personal projects): [Error] Cannot find module 'autoprefixer'\n```\n\n```text\nmodule.exports = {\n    autoprefixer: {}\n}\n```\n\n```text\nnpm run dev\n```\n\n```text\npostcss.config.cjs\n```\n\n```text\nmodule.exports = {\n    autoprefixer: {}\n}\n```\n\n```text\npostcss.config.cjs\n```\n\n```text\nnpm i\n```\n\n```text\n\"type\": \"module\",\n```\n\n```text\nnpm install -D tailwindcss@latest postcss@latest autoprefixer@latest\n\nnpx tailwindcss init -p\n\nnpm i\n```\n\n```text\nnpm run dev\n```\n\n```js\nmodule.exports = {\n        autoprefixer: {}\n    }\n```\n\n```js\nimport tailwindConfig from './tailwind.config'\nimport autoprefixer from 'autoprefixer'\nimport tailwind from 'tailwindcss'\n\nexport default {\n  plugins: [tailwind(tailwindConfig), autoprefixer],\n}\n```\n\n```js\n...\nimport postcss from './postcss.config'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  css: {\n    postcss,\n  },\n})\n```\n\n```json\n{\n  ...\n  \"include\": [\n    \"vite.config.ts\",\n    \"postcss.config.ts\",\n    \"tailwind.config.ts\"\n  ]\n}\n```\n\n```text\npostcss\n```\n\n```text\ncss\n```\n\n```text\ninclude\n```\n\n========================================\n\nComments:\n- CommonJS files when using vite need to be explicitly named as `.cjs`. See issue on GitHub\n- Best answer for entire TS Vite project !","metadata":{"transformedAt":"2026-08-18T18:33:46.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":134,"estimatedTokens":670}}100{"id":"stack-75234915","source":"stackoverflow","questionId":75234915,"title":"Why is Vite/TS bundling both production and development versions of react-jsx-runtime?","tags":["reactjs","typescript","vite","rollup"],"text":"Title: Why is Vite/TS bundling both production and development versions of react-jsx-runtime?\nTags: reactjs, typescript, vite, rollup\nSource: Stack Overflow\n\nQuestion:\nI am using `\"jsx\": \"react-jsx\",` in my tsconfig file and using Vite/rollup for bundling. For some reason my module is always bundling with both `react-jsx-runtime.production.min.js` and `react-jsx-runtime.development.js`, even when NODE_ENV is set to production. I only expect the production code to be included.\n\nI can remove both by setting `'react/jsx-runtime'` to external in rollup options, but this is also not what I want for the prod bundle. I can't find docs that explain this. Does anyone know how I can stop the bundler from including the development runtime?\n\n**vite.config.ts**\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\nexport default defineConfig({\n build: {\n lib: {\n entry: './src/index.tsx',\n formats: ['es'],\n name: `button`,\n fileName: `button`,\n },\n rollupOptions: {\n external: ['react'],\n },\n },\n plugins: [react()],\n})\n```\n\n**tsconfig.json**\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"ESNext\",\n \"useDefineForClassFields\": true,\n \"lib\": [\"DOM\", \"DOM.Iterable\", \"ESNext\"],\n \"allowJs\": false,\n \"skipLibCheck\": true,\n \"esModuleInterop\": false,\n \"allowSyntheticDefaultImports\": true,\n \"strict\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Node\",\n \"resolveJsonModule\": true,\n \"isolatedModules\": true,\n \"noEmit\": true,\n \"jsx\": \"react-jsx\"\n },\n \"include\": [\"src\"],\n \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\n**tsconfig.node.json**\n\n```\n{\n \"compilerOptions\": {\n \"composite\": true,\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Node\",\n \"allowSyntheticDefaultImports\": true\n },\n \"include\": [\"vite.config.ts\"]\n}\n```\n\n**package.json**\n\n```\n{\n \"name\": \"button\",\n \"private\": true,\n \"version\": \"0.0.0\",\n \"type\": \"module\",\n \"scripts\": {\n \"build\": \"cross-env NODE_ENV=production vite build && npx tsc\"\n },\n \"dependencies\": {\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\",\n \"react-is\": \"^18.2.0\"\n },\n \"devDependencies\": {\n \"cross-env\": \"^7.0.3\",\n \"@types/react\": \"^18.0.26\",\n \"@types/react-dom\": \"^18.0.9\",\n \"@vitejs/plugin-react\": \"^3.0.0\",\n \"typescript\": \"^4.9.3\",\n \"vite\": \"^4.0.0\"\n }\n}\n```\n\n**src/index.tsx**\n\n```\nimport React, { FC } from 'react'\n\nexport const Button: FC = ({\n children\n}) => (\n {children}\n)\n\nexport default Button\n```\n\n========================================\n\nTop Answer:\nI had the same problem but I found a tutorial on medium where it explained the creation of libraries with vite, I show you my config that avoids external dependencies\n\n```\nbuild: {\n ...\n rollupOptions: {\n external: [\n 'react',\n \"react/jsx-runtime\",\n 'react-dom',\n ],\n output: {\n globals: {\n 'react': 'react',\n 'react-dom': 'ReactDOM',\n 'react/jsx-runtime': 'react/jsx-runtime',\n },\n },\n },\n},\n```\n\nhug from argentina\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\nexport default defineConfig({\n  build: {\n    lib: {\n      entry: './src/index.tsx',\n      formats: ['es'],\n      name: `button`,\n      fileName: `button`,\n    },\n    rollupOptions: {\n      external:  ['react'],\n    },\n  },\n  plugins: [react()],\n})\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"DOM\", \"DOM.Iterable\", \"ESNext\"],\n    \"allowJs\": false,\n    \"skipLibCheck\": true,\n    \"esModuleInterop\": false,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\"\n  },\n  \"include\": [\"src\"],\n  \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Node\",\n    \"allowSyntheticDefaultImports\": true\n  },\n  \"include\": [\"vite.config.ts\"]\n}\n```\n\n```text\n{\n  \"name\": \"button\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"build\": \"cross-env NODE_ENV=production vite build && npx tsc\"\n  },\n  \"dependencies\": {\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\",\n    \"react-is\": \"^18.2.0\"\n  },\n  \"devDependencies\": {\n    \"cross-env\": \"^7.0.3\",\n    \"@types/react\": \"^18.0.26\",\n    \"@types/react-dom\": \"^18.0.9\",\n    \"@vitejs/plugin-react\": \"^3.0.0\",\n    \"typescript\": \"^4.9.3\",\n    \"vite\": \"^4.0.0\"\n  }\n}\n```\n\n```text\nimport React, { FC } from 'react'\n\nexport const Button: FC<any> = ({\n  children\n}) => (\n  <button>{children}</button>\n)\n\nexport default Button\n```\n\n```text\n\"jsx\": \"react-jsx\",\n```\n\n```text\nreact-jsx-runtime.production.min.js\n```\n\n```text\nreact-jsx-runtime.development.js\n```\n\n```text\n'react/jsx-runtime'\n```\n\n```text\nexport default defineConfig((env) => ({\n  define: env.command === 'build' ? { \"process.env.NODE_ENV\":  \"'production'\" } : undefined,\n...\n```\n\n```text\nreact/jsx-runtime\n```\n\n```js\nreact({\n  jsxRuntime: 'classic',\n})\n```\n\n```js\nbuild: {\n  lib: {\n    ...\n  },\n  rollupOptions: {\n    external: [\n      \"react\",\n      \"react/jsx-runtime\",\n      \"react-dom\",\n    ],\n    ...\n  }\n}\n```\n\n```text\nreact/jsx-runtime\n```\n\n```text\nbuild: {\n  ...\n  rollupOptions: {\n    external: [\n      'react',\n      \"react/jsx-runtime\",\n      'react-dom',\n    ],\n    output: {\n      globals: {\n        'react': 'react',\n        'react-dom': 'ReactDOM',\n        'react/jsx-runtime': 'react/jsx-runtime',\n      },\n    },\n  },\n},\n```\n\n========================================\n\nComments:\n- Sounds like maybe it's a bug then?\n- Thanks, I tried this option, but it stops the bundling of the runtime entirely. I do want (only) the production runtime. The issue for me is that both the development and production versions of the runtime are bundled together. I only want one or the other, in this case the production one.\n- This is the correct answer. I am unsure why Vite is not honoring the 'NODE_ENV=production' environment variable. Nevertheless, it seems to be the sole method to make Vite recognize the environment variable. I verified this works using npmjs.com/package/vite-bundle-visualizer\n- Thank you so much for this answer! It has been doing my head in all day. For some reason, this only seems to happen when upgrading to 3.x of Vite. 2.9.16 would only bundle runtime.production so I started noticing the difference. This looks to remove both which is great!","metadata":{"transformedAt":"2026-08-18T18:33:46.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":314,"estimatedTokens":1625}}101{"id":"stack-74229258","source":"stackoverflow","questionId":74229258,"title":"Vite+React+Docker: not working in container","tags":["reactjs","docker","vite"],"text":"Title: Vite+React+Docker: not working in container\nTags: reactjs, docker, vite\nSource: Stack Overflow\n\nQuestion:\nI'm writing a standard react app using vite and yarn. I'm new to vite...\n\npackage.json\n\n```\n{\n \"name\": \"bpm\",\n \"private\": true,\n \"version\": \"0.0.0\",\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\"\n },\n \"dependencies\": {\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\",\n \"react-icons\": \"^4.4.0\",\n \"uuid\": \"^9.0.0\"\n },\n \"devDependencies\": {\n \"@types/react\": \"^18.0.17\",\n \"@types/react-dom\": \"^18.0.6\",\n \"@vitejs/plugin-react\": \"^2.1.0\",\n \"vite\": \"^3.1.0\"\n }\n}\n```\n\nvite.config.js\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\nexport default defineConfig({\n server: {host:'0.0.0.0', port:8080},\n plugins: [react()]\n})\n```\n\nWhen I run it directly in wsl (ubuntu), using `yarn dev` it works fine. I can point my browser at `http://localhost:8080` and my app runs with no problems.\n\nI also have this basic dockerfile which I build in the normal way:\n\n```\nfrom node:alpine3.15\nworkdir /app\ncopy package.json /app/package.json\nrun yarn\ncopy src /app/src\ncopy public /app/public\ncopy vite.config.js /app/\ncmd [\"yarn\", \"dev\", \"--debug\"]\n```\n\nBut, when I run this in wsl:\n\n```\ndocker run -it --rm -p 8080:8080 bpm\n```\n\nThe app no longer works.\n\nWhat do I mean by 'no longer works'? Well, that's where it gets interesting. When the app starts the debugging output shows that vite has resolved all of its dependencies, so vite appears to be working, it reports no errors on stdout, and reports its port bindings. But, when I access the app root: `http://localhost:8080` I get a 404.\n\nI can access the files in the app if I enter their URI's: `curl http://localhost:8080/src/main.jsx` returns the appropriate source-code. So, this isn't a docker networking problem.\n\nIf I navigate to `http://localhost:8080/index.html` then that page loads and the network tab shows no problems, but the console reports an error:\n\n```\n@vitejs/plugin-react can't detect preamble. Something is wrong. See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201\n at Toolbar.jsx:6:11\n```\n\nWhere `Toolbar.jsx` is on of my component files.\n\nJust in case, I read the docs and tried adding:\n\n```\norigin: 'http://127.0.0.1:8080'\n```\n\nTo the vite server config and it hasn't helped (surprisingly).\n\nThere seem to be some other questions on this topic (here and here), but those questions and answers don't seem to cover the actual behaviour I'm seeing, though I have read them and applied their solutions they don't help.\n\nI've also tried different base containers for node, and different versions of node. It doesn't seem to make any difference.\n\nI've been banging my head against this all evening but it's getting annoying now. Any insights would be appreciated.\n\n### Note\n\nI can `vite build` the app and serve it in nginx, and it works, but that really doesn't help during development.\n\n========================================\n\nTop Answer:\nWhat i learned from some of open source projects\n\n```\n// https://vitejs.dev/config/\n export default defineConfig({\n plugins: [react()],\n server: {\n // watch: {\n // usePolling: true,\n // },\n host: true, // Here\n // strictPort: true,\n // port: 5000\n }\n})\n```\n\nIf you want to run your application on vite default port (5173), you have to make **host:true** and if you want on some other port you can mention that under server object as i have given a reference code\n\n```\n# Official Image using node 20 alphine\nFROM node:20-alpine \n\n# working directory \nWORKDIR /app/fronted\n\n# Changes in package* . json file \nCOPY package*.json ./\n\n# Install Dependencies\nRUN npm install\n\n# Copy all changes on fronted\nCOPY . .\n\n# expose the app on port 5173\nEXPOSE 5173\n\n# Start your frontend application\nCMD [ \"npm\", \"run\", \"dev\", \"--\", \"--host\", \"0.0.0.0\"]\n```\n\nDockerfile\n\n========================================\n\nCode:\n```json\n{\n  \"name\": \"bpm\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"preview\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\",\n    \"react-icons\": \"^4.4.0\",\n    \"uuid\": \"^9.0.0\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^18.0.17\",\n    \"@types/react-dom\": \"^18.0.6\",\n    \"@vitejs/plugin-react\": \"^2.1.0\",\n    \"vite\": \"^3.1.0\"\n  }\n}\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\nexport default defineConfig({\n  server: {host:'0.0.0.0', port:8080},\n  plugins: [react()]\n})\n```\n\n```text\nfrom node:alpine3.15\nworkdir /app\ncopy package.json /app/package.json\nrun yarn\ncopy src /app/src\ncopy public /app/public\ncopy vite.config.js /app/\ncmd [\"yarn\", \"dev\", \"--debug\"]\n```\n\n```bash\ndocker run -it --rm -p 8080:8080 bpm\n```\n\n```text\n@vitejs/plugin-react can't detect preamble. Something is wrong. See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201\n    at Toolbar.jsx:6:11\n```\n\n```bash\norigin: 'http://127.0.0.1:8080'\n```\n\n```text\nyarn dev\n```\n\n```text\nhttp://localhost:8080\n```\n\n```text\nhttp://localhost:8080\n```\n\n```text\ncurl http://localhost:8080/src/main.jsx\n```\n\n```text\nhttp://localhost:8080/index.html\n```\n\n```text\nToolbar.jsx\n```\n\n```text\nvite build\n```\n\n```text\nexport default defineConfig({\n plugins: [react()],\n server: {\n  watch: {\n   usePolling: true,\n  },\n  host: true, // Here\n  strictPort: true,\n  port: 8080, \n}\n```\n\n```text\nFROM node:alpine\nWORKDIR /app\nCOPY package.json .\nRUN yarn\n# copy all files\nCOPY . .\ncmd [\"yarn\", \"dev\", \"--debug\"]\n```\n\n```text\n.git\n.vscode\n.dockerignore\n.gitignore\n.env\nconfig\nbuild\nnode_modules\ndocker-compose.yaml\nDockerfile\nREADME.md\n```\n\n```text\n// https://vitejs.dev/config/\n   export default defineConfig({\n  plugins: [react()],\n  server: {\n    // watch: {\n    //  usePolling: true,\n    // },\n    host: true, // Here\n    // strictPort: true,\n    // port: 5000\n  }\n})\n```\n\n```text\n# Official Image using node 20 alphine\nFROM node:20-alpine  \n\n# working directory \nWORKDIR /app/fronted\n\n# Changes in package* . json file \nCOPY package*.json ./\n\n# Install Dependencies\nRUN npm install\n\n# Copy all changes on fronted\nCOPY . .\n\n# expose the app on port 5173\nEXPOSE 5173\n\n# Start your frontend application\nCMD [ \"npm\", \"run\", \"dev\", \"--\", \"--host\", \"0.0.0.0\"]\n```\n\n```text\n...\nexport default defineConfig(\n{\n    plugins: [vue()],\n\n    server:  {\n        port: 8080,\n        host: '0.0.0.0'\n    },\n\n    host: true,\n...\n```\n\n```text\nvite.config.js\n```\n\n```text\nhost: '0.0.0.0'\n```\n\n```text\nhost: true\n```\n\n========================================\n\nComments:\n- Please upload to github a minimal working solution with dockerfile, codes etc that can reproduce the same error you are seeing with your actual project.\n- Thanks, but that produced exactly the same results as my original attempt at this. To bypass any potential networking problems, I've exec'd into the container and curl'd `http:&#47;&#47;localhost:8080` (using your config as posted here) and I get a 404.\n- I think i know your problem, you are missing some files that you didn't move inside your container like configs one and the index it self, i will post a proper dockerfile for you\n- Wow. @FatehMohamed - I was about to write your comment off, because I already have the config file inside my container. However, I did pay attention and I noticed that I was missing the base index.html file. So, you were write, I was missing a file. All this time, something so simple! I have the index.html file in my project root and I hadn't even noticed it. I have a copy in my `public` folder and another in my `src` (probably both redundant). If you write this up as an answer I'll give you the bounty if you like.\n- I'm glad you fixed it, i added some clarifications on the answer\n- You were using \"Create react app\" before? because the file structure is not that same as vite, for vite index.html has to be in root directory and if you use CRA it has to be in public one\n- Ah! That's interesting, thanks. I didn't realise that. I had started with CRA (as I usually do), and only later became aware of vite and patched it into my project. I really like it, despite how confusing it can be.\n- thanks again. One thing, it might be worth mentioning in your answer that the `COPY . .` line is only sensible if you have a `.dockerignore` file that excludes the files you don't want in the image. Or, change it to copy only the files you want (which is my preferred approach)(although I do use the `.dockerignore` to save having to copy my `node_modules` folder into the docker staging area, which can take a long time for a complex project). In fact, `COPY . .` is potentially dangerous so we (the companies I work for) ban it outright and insist on a targetted copy.\n- That's a good strategy and more safe yes\n- \"your index.html have to be on your root directory in dev mode\" that saved me, thanks ! An error should be raised or something x)","metadata":{"transformedAt":"2026-08-18T18:33:46.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":354,"estimatedTokens":2240}}102{"id":"stack-73594809","source":"stackoverflow","questionId":73594809,"title":"What is the difference between npm init vite@latest and npm init vite?","tags":["reactjs","npm","vite"],"text":"Title: What is the difference between npm init vite@latest and npm init vite?\nTags: reactjs, npm, vite\nSource: Stack Overflow\n\nQuestion:\nI recently started using vite to make my react apps as I grew tired of the excruciatingly long install times for create-react-app. However, as I looked online, I found different ways of making a vite app. On the official documentation, it says to use npm init vite@latest while other tutorials use npm init vite. Both require you to install different dependencies on your machine before you can run the commands. However, it appears that they both do essentially the same thing. Can anyone explain the difference between the 2 commands?\n\n========================================\n\nCode:\n```text\nnpm init vite@latest\n```\n\n```text\nnpm init vite\n```\n\n```text\ncreate-vite\n```\n\n```text\n@latest\n```\n\n```text\ncreate-vite\n```\n\n```text\nnpm init\n```\n\n```text\nnpm init foo\n```\n\n```text\nnpm init foo@latest\n```\n\n```text\nnpm init foo@1.2.3\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.400Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":45,"estimatedTokens":242}}103{"id":"stack-75492238","source":"stackoverflow","questionId":75492238,"title":"Difference in using create vite@latest vs create-next-app vs create-react-app","tags":["reactjs","next.js","vite"],"text":"Title: Difference in using create vite@latest vs create-next-app vs create-react-app\nTags: reactjs, next.js, vite\nSource: Stack Overflow\n\nQuestion:\nI know that using create react-app is much slower than using create vite@latest and that using create next-app specifies you want to use the next.js framework, but what about using create vite@latest vs create next-app. Is create-next-app also slower than create vite@latest? and can I use create vite@latest first and then install the next.js framework? because I only see examples of next.js being used when react apps are initialized with create next-app","metadata":{"transformedAt":"2026-08-18T18:33:46.400Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":6,"estimatedTokens":152}}104{"id":"stack-75486304","source":"stackoverflow","questionId":75486304,"title":"Vite add assets path prefix / change assets path in compiled files","tags":["javascript","path","vite"],"text":"Title: Vite add assets path prefix / change assets path in compiled files\nTags: javascript, path, vite\nSource: Stack Overflow\n\nQuestion:\nCould you tell me please, how to change how vite assets path is built, but only for compiled files?\nI mean, for example, I have file index.html like:\n\n```\n\n \n \n \n \n Vite App\n \n \n \n \n\n```\n\nand here I have script with src=\"/src/main.js\"\n\nWhen I compile it, I get src=\"/assets/index-c371877d.js\"\n\nI am making ESP32 webserver, and because of some internal moments I need to put compiled files in another folder, on SD card.\n\nI can change output directory using vite.config.js, here I have:\n\n```\nexport default defineConfig({\n plugins: [vue(), vueJsx()],\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url))\n }\n },\n build: {\n outDir: \"../../SD/modules/test\", // test is project name\n },\n})\n```\n\nBut the problem is, that compiled files have same relative path, while I need to have modules/%moduleName%/%relative path%\n\nSo instead of src=\"/assets/index-c371877d.js\" I need src=\"module/test/assets/index-c371877d.js\"\n\nI tried to change vite assetsDir:\n\n```\nexport default defineConfig({\n plugins: [vue(), vueJsx()],\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url))\n }\n },\n build: {\n outDir: \"../../SD/modules/test\",\n assetsDir: \"modules/test\"\n})\n```\n\nNow it adds modules/test before path, but compiled files are put into outDir + assetsDir directory, what I don't want.\n\nTell me please, how could I just prepend necessary path data without changing real assets directory? Thank you in advance.\n\n========================================\n\nCode:\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\">\n    <link rel=\"icon\" href=\"/favicon.ico\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <title>Vite App</title>\n  </head>\n  <body>\n    <script type=\"module\" src=\"/src/main.js\"></script>\n  </body>\n</html>\n```\n\n```js\nexport default defineConfig({\n  plugins: [vue(), vueJsx()],\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url))\n    }\n  },\n  build: {\n    outDir: \"../../SD/modules/test\", // test is project name\n  },\n})\n```\n\n```js\nexport default defineConfig({\n  plugins: [vue(), vueJsx()],\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url))\n    }\n  },\n  build: {\n    outDir: \"../../SD/modules/test\",\n    assetsDir: \"modules/test\"\n})\n```\n\n```js\nexport default defineConfig({\n  plugins: [vue(), vueJsx()],\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url))\n    }\n  },\n  build: {\n    outDir: Config.modulesDirRelativePath + \"/vue-project\"\n  },\n  base: \"/modules/vue-project\"\n})\n```\n\n========================================\n\nComments:\n- Worked! I wanted to change assets path from \"/assets/[files]\" to \"./assets/[files]\". base: \"./\", did the trick.\n- same for me from \"/assets/[files]\" to \"./assets/[files]\" for electron integration","metadata":{"transformedAt":"2026-08-18T18:33:46.400Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":134,"estimatedTokens":742}}105{"id":"stack-74271099","source":"stackoverflow","questionId":74271099,"title":"tailwindcss: animate-spin not showing up","tags":["reactjs","tailwind-css","vite","tailwind-ui","daisyui"],"text":"Title: tailwindcss: animate-spin not showing up\nTags: reactjs, tailwind-css, vite, tailwind-ui, daisyui\nSource: Stack Overflow\n\nQuestion:\nI wanted to include a loading spinner from tailwind-css and according to tailwindcss documentation, this should be available with the className=\"animate-spin\".\n\nI'm using React18 created from Vite. I've also installed daisyui in addition to tailwindcss.\n\nWhen I apply \"animate-spin\" and inspect in the browser, I can see that it's been added when I select the spinner. It's definitely there and spinning in my button element, but for some reason, it just doesn't show up/is transparent.\n\nHere is my code:\n`\n\n```\n\n \n \n Loading...\n \n \n```\n\n`\n\nI've tried taking out \"border-transparent\" from the button className, but it still didn't show.\n\nAppreciate any help from anybody who knows Tailwind. Both my App.css and index.css are blank aside from the tailwind imports and applying a universal font.\n\nI've tried adjusting the color and background-color properties of the svg element with the spinner. So far only making the background-color white has made it shown up but only as a spinning squre.\n\nI've tried adjusting text-white to the svg element but it doesn't show up and changing the color property doesn't make it show up.\n\n========================================\n\nTop Answer:\nYour svg element has nothing in it.\nYou would need to add a path for example.\n\nIf you want to have the exact same svg from tailwind website, check the code down below:\n\n```\n\n \n \n \n \n\n```\n\n========================================\n\nCode:\n```text\n<div className=\"bg-gray-50 px-4 py-3 text-right sm:px-6\">\n                                <button\n                                    type=\"submit\"\n                                    className=\"inline-flex justify-center rounded-md border border-transparent bg-indigo-600 py-2 px-4 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2\"\n                                >\n                                    <svg className=\"animate-spin h-5 w-5 mr-3\"></svg>\n                                    Loading...\n                                </button>\n                            </div>\n```\n\n```text\n<button type=\"button\" className=\"bg-indigo-500\" disabled>\n    <svg class=\"animate-spin -ml-1 mr-3 h-5 w-5 text-white\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\">\n        <circle class=\"opacity-25\" cx=\"12\" cy=\"12\" r=\"10\" stroke=\"currentColor\" stroke-width=\"4\"></circle>\n        <path class=\"opacity-75\" fill=\"currentColor\" d=\"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z\"></path>\n    </svg>\n</button>\n```\n\n========================================\n\nComments:\n- Hi, first of all, super grateful for your time looking at this. I've tried this: And it appears as a spinning square when it should appear like this: tailwindcss.com/docs/animation Do you have any experience getting this to work?\n- you can use some icon library like font awesome to get circle icon like in tailwind doc. Or you can extract svg icon directly with devtool stackoverflow.com/questions/43804171/&hellip; when you done get the icon, just put `animate-spin` class to that icon element\n- Thanks so much! I got it working with this.","metadata":{"transformedAt":"2026-08-18T18:33:46.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":80,"estimatedTokens":832}}106{"id":"stack-69613533","source":"stackoverflow","questionId":69613533,"title":"Testing React app with Jest, using Vite as a module Bundler; import.meta error","tags":["reactjs","testing","jestjs","vite","esbuild"],"text":"Title: Testing React app with Jest, using Vite as a module Bundler; import.meta error\nTags: reactjs, testing, jestjs, vite, esbuild\nSource: Stack Overflow\n\nQuestion:\ni am testing a React-Typescript application with Jest; my application uses Vite as a module bundler.\nThe issue is, everytime i run tests and jest encounters an import.meta.ENV_VAR_NAME statement i get the following error: \"SyntaxError: Cannot use 'import.meta' outside a module\"\n\nThis is my jest.config.js file:\n\n```\nmodule.exports = {\nroots: [\"/src\"],\nsetupFilesAfterEnv: [\"/jest/jest.setup.js\"],\ncollectCoverageFrom: [\"src//*.{js,jsx,ts,tsx}\", \"!src//.d.ts\"],\ntestMatch: [\n \"/src//tests//.{js,jsx,ts,tsx}\",\n \"/src/*/.{spec,test}.{js,jsx,ts,tsx}\"\n],\ntestEnvironment: \"jsdom\",\ntransform: {\n // \"^.+\\.(js|jsx|mjs|cjs|ts|tsx)$\": \"esbuild-jest\",\n \"^.+\\.(js|jsx|mjs|cjs|ts|tsx)$\": \"@swc/jest\",\n \"^.+\\.scss$\": \"jest-scss-transform\",\n \"^.+\\.css$\": \"/jest/mocks/cssMock.js\"\n},\ntransformIgnorePatterns: [\n \"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$\",\n \"^.+\\.module\\.(css|sass|scss)$\"\n],\nwatchPlugins: [\n \"jest-watch-typeahead/filename\",\n \"jest-watch-typeahead/testname\"\n],\nresetMocks: true,\nmoduleDirectories: [\"node_modules\", \"src\"],\nmoduleNameMapper: {\n \"\\.worker\": \"/src/seo/mocks/workerMock.ts\",\n \"\\.(css|sass|scss)$\": \"identity-obj-proxy\"\n}\n};\n```\n\nIn transform key of jest.config i tried using either @swc/jest and esbuild-jest, but none fixed the import.meta issue; is there a solution to this problem? Can i achieve it without using Babel?\n\nThanks in advance for your time\n\n========================================\n\nTop Answer:\nOR! You could just mock the env vars in your Jest context. Much simpler.\n\n(this is already answered on another SO post)\nTest suite failed to run import.meta.env.VITE_*\n\n========================================\n\nCode:\n```text\nmodule.exports = {\nroots: [\"<rootDir>/src\"],\nsetupFilesAfterEnv: [\"<rootDir>/jest/jest.setup.js\"],\ncollectCoverageFrom: [\"src//*.{js,jsx,ts,tsx}\", \"!src//.d.ts\"],\ntestMatch: [\n    \"<rootDir>/src//tests//.{js,jsx,ts,tsx}\",\n    \"<rootDir>/src/*/.{spec,test}.{js,jsx,ts,tsx}\"\n],\ntestEnvironment: \"jsdom\",\ntransform: {\n    // \"^.+\\.(js|jsx|mjs|cjs|ts|tsx)$\": \"esbuild-jest\",\n    \"^.+\\.(js|jsx|mjs|cjs|ts|tsx)$\": \"@swc/jest\",\n    \"^.+\\.scss$\": \"jest-scss-transform\",\n    \"^.+\\.css$\": \"<rootDir>/jest/mocks/cssMock.js\"\n},\ntransformIgnorePatterns: [\n    \"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$\",\n    \"^.+\\.module\\.(css|sass|scss)$\"\n],\nwatchPlugins: [\n    \"jest-watch-typeahead/filename\",\n    \"jest-watch-typeahead/testname\"\n],\nresetMocks: true,\nmoduleDirectories: [\"node_modules\", \"src\"],\nmoduleNameMapper: {\n    \"\\.worker\": \"<rootDir>/src/seo/mocks/workerMock.ts\",\n    \"\\.(css|sass|scss)$\": \"identity-obj-proxy\"\n}\n};\n```\n\n```text\n.env\n```\n\n```text\n.env\n```\n\n```text\nimport.meta.env.YOUR_VAR\n```\n\n```text\nprocess.env.YOUR_VAR\n```\n\n```text\nvite.config.ts\n```\n\n```text\nimport EnvironmentPlugin from 'vite-plugin-environment';\n```\n\n```text\nEnvironmentPlugin('all')\n```\n\n```text\nplugins: [react(), EnvironmentPlugin('all')]\n```\n\n```text\nimport.meta.env\n```\n\n```text\nprocess.env.YOUR_VAR\n```\n\n```text\nimport.meta.env.YOUR_VAR\n```\n\n```text\nprocess.env.YOUR_VAR\n```\n\n```text\nvite-plugin-environment\n```\n\n```text\nprocess.env.YOUR_VAR\n```\n\n========================================\n\nComments:\n- @Ju-riJung yes i solved it; i changed all my import.meta into process.env in order to not bother jest; as for vite, with a vite plugin called env-compatible, at compile time converts the process.env into import.meta so that vite won't be bothered.\n- *Finally* a solution that works - thank you. Tussled with this one for entirely too long. Such an annoying constraint.\n- That's a lot of steps for something that just needs mocked in the jest files!","metadata":{"transformedAt":"2026-08-18T18:33:46.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":153,"estimatedTokens":942}}107{"id":"stack-70656230","source":"stackoverflow","questionId":70656230,"title":"Overriding Vuetify variables when building a Vue2+Vuetify app with Vite","tags":["vue.js","sass","vuejs2","vuetify.js","vite"],"text":"Title: Overriding Vuetify variables when building a Vue2+Vuetify app with Vite\nTags: vue.js, sass, vuejs2, vuetify.js, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to migrate a Vue2+Vuetify app from Vue-CLI/Webpack to Vite. The app has a couple of SCSS files, `main.scss` and `variables.scss` with the latter imported by the former.\n\n### main.scss\n\n```\n@import 'variables';\n// global style rules (omitted)\n```\n\n### variables.scss\n\n```\n// override some Vuetify variables and define some variables of my own, e.g.\n// Vuetify default is 48px\n$data-table-mobile-row-min-height: 32px;\n\n// Increase default height by 10px\n// https://vuetifyjs.com/en/api/v-date-picker/#sass-variables\n$date-picker-table-height: 252px;\n```\n\n`main.scss` is imported in the root component, which means that:\n\n- rules in `main.scss` are applied to every component\n\n- variables in `variables.scss` can be referred to in any component without any additional imports\n\n- variables defined by Vuetify can be referred to in any component without any additional imports\n\n- variables in `variables.scss` override Vuetify variables with the same name\n\nHowever, after migrating to Vite, only (1) still worked. I was able to resolve (2) and (3) by adding the following to `vite.config.js`\n\n```\nexport default defineConfig({\n // other config omitted\n\n css: {\n preprocessorOptions: {\n scss: {\n // Make the variables defined in these files available to all components, without requiring an explicit\n // @import of the files themselves\n additionalData: `@import \"./src/styles/variables\"; @import \"vuetify/src/styles/settings/_variables\";`\n },\n },\n },\n});\n```\n\nHowever, it's still the case that (4) no longer works.\n\nAs far as I know, the vuetify-loader is responsible for this behaviour when building with Vue-CLI, but it's not clear how to override Vuetify variables when building with Vite?\n\n========================================\n\nCode:\n```css\n@import 'variables';\n// global style rules (omitted)\n```\n\n```css\n// override some Vuetify variables and define some variables of my own, e.g.\n// Vuetify default is 48px\n$data-table-mobile-row-min-height: 32px;\n\n// Increase default height by 10px\n// https://vuetifyjs.com/en/api/v-date-picker/#sass-variables\n$date-picker-table-height: 252px;\n```\n\n```js\nexport default defineConfig({\n  // other config omitted\n\n  css: {\n    preprocessorOptions: {\n      scss: {\n        // Make the variables defined in these files available to all components, without requiring an explicit\n        // @import of the files themselves\n        additionalData: `@import \"./src/styles/variables\"; @import \"vuetify/src/styles/settings/_variables\";`\n      },\n    },\n  },\n});\n```\n\n```text\nmain.scss\n```\n\n```text\nvariables.scss\n```\n\n```text\nmain.scss\n```\n\n```text\nmain.scss\n```\n\n```text\nvariables.scss\n```\n\n```text\nvariables.scss\n```\n\n```text\nvite.config.js\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport Components from 'unplugin-vue-components/vite'\nimport { VuetifyResolver } from 'unplugin-vue-components/resolvers'\n\nexport default defineConfig({\n  plugins: [\n    ⋮\n    Components({\n      resolvers: [VuetifyResolver()],\n    }),\n  ],\n})\n```\n\n```js\n// vite.config.js\nexport default defineConfig({\n  css: {\n    preprocessorOptions: {\n      sass: {\n        // ❌ no semicolons for indented syntax\n        // additionalData: `@import \"./src/styles/variables\"; @import \"vuetify/src/styles/settings/_variables\";`\n\n        // ✅\n        additionalData: [\n          '@import \"./src/styles/variables\"',\n          '@import \"vuetify/src/styles/settings/_variables\"',\n          '', // end with newline\n        ].join('\\n'),\n      },\n    },\n  },\n})\n```\n\n```js\n// plugins/vuetify.js\nimport Vue from 'vue'\n\n// ❌ defeats dynamic imports from unplugin-vue-components\n// import Vuetify from 'vuetify'\n// import 'vuetify/dist/vuetify.min.css'\n\n// ✅\nimport Vuetify from 'vuetify/lib/framework'\n\nVue.use(Vuetify)\n\nexport default new Vuetify({/* options */})\n```\n\n```text\nunplugin-vue-components\n```\n\n```text\nvuetify-loader\n```\n\n```text\nunplugin-vue-components\n```\n\n```text\nvuetify-loader\n```\n\n```text\nadditionalData\n```\n\n```text\nvuetify/lib/framework\n```\n\n```text\nvuetify\n```\n\n========================================\n\nComments:\n- Thank you, that helped me a lot! But adding @import '~vuetify/src/styles/styles.sass' to App.vue in your Stackblitz example produces a runtime error [plugin:vite:css] Can't find stylesheet to import. Do you have any idea why?","metadata":{"transformedAt":"2026-08-18T18:33:46.400Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":205,"estimatedTokens":1112}}108{"id":"stack-79487101","source":"stackoverflow","questionId":79487101,"title":"TailwindCSS v4 dark theme by class not working without dark tag","tags":["html","css","tailwind-css","vite","tailwind-css-4"],"text":"Title: TailwindCSS v4 dark theme by class not working without dark tag\nTags: html, css, tailwind-css, vite, tailwind-css-4\nSource: Stack Overflow\n\nQuestion:\nI'm trying to set up a custom theme in Tailwind CSS v4 that auto-switches to dark mode **without adding the `dark:` prefix to every custom class.**\n\n**In Tailwind v3, my setup was:**\n\n**index.css:**\n\n```\n:root {\n --color-primary100: #0A7280;\n --color-primary50: #BAD7DB;\n --color-bgBase: #FDFDFD;\n}\n```\n\n**tailwind.config.js:**\n\n```\nexport default {\n darkMode: 'class',\n content: [\"./index.html\", \"./src/**/*.{js,ts,jsx,tsx}\"],\n plugins: [tailwindCssForms, containerQueries],\n theme: {\n extend: {\n colors: {\n primary100: \"var(--color-primary100, #0A7280)\",\n primary50: \"var(--color-primary50, #BAD7DB)\",\n bgBase: \"var(--color-bgBase, #FDFDFD)\",\n },\n },\n },\n}\n```\n\nToggling the dark mode by adding a `dark` class to `` worked as expected **without having to set** a `dark:bg-primary100-V2 bg-primary100` everywhere :\n\n**A single `bg-primary100` will handle it both themes** (multiply it by each customized props and you see why this is important)\n\n**After migrating to Tailwind CSS v4 (https://tailwindcss.com/docs/dark-mode), I updated my CSS using the new `@theme` syntax :**\n\n```\n@import 'tailwindcss';\n@plugin '@tailwindcss/forms';\n@plugin '@tailwindcss/container-queries';\n\n@custom-variant dark (&:where(.dark, .dark *));\n\n@theme {\n --color-bgContrast: #f9f9f9;\n}\n\n/*and was hopping for this to do the job but i tried many others */\n@theme dark: {\n --color-bgContrast: #66C8B6;\n}\n```\n\nI expected that adding `` would update `--color-bgContrast` to `#66C8B6`, but it doesn't work as intended. My goal is to **avoid duplicating styles with multiple `dark:` prefixes across components everywhere**.\n\nHas anyone managed to achieve this centralized dark theme approach in v4 or faced a similar issue? Any insights or workarounds would be appreciated.\n\n========================================\n\nTop Answer:\nBasically, Wongjn has already answered the question, but I would like to draw attention to the use of `@variant dark`.\n\nWith `@variant`, you don't need to update the code if, for example, in the future you no longer want to identify dark mode as `.dark`. So, if you modify the `@custom-variant` setting, this will automatically take effect in the `@variant`.\n\n- `@variant` directive - TailwindCSS v4 Docs\n\n```\ndocument.querySelector('button').addEventListener('click', () => {\n document.documentElement.classList.toggle('dark');\n});\n```\n\n```\n\n@custom-variant dark (&:where(.dark, .dark *));\n\n@theme {\n --color-bgContrast: #f9f9f9;\n}\n\n@layer theme {\n :root, :host {\n @variant dark {\n --color-bgContrast: #66C8B6;\n }\n }\n}\n\nToggle\n```\n\nAnd if change rule of dark mode:\n\n```\ndocument.querySelector('button').addEventListener('click', () => {\n document.documentElement.classList.toggle('new-dark');\n});\n```\n\n```\n\n/* changed classname from .dark to .new-dark */\n@custom-variant dark (&:where(.new-dark, .new-dark *));\n\n@theme {\n --color-bgContrast: #f9f9f9;\n}\n\n@layer theme {\n :root, :host {\n /* working without modification */\n @variant dark {\n --color-bgContrast: #66C8B6;\n }\n }\n}\n\nToggle\n```\n\nAdditionally, without JS, it's possible to detect whether the system prefers light or dark mode by default, and integrate this into the `dark:` variant behavior. For this, your light/dark toggle needs to support three states: system/light/dark. You'll also need an extra `.system` class, but the `dark:` variant can work the same way with both `.system` and `.dark` classes:\n\n- Manual dark mode toggle, but by default it should the system scheme\n\n========================================\n\nCode:\n```css\n:root {\n    --color-primary100: #0A7280;\n    --color-primary50: #BAD7DB;\n    --color-bgBase: #FDFDFD;\n}\n```\n\n```js\nexport default {\n    darkMode: 'class',\n    content: [\"./index.html\", \"./src/**/*.{js,ts,jsx,tsx}\"],\n    plugins: [tailwindCssForms, containerQueries],\n    theme: {\n        extend: {\n            colors: {\n                primary100: \"var(--color-primary100, #0A7280)\",\n                primary50: \"var(--color-primary50, #BAD7DB)\",\n                bgBase: \"var(--color-bgBase, #FDFDFD)\",\n            },\n        },\n    },\n}\n```\n\n```css\n@import 'tailwindcss';\n@plugin '@tailwindcss/forms';\n@plugin '@tailwindcss/container-queries';\n\n@custom-variant dark (&:where(.dark, .dark *));\n\n@theme {\n  --color-bgContrast: #f9f9f9;\n}\n\n/*and was hopping for this to do the job but i tried many others */\n@theme dark: {\n  --color-bgContrast: #66C8B6;\n}\n```\n\n```text\ndark:\n```\n\n```text\ndark\n```\n\n```text\n<html>\n```\n\n```text\ndark:bg-primary100-V2 bg-primary100\n```\n\n```text\nbg-primary100\n```\n\n```text\n@theme\n```\n\n```text\n<html class=\"dark\">\n```\n\n```text\n--color-bgContrast\n```\n\n```text\n#66C8B6\n```\n\n```text\ndark:\n```\n\n```css\n@layer theme {\n  .dark {\n    --color-bgContrast: #66C8B6;\n  }\n}\n```\n\n```js\ndocument.querySelector('button').addEventListener('click', () => {\n  document.documentElement.classList.toggle('dark');\n});\n```\n\n```html\n<script src=\"https://unpkg.com/@tailwindcss/browser@4.0.9\"></script>\n\n<style type=\"text/tailwindcss\">\n@import 'tailwindcss';\n\n@custom-variant dark (&:where(.dark, .dark *));\n\n@theme {\n  --color-bgContrast: #f9f9f9;\n}\n\n@layer theme {\n  .dark {\n    --color-bgContrast: #66C8B6;\n  }\n}\n</style>\n\n<button class=\"grid place-items-center size-20 bg-bgContrast\">Toggle</button>\n```\n\n```text\ntheme\n```\n\n```text\n.dark\n```\n\n```text\ndark\n```\n\n```js\ndocument.querySelector('button').addEventListener('click', () => {\n  document.documentElement.classList.toggle('dark');\n});\n```\n\n```html\n<script src=\"https://unpkg.com/@tailwindcss/browser@4.0.9\"></script>\n<style type=\"text/tailwindcss\">\n@custom-variant dark (&:where(.dark, .dark *));\n\n@theme {\n  --color-bgContrast: #f9f9f9;\n}\n\n@layer theme {\n  :root, :host {\n    @variant dark {\n      --color-bgContrast: #66C8B6;\n    }\n  }\n}\n</style>\n\n<button class=\"grid place-items-center size-20 bg-bgContrast\">Toggle</button>\n```\n\n```js\ndocument.querySelector('button').addEventListener('click', () => {\n  document.documentElement.classList.toggle('new-dark');\n});\n```\n\n```html\n<script src=\"https://unpkg.com/@tailwindcss/browser@4.0.9\"></script>\n<style type=\"text/tailwindcss\">\n/* changed classname from .dark to .new-dark */\n@custom-variant dark (&:where(.new-dark, .new-dark *));\n\n@theme {\n  --color-bgContrast: #f9f9f9;\n}\n\n@layer theme {\n  :root, :host {\n    /* working without modification */\n    @variant dark {\n      --color-bgContrast: #66C8B6;\n    }\n  }\n}\n</style>\n\n<button class=\"grid place-items-center size-20 bg-bgContrast\">Toggle</button>\n```\n\n```text\n@variant dark\n```\n\n```text\n@variant\n```\n\n```text\n.dark\n```\n\n```text\n@custom-variant\n```\n\n```text\n@variant\n```\n\n```text\n@variant\n```\n\n```text\ndark:\n```\n\n```text\n.system\n```\n\n```text\ndark:\n```\n\n```text\n.system\n```\n\n```text\n.dark\n```\n\n========================================\n\nComments:\n- @JulienJ, while I understand your opinion, I believe that the CSS-first configuration is a great concept, though it was still in its early stages. I think even in the time between v4.0 and 4.1, many important improvements were made - for example, the safelist was brought back, nearly every plugin became customizable, etc. Of course, if you prefer not to learn it, the JS-based configuration is still available as an option: TailwindCSS v4 is backwards compatible with v3 - How to use `tailwind.config.js` in v4\n- This information currently lacks in the official docs here - imho it should be there too.","metadata":{"transformedAt":"2026-08-18T18:33:46.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":370,"estimatedTokens":1869}}109{"id":"stack-75059354","source":"stackoverflow","questionId":75059354,"title":"No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"","tags":["bootstrap-4","vuejs3","vite","bootstrap-vue"],"text":"Title: No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\nTags: bootstrap-4, vuejs3, vite, bootstrap-vue\nSource: Stack Overflow\n\nQuestion:\nI try to start a brand new Vue project and want to add Bootstrap to it.\n\nAll is good, but when i try to launch it, i have this error :\n\n`node_modules/bootstrap-vue/esm/vue.js:13:7: ERROR: No matching export in node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"`\n\ni started with `npm init vue@latest`\nafter that i done an `npm install`.\nTo install bootstrap i made `npm install bootstrap bootstrap-vue`.\nIf at this point i made an npm run all is good but when i try to import bootstrap in my project i get the error. Here is how i use it :\n\n```\nimport { createApp } from 'vue'\nimport { createPinia } from 'pinia'\nimport { BootstrapVue } from 'bootstrap-vue'\n\nimport App from './App.vue'\nimport router from './router'\n\nimport './assets/main.css'\n\nconst app = createApp(App)\n\nVue.use(BootstrapVue)\n\napp.use(createPinia())\napp.use(router)\n\napp.mount('#app')\n```\n\nand here is the trace of the error :\n\n```\nnpm run dev\n\n> test@0.0.0 dev C:\\Users\\ycolin\\projet\\test\n> vite\n\n VITE v4.0.4 ready in 2204 ms\n\n ➜ Local: http://127.0.0.1:5173/\n ➜ Network: use --host to expose\n ➜ press h to show help\nX [ERROR] No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\n\n node_modules/bootstrap-vue/esm/vue.js:13:7:\n 13 │ import Vue from 'vue';\n ╵ ~~~\n\nX [ERROR] No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\n\n node_modules/bootstrap-vue/esm/vue.js:13:7:\n 13 │ import Vue from 'vue';\n ╵ ~~~\n\nX [ERROR] No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\n\n node_modules/bootstrap-vue/esm/vue.js:13:7:\n 13 │ import Vue from 'vue';\n ╵ ~~~\n\nX [ERROR] No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\n\n node_modules/bootstrap-vue/esm/vue.js:13:7:\n 13 │ import Vue from 'vue';\n ╵ ~~~\n\nX [ERROR] No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\n\n node_modules/bootstrap-vue/esm/vue.js:13:7:\n 13 │ import Vue from 'vue';\n ╵ ~~~\n\nX [ERROR] No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\n\n node_modules/bootstrap-vue/esm/vue.js:13:7:\n 13 │ import Vue from 'vue';\n ╵ ~~~\n\nX [ERROR] No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\n\n node_modules/portal-vue/dist/portal-vue.esm.js:13:7:\n 13 │ import Vue from 'vue';\n ╵ ~~~\n\n(node:28520) UnhandledPromiseRejectionWarning: Error: Build failed with 7 errors:\nnode_modules/bootstrap-vue/esm/vue.js:13:7: ERROR: No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\nnode_modules/bootstrap-vue/esm/vue.js:13:7: ERROR: No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\nnode_modules/bootstrap-vue/esm/vue.js:13:7: ERROR: No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\nnode_modules/bootstrap-vue/esm/vue.js:13:7: ERROR: No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\nnode_modules/bootstrap-vue/esm/vue.js:13:7: ERROR: No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\n...\n at failureErrorWithLog (C:\\Users\\ycolin\\projet\\test\\node_modules\\esbuild\\lib\\main.js:1604:15)\n at C:\\Users\\ycolin\\projet\\test\\node_modules\\esbuild\\lib\\main.js:1056:28\n at runOnEndCallbacks (C:\\Users\\ycolin\\projet\\test\\node_modules\\esbuild\\lib\\main.js:1476:61)\n at buildResponseToResult (C:\\Users\\ycolin\\projet\\test\\node_modules\\esbuild\\lib\\main.js:1054:7)\n at C:\\Users\\ycolin\\projet\\test\\node_modules\\esbuild\\lib\\main.js:1166:14\n at responseCallbacks. (C:\\Users\\ycolin\\projet\\test\\node_modules\\esbuild\\lib\\main.js:701:9)\n at handleIncomingPacket (C:\\Users\\ycolin\\projet\\test\\node_modules\\esbuild\\lib\\main.js:756:9)\n at Socket.readFromStdout (C:\\Users\\ycolin\\projet\\test\\node_modules\\esbuild\\lib\\main.js:677:7)\n at Socket.emit (events.js:400:28)\n at addChunk (internal/streams/readable.js:293:12)\n(Use `node --trace-warnings ...` to show where the warning was created)\n(node:28520) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)\n(node:28520) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\n========================================\n\nTop Answer:\n`BootstrapVue` is now compatible with Vue 3 using @vue-compat.\nYou can read more about it here: Vue.js 3.x initial support.\nUse this sandbox for reference.\n\n========================================\n\nCode:\n```text\nimport { createApp } from 'vue'\nimport { createPinia } from 'pinia'\nimport { BootstrapVue } from 'bootstrap-vue'\n\nimport App from './App.vue'\nimport router from './router'\n\nimport './assets/main.css'\n\nconst app = createApp(App)\n\nVue.use(BootstrapVue)\n\napp.use(createPinia())\napp.use(router)\n\napp.mount('#app')\n```\n\n```text\nnpm run dev\n\n> test@0.0.0 dev C:\\Users\\ycolin\\projet\\test\n> vite\n\n\n  VITE v4.0.4  ready in 2204 ms\n\n  ➜  Local:   http://127.0.0.1:5173/\n  ➜  Network: use --host to expose\n  ➜  press h to show help\nX [ERROR] No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\n\n    node_modules/bootstrap-vue/esm/vue.js:13:7:\n      13 │ import Vue from 'vue';\n         ╵        ~~~\n\nX [ERROR] No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\n\n    node_modules/bootstrap-vue/esm/vue.js:13:7:\n      13 │ import Vue from 'vue';\n         ╵        ~~~\n\nX [ERROR] No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\n\n    node_modules/bootstrap-vue/esm/vue.js:13:7:\n      13 │ import Vue from 'vue';\n         ╵        ~~~\n\nX [ERROR] No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\n\n    node_modules/bootstrap-vue/esm/vue.js:13:7:\n      13 │ import Vue from 'vue';\n         ╵        ~~~\n\nX [ERROR] No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\n\n    node_modules/bootstrap-vue/esm/vue.js:13:7:\n      13 │ import Vue from 'vue';\n         ╵        ~~~\n\nX [ERROR] No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\n\n    node_modules/bootstrap-vue/esm/vue.js:13:7:\n      13 │ import Vue from 'vue';\n         ╵        ~~~\n\nX [ERROR] No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\n\n    node_modules/portal-vue/dist/portal-vue.esm.js:13:7:\n      13 │ import Vue from 'vue';\n         ╵        ~~~\n\n(node:28520) UnhandledPromiseRejectionWarning: Error: Build failed with 7 errors:\nnode_modules/bootstrap-vue/esm/vue.js:13:7: ERROR: No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\nnode_modules/bootstrap-vue/esm/vue.js:13:7: ERROR: No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\nnode_modules/bootstrap-vue/esm/vue.js:13:7: ERROR: No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\nnode_modules/bootstrap-vue/esm/vue.js:13:7: ERROR: No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\nnode_modules/bootstrap-vue/esm/vue.js:13:7: ERROR: No matching export in \"node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\n...\n    at failureErrorWithLog (C:\\Users\\ycolin\\projet\\test\\node_modules\\esbuild\\lib\\main.js:1604:15)\n    at C:\\Users\\ycolin\\projet\\test\\node_modules\\esbuild\\lib\\main.js:1056:28\n    at runOnEndCallbacks (C:\\Users\\ycolin\\projet\\test\\node_modules\\esbuild\\lib\\main.js:1476:61)\n    at buildResponseToResult (C:\\Users\\ycolin\\projet\\test\\node_modules\\esbuild\\lib\\main.js:1054:7)\n    at C:\\Users\\ycolin\\projet\\test\\node_modules\\esbuild\\lib\\main.js:1166:14\n    at responseCallbacks.<computed> (C:\\Users\\ycolin\\projet\\test\\node_modules\\esbuild\\lib\\main.js:701:9)\n    at handleIncomingPacket (C:\\Users\\ycolin\\projet\\test\\node_modules\\esbuild\\lib\\main.js:756:9)\n    at Socket.readFromStdout (C:\\Users\\ycolin\\projet\\test\\node_modules\\esbuild\\lib\\main.js:677:7)\n    at Socket.emit (events.js:400:28)\n    at addChunk (internal/streams/readable.js:293:12)\n(Use `node --trace-warnings ...` to show where the warning was created)\n(node:28520) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)\n(node:28520) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\n```text\nnode_modules/bootstrap-vue/esm/vue.js:13:7: ERROR: No matching export in node_modules/vue/dist/vue.runtime.esm-bundler.js\" for import \"default\"\n```\n\n```text\nnpm init vue@latest\n```\n\n```text\nnpm install\n```\n\n```text\nnpm install bootstrap bootstrap-vue\n```\n\n```text\nnpm i bootstrap\n```\n\n```text\nBootstrapVue\n```\n\n========================================\n\nComments:\n- So if i understand well, i must use bootstrap instead of bootstrapVue ?\n- Yes, unfortunately there is no wrapper for bootstrap for Vue 3 yet.\n- Thanks a lot it's working pretty fine !","metadata":{"transformedAt":"2026-08-18T18:33:46.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":249,"estimatedTokens":2528}}110{"id":"stack-70950440","source":"stackoverflow","questionId":70950440,"title":"Vite + Vue Router - Dynamic Imports","tags":["typescript","vue.js","vite"],"text":"Title: Vite + Vue Router - Dynamic Imports\nTags: typescript, vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI'm using Vite together with Vue 3 for a personal project and have `vue-router@4` for my routes. Because each of my modules uses the same set of routes, I created a helper function:\n\n```\nimport { RouteRecordRaw } from 'vue-router'\nimport pluralize from 'pluralize'\nimport Str from '@supercharge/strings'\n\nexport function createRoutes(name: string): Array {\n const plural = pluralize.plural(name)\n const path = Str(plural).trim().lower().kebab().get()\n const module = Str(plural).trim().studly().get()\n const titleSingular = Str(pluralize.singular(name)).title().get()\n const titlePlural = Str(plural).title().get()\n\n return [\n {\n path: `/${path}`,\n name: titlePlural,\n component: () => import(`@/views/${module}/index.vue`),\n },\n {\n path: `/${path}/:id`,\n name: titleSingular,\n component: () => import(`@/views/${module}/Single.vue`),\n },\n {\n path: `/${path}/new`,\n name: `New ${titleSingular}`,\n component: () => import(`@/views/${module}/New.vue`),\n },\n ]\n}\n```\n\nThe problem I'm facing however is that Vite doesn't appear to support dynamic imports.\n\n```\n3:05:29 pm [vite] warning: \nG:/Dev/world-building/client/src/router/util.ts\n21 | path: `/${path}/new`,\n22 | name: `New ${titleSingular}`,\n23 | component: () => import(`@/views/${module}/New.vue`)\n | ^\n24 | }\n25 | ];\nThe above dynamic import cannot be analyzed by vite.\nSee https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations for supported dynamic import formats. If this is intended to be left as-is, you can use the /* @vite-ignore */ comment inside the import() call to suppress this warning.\n\n Plugin: vite:import-analysis\n File: G:/Dev/world-building/client/src/router/util.ts\n```\n\nI took a look at the provided link to see the limitations however my pattern appears to match what's supported.\n\nWhy doesn't my code work? Everything appears to be fine yet I get the above warning (and an error in console when I try to visit any routes using dynamic imports).\n\nIn case it helps, the error I get in console is:\n\n```\nTypeError: Failed to resolve module specifier '@/views/Galaxies/index.vue'\n```\n\n========================================\n\nCode:\n```text\nimport { RouteRecordRaw } from 'vue-router'\nimport pluralize from 'pluralize'\nimport Str from '@supercharge/strings'\n\nexport function createRoutes(name: string): Array<RouteRecordRaw> {\n    const plural = pluralize.plural(name)\n    const path = Str(plural).trim().lower().kebab().get()\n    const module = Str(plural).trim().studly().get()\n    const titleSingular = Str(pluralize.singular(name)).title().get()\n    const titlePlural = Str(plural).title().get()\n\n    return [\n        {\n            path: `/${path}`,\n            name: titlePlural,\n            component: () => import(`@/views/${module}/index.vue`),\n        },\n        {\n            path: `/${path}/:id`,\n            name: titleSingular,\n            component: () => import(`@/views/${module}/Single.vue`),\n        },\n        {\n            path: `/${path}/new`,\n            name: `New ${titleSingular}`,\n            component: () => import(`@/views/${module}/New.vue`),\n        },\n    ]\n}\n```\n\n```text\n3:05:29 pm [vite] warning: \nG:/Dev/world-building/client/src/router/util.ts\n21 |        path: `/${path}/new`,\n22 |        name: `New ${titleSingular}`,\n23 |        component: () => import(`@/views/${module}/New.vue`)\n   |                                ^\n24 |      }\n25 |    ];\nThe above dynamic import cannot be analyzed by vite.\nSee https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations for supported dynamic import formats. If this is intended to be left as-is, you can use the /* @vite-ignore */ comment inside the import() call to suppress this warning.\n\n  Plugin: vite:import-analysis\n  File: G:/Dev/world-building/client/src/router/util.ts\n```\n\n```text\nTypeError: Failed to resolve module specifier '@/views/Galaxies/index.vue'\n```\n\n```text\nvue-router@4\n```\n\n```bash\nnpm i -D vite@alpha\n```\n\n```js\nreturn [\n  {\n    path: `/${path}`,\n    name: titlePlural,\n    component: () => import(`./views/${module}/index.vue`),\n  },                         👆\n  {\n    path: `/${path}/:id`,\n    name: titleSingular,\n    component: () => import(`./views/${module}/Single.vue`),\n  },                         👆\n  {\n    path: `/${path}/new`,\n    name: `New ${titleSingular}`,\n    component: () => import(`./views/${module}/New.vue`),\n  },                         👆\n]\n```\n\n```text\n3.0.0-alpha.7\n```\n\n```text\n./\n```\n\n```text\n../\n```\n\n```text\n@\n```\n\n```text\n@\n```\n\n```text\n<projectRoot>/src\n```\n\n```text\nrouter.js\n```\n\n```text\n<projectRoot>/src\n```\n\n```text\n@\n```\n\n```text\n./\n```\n\n========================================\n\nComments:\n- I don't understand why that's an issue. I have `@` set as an alias in my vite config to `path.resolve(__dirname, '.&#47;src')`. In a previous Vue3-only project, I had lazy-loaded routes use `@` in imports and it worked just fine. Is it because these are dynamic or is it because of vite?\n- This is a limitation of Vite's static import analysis. It's probably too costly to implement support for imports that have multiple dynamic parts (the `@` itself would technically be a variable in the path, in addition to the part you actually want to be dynamic). The docs describe the reason as: `To help static analysis, and to avoid possible foot guns`.\n- Well thank you for the help here. I thought the `@` might have been the issue however I was hoping there'd be a way to keep it.\n- @Spedwards Vite 3.x now supports path aliases in dynamic imports. See updated answer.","metadata":{"transformedAt":"2026-08-18T18:33:46.400Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":197,"estimatedTokens":1410}}111{"id":"stack-71162040","source":"stackoverflow","questionId":71162040,"title":"How to insert git info in environment variables using Vite?","tags":["javascript","git","version-control","vite"],"text":"Title: How to insert git info in environment variables using Vite?\nTags: javascript, git, version-control, vite\nSource: Stack Overflow\n\nQuestion:\nHow to get information from git about current branch, commit date and other when using Vite bundler?\n\n========================================\n\nCode:\n```text\nexport default ({ mode }: ConfigEnv) => {\n   const dev = mode === 'development';\n\n   const commitDate = execSync('git log -1 --format=%cI').toString().trimEnd();\n   const branchName = execSync('git rev-parse --abbrev-ref HEAD').toString().trimEnd();\n   const commitHash = execSync('git rev-parse HEAD').toString().trimEnd();\n   const lastCommitMessage = execSync('git show -s --format=%s').toString().trimEnd();\n\n   process.env.VITE_GIT_COMMIT_DATE = commitDate;\n   process.env.VITE_GIT_BRANCH_NAME = branchName;\n   process.env.VITE_GIT_COMMIT_HASH = commitHash;\n   process.env.VITE_GIT_LAST_COMMIT_MESSAGE = lastCommitMessage;\n...\n```\n\n```text\nfunction BuildInfo() {\n   const date = new Date(import.meta.env.VITE_GIT_COMMIT_DATE);\n   return (\n      <div>\n         <span>{date.toLocaleString()}</span>\n         <span>{import.meta.env.VITE_GIT_LAST_COMMIT_MESSAGE}</span>\n         <span>{import.meta.env.VITE_GIT_BRANCH_NAME}/{import.meta.env.VITE_GIT_COMMIT_HASH}</span>\n      </div>\n   );\n}\n```\n\n```text\nVITE_\n```\n\n```text\nhttps://www.npmjs.com/package/git-rev-sync\n```\n\n========================================\n\nComments:\n- does this work for `vite build`? thanks,","metadata":{"transformedAt":"2026-08-18T18:33:46.400Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":51,"estimatedTokens":368}}112{"id":"stack-74898679","source":"stackoverflow","questionId":74898679,"title":"Vite CommonJS Resolver throws Unexpected Token Error when importing ESM","tags":["create-react-app","es6-modules","vite","commonjs"],"text":"Title: Vite CommonJS Resolver throws Unexpected Token Error when importing ESM\nTags: create-react-app, es6-modules, vite, commonjs\nSource: Stack Overflow\n\nQuestion:\nI have a create-react-app project I'm migrating to Vite. That project uses \"styled-components\" like this:\n\n```\nimport styled from 'styled-components';\n\nconst someDiv = styled.div`...`;\n```\n\nNow the issue comes up when running `vite build`:\n\n```\nvite v4.0.2 building for production...\n✓ 51 modules transformed.\n[commonjs--resolver] Unexpected token (1:167492) in /project/node_modules/styled-components/dist/styled-components.browser.esm.js\nfile: /project/node_modules/styled-components/dist/styled-components.browser.esm.js:1:167492\n1: import{typeOf as e,isElement as t,isValidElementType as n}from\"react-is\";import r,{useState as o,useContext as i,useMemo as s,useEffect as a,useRef as c,createElement as u,useDebugValue as l,useLayoutEffect as d}from\"react\";import h from\"shallowequal\";import p from\"@emotion/stylis\";import f from\"@emotion/unitless\";import m from\"@emotion/is-prop-valid\";import y from\"hoist-non-react-statics\";function // ... rest of file\n```\n\nSo it seems like it is trying to import `styled-components.browser.esm.js` using the commonjs--resolver, but there are `import` statements at the top of that file and it seems to get confused.\n\nAny ideas why the \"Unexpected token\" error might happen and how this can be resolved? Shouldn't it import it as ESM?\n\nUPDATE 07/02/2023:\nOn a Github discussion it was noticed by someone else, that everything works when there is no `define` block in the `vite.config.ts`: https://github.com/vitejs/vite/discussions/11495.\nHowever, this is a questionable solution if you actually need to define something there.\n\n========================================\n\nTop Answer:\nFrom Vite documentation: https://vitejs.dev/guide/env-and-mode.html\n\nFor JavaScript strings, you can break the string up with a Unicode zero-width space, e.g. 'import.meta\\u200b.env.MODE'.\n\nFor Vue templates or other HTML that gets compiled into JavaScript strings, you can use the tag, e.g. import.meta.env.MODE\n\nSo my `define` became:\n\n```\ndefine: {\n 'process.env': {}\n```\n\n========================================\n\nCode:\n```js\nimport styled from 'styled-components';\n\nconst someDiv = styled.div`...`;\n```\n\n```text\nvite v4.0.2 building for production...\n✓ 51 modules transformed.\n[commonjs--resolver] Unexpected token (1:167492) in /project/node_modules/styled-components/dist/styled-components.browser.esm.js\nfile: /project/node_modules/styled-components/dist/styled-components.browser.esm.js:1:167492\n1: import{typeOf as e,isElement as t,isValidElementType as n}from\"react-is\";import r,{useState as o,useContext as i,useMemo as s,useEffect as a,useRef as c,createElement as u,useDebugValue as l,useLayoutEffect as d}from\"react\";import h from\"shallowequal\";import p from\"@emotion/stylis\";import f from\"@emotion/unitless\";import m from\"@emotion/is-prop-valid\";import y from\"hoist-non-react-statics\";function // ... rest of file\n```\n\n```text\nvite build\n```\n\n```text\nstyled-components.browser.esm.js\n```\n\n```text\nimport\n```\n\n```text\ndefine\n```\n\n```text\nvite.config.ts\n```\n\n```text\ndefine\n```\n\n```text\ndefine\n```\n\n```text\ndefine: {\n    'process.<wbr>env': {}\n```\n\n```text\ndefine\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":100,"estimatedTokens":817}}113{"id":"stack-72009814","source":"stackoverflow","questionId":72009814,"title":"Vue + Vite + Rollup: Dynamic import not working on production build","tags":["vue.js","es6-modules","rollup","rollupjs","vite"],"text":"Title: Vue + Vite + Rollup: Dynamic import not working on production build\nTags: vue.js, es6-modules, rollup, rollupjs, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use Vite with ***dynamic-import*** Vue SFCs, but it does not work on production build.\n\nThere is stackblitz example:\n\nhttps://stackblitz.com/edit/vitejs-vite-ant1g2?file=src/main.ts\n\nTest command and localhost:3000 shows good.\n\n```\nvite\n```\n\nHowever preview and localhost:4173 shows blank.\n\n```\nvite build && vite preview\n```\n\nWhat is wrong? Do you have any solutions?\n\n========================================\n\nTop Answer:\nI was recently doing a PoC and was surprised to know that `dynamic` imports feature works fine in `dev` mode but fails in production build without a special configuration. Reason behind this (probably) is that `vite` uses `esbuild` as bundler for `dev` mode while using `rollup` as bundler for `production` build.\n\nDue to this discrepancy in the behavior between two modes, I am making sure that I always test a new concept in both `dev` and `production` modes to make sure it works in `production` build too otherwise you will end up developing a feature in `dev` mode only to realize at a later stage that it is not working in `production` mode.\n\nYou will need to list all the dynamic imports under `rollupOptions` of `vite.configs.ts` file in order to make it work in `production` mode -\n\n```\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n build: {\n rollupOptions: {\n external: [\n \"/path/to/external/module.es.js\"\n ]\n }\n }\n})\n```\n\n========================================\n\nCode:\n```text\nvite\n```\n\n```text\nvite build && vite preview\n```\n\n```text\nimport { createApp, defineAsyncComponent } from 'vue';\n\nconsole.log('start app');\ncreateApp(defineAsyncComponent(() => import('./App.vue'))).mount('#app');\n```\n\n```text\ndefineAsyncComponent\n```\n\n```text\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n    build: {\n        rollupOptions: {\n            external: [\n                \"/path/to/external/module.es.js\"\n            ]\n        }\n    }\n})\n```\n\n```text\ndynamic\n```\n\n```text\ndev\n```\n\n```text\nvite\n```\n\n```text\nesbuild\n```\n\n```text\ndev\n```\n\n```text\nrollup\n```\n\n```text\nproduction\n```\n\n```text\ndev\n```\n\n```text\nproduction\n```\n\n```text\nproduction\n```\n\n```text\ndev\n```\n\n```text\nproduction\n```\n\n```text\nrollupOptions\n```\n\n```text\nvite.configs.ts\n```\n\n```text\nproduction\n```\n\n========================================\n\nComments:\n- JS apps usually do not just \"show blank\" without any error in console. Check the dev tools....\n- I can confirm this behaviour and there is no error message on the console. I guess it is about the path `.&#47;App.vue`. It is not resolved as an asset, which is needed for production. Did you check out `cli.vuejs.org/guide/&hellip;?\n- I forgot to mention that there are no clues in the console. I am not very familiar with Vite and Rollup so I don't know how to apply @Nechoj 's link.\n- Why do you want dynamic loading of `App.vue` and not standard import?\n- More info: I added console.log and found that create cycle of App.vue does't run.\n- @Nechoj Guys on stackoverflow say so all the time. I am asking why it fails in such a simple use case. And in my product, almost all of dynamic import of SFCs fails--that is, if dynamic import really doesn't work, then I need to give up using dynamic import in the whole product.\n- I do not recommend using dynamic component import. See also docs: vuejs.org/guide/essentials/application.html#the-root-compone&zwnj;&#8203;nt\n- So there is no way to make the rollup understand dynamic imports?\n- This does not seem to work with dynamic imports\n- This would not work If we don't know what we exactly have to import (for e.g. App.vue) What If the App.vue part is dynamic?\n- @ShakilAlam Exactly. I am facing the same issue. Please check my question: stackoverflow.com/questions/75988909/vue-3-dynamic-import-is&zwnj;&#8203;sue/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:46.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":158,"estimatedTokens":984}}114{"id":"stack-68998731","source":"stackoverflow","questionId":68998731,"title":"Vue Transition with Tailwind","tags":["html","vuejs3","tailwind-css","transition","vite"],"text":"Title: Vue Transition with Tailwind\nTags: html, vuejs3, tailwind-css, transition, vite\nSource: Stack Overflow\n\nQuestion:\nWhy do Tailwind do not work directly on element?\n\n### This does not work:\n\n```\n\n \n Test\n \n\n```\n\n### But this:\n\n```\n\n \n Test\n \n\n.fade-enter-active,\n.fade-leave-active {\n @apply transition-opacity duration-300 ease-out;\n}\n.fade-enter,\n.fade-leave-active {\n @apply opacity-0;\n}\n\n```\n\nI need to get it work like in \"But this\", because I use Nuxt with vite and I do not get scss to work, so @apply is not an option.\n\nTHanks.\n\n========================================\n\nTop Answer:\nHere are my `tailwind transition live templates` in `phpstorm`. Replace the `$SELECTION$` parameter with what you want to transition or use it as is:\n\n### FadeIn\n\n```\n\n $SELECTION$\n\n```\n\n### FadeOut\n\n```\n\n $SELECTION$\n\n```\n\n### Fade (if you need both)\n\n```\n\n $SELECTION$\n\n```\n\n### SlideIn\n\n```\n\n $SELECTION$\n\n```\n\n### SlideOut\n\n```\n\n $SELECTION$\n\n```\n\n### Slide\n\n```\n\n $SELECTION$\n\n```\n\nHope it helps.\n\n========================================\n\nCode:\n```text\n<template>\n      <transition\n        enter-class=\"opacity-0\"\n        enter-active-class=\"transition-opacity duration-300 ease-out\"\n        leave-class=\"opacity-0\"\n        leave-active-class=\"transition-opacity duration-300 ease-out\"\n      >\n        Test\n      </transition>\n</template>\n```\n\n```text\n<template>\n    <transition name=\"fade\">\n        Test\n    </transition>\n</template>\n<style>\n.fade-enter-active,\n.fade-leave-active {\n  @apply transition-opacity duration-300 ease-out;\n}\n.fade-enter,\n.fade-leave-active {\n  @apply opacity-0;\n}\n</style>\n```\n\n```text\n<transition\n    enter-active-class=\"duration-300 ease-out\"\n    enter-from-class=\"transform opacity-0\"\n    enter-to-class=\"opacity-100\"\n    leave-active-class=\"duration-200 ease-in\"\n    leave-from-class=\"opacity-100\"\n    leave-to-class=\"transform opacity-0\"\n  >\n        Test\n</transition>\n```\n\n```text\n<transition\n  enter-from-class=\"opacity-0\"\n  enter-active-class=\"transition duration-300\">\n  $SELECTION$\n</transition>\n```\n\n```text\n<transition\n  leave-to-class=\"opacity-0\"\n  leave-active-class=\"transition duration-300\">\n  $SELECTION$\n</transition>\n```\n\n```text\n<transition\n  enter-from-class=\"opacity-0\"\n  leave-to-class=\"opacity-0\"\n  enter-active-class=\"transition duration-300\"\n  leave-active-class=\"transition duration-300\">\n  $SELECTION$\n</transition>\n```\n\n```text\n<transition\n  enter-from-class=\"translate-x-[150%] opacity-0\"\n  enter-active-class=\"transition duration-300\">\n  $SELECTION$\n</transition>\n```\n\n```text\n<transition\n  leave-to-class=\"translate-x-[150%] opacity-0\"\n  leave-active-class=\"transition duration-300\">\n  $SELECTION$\n</transition>\n```\n\n```text\n<transition\n  enter-from-class=\"translate-x-[150%] opacity-0\"\n  leave-to-class=\"translate-x-[150%] opacity-0\"\n  enter-active-class=\"transition duration-300\"\n  leave-active-class=\"transition duration-300\">\n  $SELECTION$\n</transition>\n```\n\n```text\ntailwind transition live templates\n```\n\n```text\nphpstorm\n```\n\n```text\n$SELECTION$\n```\n\n========================================\n\nComments:\n- This is great! However we cant do with tailwind is doing animations with multiple different timings and steps, right?","metadata":{"transformedAt":"2026-08-18T18:33:46.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":210,"estimatedTokens":798}}115{"id":"stack-75531401","source":"stackoverflow","questionId":75531401,"title":"How to use vite for production build","tags":["javascript","reactjs","npm","yarnpkg","vite"],"text":"Title: How to use vite for production build\nTags: javascript, reactjs, npm, yarnpkg, vite\nSource: Stack Overflow\n\nQuestion:\nI'm new to Vite and trying to use this for production.\nThe question is how can i create scripts (used for docker) to run this on prod.\n\nThe documentation says the preview should not be used for production.\n\nIn that case, what i do is run `yarn build (tsc && vite build)` but what to run after ?\n\nI'm looking for equivalent of `vite preview` but for production.\n\nSample docker:\n\n```\nFROM node:18 as build\n\nWORKDIR /src/build\n\nCOPY package.json .\n\nCOPY . .\n\nRUN yarn install \\\n&& yarn build\n\nEXPOSE 3001\n\nCMD ['SOME COMMAND INSTEAD OF PREVIEW']\n```\n\nThanks\n\n========================================\n\nTop Answer:\nIf you want to create an image that only contains the final build artifacts and not all the bloated dependencies, you can use a two-stage Docker build. The Dockerfile below builds the artifacts using a Node.js image, then serves the generated content with a busybox httpd server.\n\n```\nFROM node:20-alpine AS build-stage\nWORKDIR /app\nCOPY package.json .\nRUN npm install\nCOPY . .\nRUN npm run build\n\nFROM busybox:1.35\nRUN adduser -D static\nUSER static\nWORKDIR /home/static\nCOPY --from=build-stage /app/dist .\nCMD [\"busybox\", \"httpd\", \"-f\", \"-v\", \"-p\", \"8080\"]\n```\n\nHope that helps!\n\n========================================\n\nCode:\n```text\nFROM node:18 as build\n\nWORKDIR /src/build\n\nCOPY package.json .\n\nCOPY . .\n\nRUN yarn install \\\n&& yarn build\n\nEXPOSE 3001\n\nCMD ['SOME COMMAND INSTEAD OF PREVIEW']\n```\n\n```text\nyarn build (tsc && vite build)\n```\n\n```text\nvite preview\n```\n\n```text\nFROM node:20-alpine AS build-stage\nWORKDIR /app\nCOPY package.json .\nRUN npm install\nCOPY . .\nRUN npm run build\n\nFROM busybox:1.35\nRUN adduser -D static\nUSER static\nWORKDIR /home/static\nCOPY --from=build-stage /app/dist .\nCMD [\"busybox\", \"httpd\", \"-f\", \"-v\", \"-p\", \"8080\"]\n```\n\n========================================\n\nComments:\n- So just use `vite build` and point the server to use the build files right ?\n- Yes, that's right. Though I would suggest using one of these methods (vitejs.dev/guide/static-deploy.html) to deploy than using docker!\n- None of the methods in the docs deploy to ECS on AWS\n- None of the methods in the docs suggest a way to deploy on Google Cloud Run either...\n- Thank you Derek! Here's an alternative with ubuntu/nginx instead of busybox: github.com/mattburrell/vite-react-docker/blob/main/Dockerfil&zwnj;&#8203;e","metadata":{"transformedAt":"2026-08-18T18:33:46.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":110,"estimatedTokens":614}}116{"id":"stack-77138313","source":"stackoverflow","questionId":77138313,"title":"Why wont my images load in my React Vite project?","tags":["javascript","reactjs","vite"],"text":"Title: Why wont my images load in my React Vite project?\nTags: javascript, reactjs, vite\nSource: Stack Overflow\n\nQuestion:\n**Public Folder>>**\nleaves.jpg\n\n**App.jsx:**\n\n```\nfunction App() {\nreturn (\n\n)\n}\n```\n\nThe image is showing up on my image-preview extension which usually indicated the path is correct, I'm not sure what I'm doing wrong. It doesn't return an error when I try to use this method. I also tried importing the image like: `import leaves from './public/leaves.jpg'` and plugging it in like: ``, but it was throwing an error that the file couldn't be found.\n\nAny help would be appreciated, thank you.\n\n========================================\n\nCode:\n```text\nfunction App() {\nreturn (\n<img src=\"./public/leaves.jpg\" alt \"img\" />\n)\n}\n```\n\n```text\nimport leaves from './public/leaves.jpg'\n```\n\n```text\n<img src={leaves} alt \"img\" />\n```\n\n```html\n<img src=\"/leaves.jpg\" alt \"img\" />\n```\n\n```text\npublic\n```\n\n```text\n/\n```\n\n========================================\n\nComments:\n- You shouldn't need to reference './' a domain is parent, public is parent to that so /public is all you need.","metadata":{"transformedAt":"2026-08-18T18:33:46.401Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":57,"estimatedTokens":275}}117{"id":"stack-78204738","source":"stackoverflow","questionId":78204738,"title":"MSW - Error: No known conditions for \"./browser\" specifier in \"msw\" package","tags":["vite","vitest","test-coverage","msw"],"text":"Title: MSW - Error: No known conditions for \"./browser\" specifier in \"msw\" package\nTags: vite, vitest, test-coverage, msw\nSource: Stack Overflow\n\nQuestion:\nAfter doing successful MSW (Mock Service worker) setup for browser. Everything is working fine.\n\nHere is my setup files ->\n\n```\n//handlers.ts\nimport { http, HttpResponse } from 'msw';\n\nconst handlers = [\n http.post('url_being_mocked', async ({ request }) => {\n ...\n }),\n];\nexport default handlers;\n```\n\n```\n//browser.ts\nimport { setupWorker } from 'msw/browser';\nimport handlers from './handlers';\n\nconst worker = setupWorker(...handlers);\nexport default worker;\n```\n\n```\n// main.tsx\nimport React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { LicenseInfo } from '@mui/x-license-pro';\nimport { CssBaseline } from '@mui/material';\nimport App from './App';\nimport AppProviders from './providers/AppProviders';\n\nLicenseInfo.setLicenseKey(import.meta.env.VITE_PUBLIC_MUI_LICENSE_KEY);\n\nasync function enableMocking() {\n if (import.meta.env.DEV) {\n const worker = await import('./mocks/browser');\n return worker.default.start({ onUnhandledRequest: 'bypass' });\n }\n return Promise.resolve();\n}\n\nenableMocking().then(() => {\n ReactDOM.createRoot(document.getElementById('root')!).render(\n \n \n \n \n \n ,\n );\n});\n```\n\nPackages being used ->\n\n```\n//package.json\n\"devDependencies\": {\n \"@vitest/coverage-istanbul\": \"1.2.2\", \n \"vitest\": \"1.3.0\"\n}\n```\n\nAt this point, Mocking is working fine in the browser.\nBut when I run\n\n**`vitest run --coverage`**\n\nI am getting the following error\n\n```\n⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Unhandled Error ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯\nError: No known conditions for \"./browser\" specifier in \"msw\" package\n ❯ e node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:47384:25\n ❯ n node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:47384:646\n ❯ o node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:47384:1297\n ❯ resolveExportsOrImports node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:48061:20\n ❯ resolveDeepImport node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:48080:31\n ❯ tryNodeResolve node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:47805:20\n ❯ Context.resolveId node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:47568:28\n ❯ Object.resolveId node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:50762:64\n ❯ process.processTicksAndRejections node:internal/process/task_queues:95:5\n ❯ TransformContext.resolve node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:50453:23\n ❯ normalizeUrl node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:65586:34\n ❯ async file:/Users/ankurmarwaha/IdeaProjects/order-entry-ui/node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:65749:47\n ❯ TransformContext.transform node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:65670:13\n ❯ Object.transform node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:50838:30\n ❯ loadAndTransform node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:53611:29\n ❯ ViteNodeServer._transformRequest node_modules/vite-node/dist/server.mjs:413:16\n ❯ IstanbulCoverageProvider.getCoverageMapForUncoveredFiles node_modules/@vitest/coverage-istanbul/dist/provider.js:281:7\n ❯ IstanbulCoverageProvider.reportCoverage node_modules/@vitest/coverage-istanbul/dist/provider.js:228:33\n ❯ Vitest.reportCoverage node_modules/vitest/dist/vendor/cli-api.RIYLcWhB.js:6537:7\n ❯ async file:/Users/ankurmarwaha/IdeaProjects/order-entry-ui/node_modules/vitest/dist/vendor/cli-api.RIYLcWhB.js:6328:7\n ❯ Vitest.runFiles node_modules/vitest/dist/vendor/cli-api.RIYLcWhB.js:6332:12\n ❯ Vitest.start node_modules/vitest/dist/vendor/cli-api.RIYLcWhB.js:6223:7\n ❯ startVitest node_modules/vitest/dist/vendor/cli-api.RIYLcWhB.js:13380:5\n ❯ start node_modules/vitest/dist/cli.js:1386:17\n ❯ CAC.run node_modules/vitest/dist/cli.js:1367:3\n\n⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯\nSerialized Error: { plugin: 'vite:import-analysis', id: '/Users/ankurmarwaha/IdeaProjects/order-entry-ui/src/mocks/browser.ts', pluginCode: 'function cov_1w46yme1q9() {\\n var path = \"/Users/ankurmarwaha/IdeaProjects/order-entry-ui/src/mocks/browser.ts\";\\n var hash = \"5c0d2e9c5d02c56205857e5a14c090467c6fff95\";\\n var global = globalThis;\\n var gcv = \"__VITEST_COVERAGE__\";\\n var coverageData = {\\n path: \"/Users/ankurmarwaha/IdeaProjects/order-entry-ui/src/mocks/browser.ts\",\\n statementMap: {\\n \"0\": {\\n start: {\\n line: 3,\\n column: 15\\n },\\n end: {\\n line: 3,\\n column: 39\\n }\\n }\\n },\\n fnMap: {},\\n branchMap: {},\\n s: {\\n \"0\": 0\\n },\\n f: {},\\n b: {},\\n inputSourceMap: {\\n version: 3,\\n sources: [\"/Users/ankurmarwaha/IdeaProjects/order-entry-ui/src/mocks/browser.ts\"],\\n sourcesContent: [\"import { setupWorker } from \\'msw/browser\\';\\nimport handlers from \\'./handlers\\';\\n\\nconst worker = setupWorker(...handlers);\\nexport default worker;\\n\"],\\n mappings: \"AAAA,SAAS,mBAAmB;AAC5B,OAAO,cAAc;AAErB,MAAM,SAAS,YAAY,GAAG,QAAQ;AACtC,eAAe;\",\\n names: []\\n },\\n _coverageSchema: \"1a1c01bbd47fc00a2c39e90264f33305004495a9\",\\n hash: \"5c0d2e9c5d02c56205857e5a14c090467c6fff95\"\\n };\\n var coverage = global[gcv] || (global[gcv] = {});\\n if (!coverage[path] || coverage[path].hash !== hash) {\\n coverage[path] = coverageData;\\n }\\n var actualCoverage = coverage[path];\\n {\\n // @ts-ignore\\n cov_1w46yme1q9 = function () {\\n return actualCoverage;\\n };\\n }\\n return actualCoverage;\\n}\\ncov_1w46yme1q9();\\nimport { setupWorker } from \"msw/browser\";\\nimport handlers from \"./handlers\";\\nconst worker = (cov_1w46yme1q9().s[0]++, setupWorker(...handlers));\\nexport default worker;' }\n```\n\n========================================\n\nTop Answer:\nFor me there was a combination of having some of the files outside of the './src' folder and some, including the handlers and the 'setupServer' call inside the src folder. Moved everything in './src/mocks'. I also added the rules to the exclude config.\n\n========================================\n\nCode:\n```text\n//handlers.ts\nimport { http, HttpResponse } from 'msw';\n\nconst handlers = [\n  http.post('url_being_mocked', async ({ request }) => {\n    ...\n  }),\n];\nexport default handlers;\n```\n\n```text\n//browser.ts\nimport { setupWorker } from 'msw/browser';\nimport handlers from './handlers';\n\nconst worker = setupWorker(...handlers);\nexport default worker;\n```\n\n```text\n// main.tsx\nimport React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { LicenseInfo } from '@mui/x-license-pro';\nimport { CssBaseline } from '@mui/material';\nimport App from './App';\nimport AppProviders from './providers/AppProviders';\n\nLicenseInfo.setLicenseKey(import.meta.env.VITE_PUBLIC_MUI_LICENSE_KEY);\n\nasync function enableMocking() {\n  if (import.meta.env.DEV) {\n    const worker = await import('./mocks/browser');\n    return worker.default.start({ onUnhandledRequest: 'bypass' });\n  }\n  return Promise.resolve();\n}\n\nenableMocking().then(() => {\n  ReactDOM.createRoot(document.getElementById('root')!).render(\n    <React.StrictMode>\n      <AppProviders>\n        <CssBaseline />\n        <App />\n      </AppProviders>\n    </React.StrictMode>,\n  );\n});\n```\n\n```text\n//package.json\n\"devDependencies\": {\n  \"@vitest/coverage-istanbul\": \"1.2.2\",    \n  \"vitest\": \"1.3.0\"\n}\n```\n\n```text\n⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Unhandled Error ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯\nError: No known conditions for \"./browser\" specifier in \"msw\" package\n ❯ e node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:47384:25\n ❯ n node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:47384:646\n ❯ o node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:47384:1297\n ❯ resolveExportsOrImports node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:48061:20\n ❯ resolveDeepImport node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:48080:31\n ❯ tryNodeResolve node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:47805:20\n ❯ Context.resolveId node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:47568:28\n ❯ Object.resolveId node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:50762:64\n ❯ process.processTicksAndRejections node:internal/process/task_queues:95:5\n ❯ TransformContext.resolve node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:50453:23\n ❯ normalizeUrl node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:65586:34\n ❯ async file:/Users/ankurmarwaha/IdeaProjects/order-entry-ui/node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:65749:47\n ❯ TransformContext.transform node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:65670:13\n ❯ Object.transform node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:50838:30\n ❯ loadAndTransform node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js:53611:29\n ❯ ViteNodeServer._transformRequest node_modules/vite-node/dist/server.mjs:413:16\n ❯ IstanbulCoverageProvider.getCoverageMapForUncoveredFiles node_modules/@vitest/coverage-istanbul/dist/provider.js:281:7\n ❯ IstanbulCoverageProvider.reportCoverage node_modules/@vitest/coverage-istanbul/dist/provider.js:228:33\n ❯ Vitest.reportCoverage node_modules/vitest/dist/vendor/cli-api.RIYLcWhB.js:6537:7\n ❯ async file:/Users/ankurmarwaha/IdeaProjects/order-entry-ui/node_modules/vitest/dist/vendor/cli-api.RIYLcWhB.js:6328:7\n ❯ Vitest.runFiles node_modules/vitest/dist/vendor/cli-api.RIYLcWhB.js:6332:12\n ❯ Vitest.start node_modules/vitest/dist/vendor/cli-api.RIYLcWhB.js:6223:7\n ❯ startVitest node_modules/vitest/dist/vendor/cli-api.RIYLcWhB.js:13380:5\n ❯ start node_modules/vitest/dist/cli.js:1386:17\n ❯ CAC.run node_modules/vitest/dist/cli.js:1367:3\n\n⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯\nSerialized Error: { plugin: 'vite:import-analysis', id: '/Users/ankurmarwaha/IdeaProjects/order-entry-ui/src/mocks/browser.ts', pluginCode: 'function cov_1w46yme1q9() {\\n  var path = \"/Users/ankurmarwaha/IdeaProjects/order-entry-ui/src/mocks/browser.ts\";\\n  var hash = \"5c0d2e9c5d02c56205857e5a14c090467c6fff95\";\\n  var global = globalThis;\\n  var gcv = \"__VITEST_COVERAGE__\";\\n  var coverageData = {\\n    path: \"/Users/ankurmarwaha/IdeaProjects/order-entry-ui/src/mocks/browser.ts\",\\n    statementMap: {\\n      \"0\": {\\n        start: {\\n          line: 3,\\n          column: 15\\n        },\\n        end: {\\n          line: 3,\\n          column: 39\\n        }\\n      }\\n    },\\n    fnMap: {},\\n    branchMap: {},\\n    s: {\\n      \"0\": 0\\n    },\\n    f: {},\\n    b: {},\\n    inputSourceMap: {\\n      version: 3,\\n      sources: [\"/Users/ankurmarwaha/IdeaProjects/order-entry-ui/src/mocks/browser.ts\"],\\n      sourcesContent: [\"import { setupWorker } from \\'msw/browser\\';\\nimport handlers from \\'./handlers\\';\\n\\nconst worker = setupWorker(...handlers);\\nexport default worker;\\n\"],\\n      mappings: \"AAAA,SAAS,mBAAmB;AAC5B,OAAO,cAAc;AAErB,MAAM,SAAS,YAAY,GAAG,QAAQ;AACtC,eAAe;\",\\n      names: []\\n    },\\n    _coverageSchema: \"1a1c01bbd47fc00a2c39e90264f33305004495a9\",\\n    hash: \"5c0d2e9c5d02c56205857e5a14c090467c6fff95\"\\n  };\\n  var coverage = global[gcv] || (global[gcv] = {});\\n  if (!coverage[path] || coverage[path].hash !== hash) {\\n    coverage[path] = coverageData;\\n  }\\n  var actualCoverage = coverage[path];\\n  {\\n    // @ts-ignore\\n    cov_1w46yme1q9 = function () {\\n      return actualCoverage;\\n    };\\n  }\\n  return actualCoverage;\\n}\\ncov_1w46yme1q9();\\nimport { setupWorker } from \"msw/browser\";\\nimport handlers from \"./handlers\";\\nconst worker = (cov_1w46yme1q9().s[0]++, setupWorker(...handlers));\\nexport default worker;' }\n```\n\n```text\nvitest run --coverage\n```\n\n```text\n// vitest.config.ts\nexport default defineConfig({\n  test: {\n    ...\n    coverage: {\n      ...\n      exclude: [\n        ...,\n        '**/browser.ts',      // Added these to be excluded from coverage\n        '**/handler.ts',\n      ],\n      thresholds: {\n        ...\n      },\n    },\n  },\n});\n```\n\n========================================\n\nComments:\n- Does not work, still getting the same error\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:46.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":241,"estimatedTokens":3094}}118{"id":"stack-71923917","source":"stackoverflow","questionId":71923917,"title":"Change Default Path of .env files in ReactJs ViteJs Project","tags":["reactjs","environment","vite"],"text":"Title: Change Default Path of .env files in ReactJs ViteJs Project\nTags: reactjs, environment, vite\nSource: Stack Overflow\n\nQuestion:\nI want to setup Multiple env file in ReactJs / ViteJs project, following the vite enDir documentation it should be something like that :\n\n```\nroot\n |\n .env.dev\n ...\n .env.prod\n```\n\nbut since it can become so messy when you have a lot of env files on the root, what i can do change vite config in order to get env variables from the **env folder**\n\n```\nroot\n |\n env\n |\n .env.dev\n ...\n .env.prod\n```\n\n========================================\n\nTop Answer:\n\"vite\": \"4.3.4\" just put the dir like :\n\n```\nimport { defineConfig } from \"vite\";\n\nexport default defineConfig({\n envDir: \"../\"\n});\n```\n\n========================================\n\nCode:\n```text\nroot\n   |\n   .env.dev\n   ...\n   .env.prod\n```\n\n```text\nroot\n   |\n   env\n      |\n      .env.dev\n      ...\n      .env.prod\n```\n\n```text\nimport { defineConfig } from \"vite\";\n\nexport default defineConfig({\n  envDir: \"./env\"\n});\n```\n\n```text\nenvDir\n```\n\n```text\ndefineConfig\n```\n\n```text\nimport { defineConfig } from \"vite\";\n\nexport default defineConfig({\n  envDir: \"../\"\n});\n```\n\n========================================\n\nComments:\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- vitejs.dev/config/#using-environment-variables-in-config","metadata":{"transformedAt":"2026-08-18T18:33:46.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":90,"estimatedTokens":387}}119{"id":"stack-68595151","source":"stackoverflow","questionId":68595151,"title":"Unable to Dockerize Vite React-Typescript Project","tags":["node.js","reactjs","typescript","docker","vite"],"text":"Title: Unable to Dockerize Vite React-Typescript Project\nTags: node.js, reactjs, typescript, docker, vite\nSource: Stack Overflow\n\nQuestion:\nI am trying to dockerize a Vite React-Typescript boilerplate setup, but I unable to connect to the container.\n\nInstalled vite-react-typescript boilerplate:\n\n`npm init vite@latest vite-docker-demo -- --template react-ts`\n\n**Dockerfile**\n\n```\n# Declare the base image\nFROM node:lts-alpine3.14\n# Build step\n# 1. copy package.json and package-lock.json to /app dir\nRUN mkdir /app\nCOPY package*.json /app\n# 2. Change working directory to newly created app dir\nWORKDIR /app\n# 3 . Install dependencies\nRUN npm ci\n# 4. Copy the source code to /app dir\nCOPY . .\n# 5. Expose port 3000 on the container\nEXPOSE 3000\n# 6. Run the app\nCMD [\"npm\", \"run\", \"dev\"]\n```\n\nCommand to run docker container in detached mode and open local dev port 3000 on host:\n`docker run -d -p 3000:3000 vite`\n\nThe vite instance seems to be running just fine within the container (docker logs output):\n\n```\n> vite-docker@0.0.0 dev /app\n> vite\n\nPre-bundling dependencies:\n react\n react-dom\n(this will be run only when your dependencies or config have changed)\n\n vite v2.4.4 dev server running at:\n\n > Local: http://localhost:3000/\n > Network: use `--host` to expose\n\n ready in 244ms.\n```\n\nHowever, when I navigate to `http://localhost:3000/` within Chrome. I see an error indicating `The connection was reset`.\n\nAny help resolving this issue would be greatly appreciated!\n\n========================================\n\nTop Answer:\nin package.json use script\n\n```\n\"dev\": \"vite --host\"\n```\n\nexample:\n\n```\n\"scripts\": {\n \"dev\": \"vite --host\",\n \"build\": \"tsc && vite build\",\n \"serve\": \"vite preview\"\n },\n```\n\nor run with `vite --host`\n\n========================================\n\nCode:\n```text\n# Declare the base image\nFROM node:lts-alpine3.14\n# Build step\n# 1. copy package.json and package-lock.json to /app dir\nRUN mkdir /app\nCOPY package*.json /app\n# 2. Change working directory to newly created app dir\nWORKDIR /app\n# 3 . Install dependencies\nRUN npm ci\n# 4. Copy the source code to /app dir\nCOPY . .\n# 5. Expose port 3000 on the container\nEXPOSE 3000\n# 6. Run the app\nCMD [\"npm\", \"run\", \"dev\"]\n```\n\n```text\n> vite-docker@0.0.0 dev /app\n> vite\n\nPre-bundling dependencies:\n  react\n  react-dom\n(this will be run only when your dependencies or config have changed)\n\n  vite v2.4.4 dev server running at:\n\n  > Local: http://localhost:3000/\n  > Network: use `--host` to expose\n\n  ready in 244ms.\n```\n\n```text\nnpm init vite@latest vite-docker-demo -- --template react-ts\n```\n\n```text\ndocker run -d -p 3000:3000 vite\n```\n\n```text\nhttp://localhost:3000/\n```\n\n```text\nThe connection was reset\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport reactRefresh from '@vitejs/plugin-react-refresh'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  server: {\n    host: '0.0.0.0',\n    port: 3000,\n  },\n  plugins: [reactRefresh()],\n})\n```\n\n```text\nhost\n```\n\n```text\nlocalhost\n```\n\n```text\nvite.config.ts\n```\n\n```text\n\"dev\": \"vite --host\"\n```\n\n```text\n\"scripts\": {\n    \"dev\": \"vite --host\",\n    \"build\": \"tsc && vite build\",\n    \"serve\": \"vite preview\"\n  },\n```\n\n```text\nvite --host\n```\n\n```text\nexport default (conf: any) => {\n  return defineConfig({\n    server: {\n      host: \"0.0.0.0\",\n      hmr: {\n        clientPort: ENV_VARIABLES.OUTER_PORT_FRONTEND,\n      },\n      port: ENV_VARIABLES.INNER_PORT_FRONTEND_DEV, \n      watch: {\n        usePolling: true,\n      },\n    },\n  });\n};\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":192,"estimatedTokens":870}}120{"id":"stack-77023769","source":"stackoverflow","questionId":77023769,"title":"Unable to locate file in Vite manifest: resources/js/Pages/MainPage.vue","tags":["laravel","vue.js","vite","inertiajs"],"text":"Title: Unable to locate file in Vite manifest: resources/js/Pages/MainPage.vue\nTags: laravel, vue.js, vite, inertiajs\nSource: Stack Overflow\n\nQuestion:\nI'm using Laravel + Inertia + VueJS + Vite.\n\nI did some research and it seems many people have different variations of this error, but none of the answers seem convincing enough or apply to my problem.\n\n**The error :**\n\nUnable to locate file in Vite manifest:\nresources/js/Pages/MainPage.vue.\n\n**Preface :**\n\nAs with other people, everything works correctly and as expected when running `npm run dev`, but after building the files for production using `npm run build`, the error occurs.\n\n**Code :**\n\nIn the head of my app.blade.php :\n\n```\n@routes\n@vite(['resources/js/app.ts', \"resources/js/Pages/{$page['component']}.vue\"])\n@inertiaHead\n```\n\n**Details :**\n\n- I'm on Windows.\n\n- Vite version : `4.0.0`\n\n- `APP_ENV=production` in `.env`\n\nIf you need any more details, feel free to ask.\n\n**What I tried :**\n\n- The error dissapears when deleting `\"resources/js/Pages/{$page['component']}.vue\"` from `app.blade.php`, but that just invites other problems : I can see in the network tab of DevTools that `/build/assets/app-3c9a2cd6.js` and `/build/assets/MainPage-0889c7a1.js` are being served correctly but they don't seem to be mounting (I put `console.log` in the `setup` function inside `app.ts` but it's not doing anything, same thing for `MainPage.vue`). I therefore think deleting `\"resources/js/Pages/{$page['component']}.vue\"` is not the way to go, I could be wrong...\n\n========================================\n\nTop Answer:\n- Restart the server\n\n- npm run build\n\n- npm run dev\n\n- php artisan serve\n\nReload the page.\n\n========================================\n\nCode:\n```text\n@routes\n@vite(['resources/js/app.ts', \"resources/js/Pages/{$page['component']}.vue\"])\n@inertiaHead\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run build\n```\n\n```text\n4.0.0\n```\n\n```text\nAPP_ENV=production\n```\n\n```text\n.env\n```\n\n```text\n\"resources/js/Pages/{$page['component']}.vue\"\n```\n\n```text\napp.blade.php\n```\n\n```text\n/build/assets/app-3c9a2cd6.js\n```\n\n```text\n/build/assets/MainPage-0889c7a1.js\n```\n\n```text\nconsole.log\n```\n\n```text\nsetup\n```\n\n```text\napp.ts\n```\n\n```text\nMainPage.vue\n```\n\n```text\n\"resources/js/Pages/{$page['component']}.vue\"\n```\n\n```text\n@vite(['resources/js/app.js'])\n```\n\n```text\napp.blade.php\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm install\n```\n\n```text\nnpm run dev -- --force\n```\n\n```text\n@vite(['resources/js/app.js', \"resources/js/Pages/{$page['component']}.vue\"])\n```\n\n```text\nnpm run build\n```\n\n```text\n\"resources/js/Pages/{$page['component']}.vue\"\n```\n\n```text\nRoute::get('/{any}', function () {\n  return view('app'); // Replace 'app' with your main Blade file name\n})->where('any', '.*');\n```\n\n```js\nresolve: (name) => {\n    const page = resolvePageComponent(\n      `./Pages/${name}.vue`,\n      import.meta.glob<DefineComponent>('./Pages/**/*.vue'),\n    );\n    page.then((p) => {\n      p.default.layout = p.default?.layout || MainLayout;\n    });\n    return page;\n  },\n```\n\n```text\nlaravel new\n```\n\n```text\nnpm i --force\n```\n\n```text\nnpm run build\n```\n\n```text\ncomposer run dev\n```\n\n========================================\n\nComments:\n- Hello, I have the same problem without acceptable solution right now. I found a way to make the `npm run build` work, but it breaks the `npm run dev`, so I have to alternate the code between developping phase and prod deployment. It works, but it's not great. To do that, everything happens in the app.js, replacing `const pages = import.meta.glob('.&#47;Pages&#47;**&#47;*.vue', {eager: true}); let page = pages[`.&#47;Pages&#47;${name}.vue`];` by `const page = resolvePageComponent(`.&#47;Pages&#47;${name}.vue`,import.meta.glob(&zwnj;&#8203;'.&#47;Pages&#47;**&#47;*.vue'))&zwnj;&#8203;;`. I have no idea why it works.I'll post an answer if I find a solution.\n- Sure enough, I determined that these assets were not listed in `&#47;public&#47;build&#47;manifest.json.` (The Vite manifest) In my case, I neglected returning the `app` object from the `setup` property in `createInertiaApp` in `app.js`\n- Hello, I had already tried this (check the \"What I tried\" section please).\n- Did you also setup the inertia SSR server?\n- did this but still get errors about ` Unable to locate file in Vite manifest:`\n- If you read again the question, it seems OP is already doing that.\n- I had the same problem trying to the Laravel bootcamp. I ran into \"Unable to locate file in Vite manifest: resources/js/Pages/Chirps/Index.vue\" and then restarting the dev and php artisan helped","metadata":{"transformedAt":"2026-08-18T18:33:46.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":201,"estimatedTokens":1149}}121{"id":"stack-79389181","source":"stackoverflow","questionId":79389181,"title":"How the container padding will use in Tailwind CSS v4","tags":["css","containers","tailwind-css","vite","tailwind-css-4"],"text":"Title: How the container padding will use in Tailwind CSS v4\nTags: css, containers, tailwind-css, vite, tailwind-css-4\nSource: Stack Overflow\n\nQuestion:\nIn Tailwind CSS v3 there was a file `tailwind.config.js` where we could declare different padding for different screens like this:\n\n```\ntheme:{\n container: {\n center: true,\n padding: {\n DEFAULT: `10px`,\n sm : `20px`,\n lg : `80px`,\n xl : `120px`\n }\n }\n}\n```\n\nNow there is no `tailwind.config.js`.\n\nWe have to use global CSS.\n\nHow to put those padding in container as there is no way/scope it.\n\nEven though they have `@container` but now way to put these padding variables which could take their padding size auto.\n\nI tried using\n\n```\n@container {}\n\n@utility container{}\n\n@layers {\n @media container (){}\n}\n```\n\n========================================\n\nTop Answer:\n**Tailwind v4 has .container class** and its generated values are:\n\n```\n.container {\n width: 100%;\n @media (width >= 40rem) {\n max-width: 40rem;\n }\n @media (width >= 48rem) {\n max-width: 48rem;\n }\n @media (width >= 64rem) {\n max-width: 64rem;\n }\n @media (width >= 80rem) {\n max-width: 80rem;\n }\n @media (width >= 96rem) {\n max-width: 96rem;\n }\n }\n```\n\nSo you can add your style to it in html file itself. **You don't have to do any other stuff.**\n\n**CENTER:**\n\n```\n Hi \n```\n\n**RESPONSIVE PADDING:**\n\n```\n Hi \n```\n\n========================================\n\nCode:\n```js\ntheme:{\n    container: {\n       center: true,\n       padding: {\n          DEFAULT: `10px`,\n           sm : `20px`,\n           lg : `80px`,\n           xl : `120px`\n       }\n    }\n}\n```\n\n```css\n@container {}\n\n@utility container{}\n\n@layers {\n  @media container (){}\n}\n```\n\n```text\ntailwind.config.js\n```\n\n```text\ntailwind.config.js\n```\n\n```text\n@container\n```\n\n```css\n@utility container {\n  …\n}\n```\n\n```css\n@utility container {\n  padding-inline: 10px;\n  margin-inline: auto;\n}\n```\n\n```css\n@utility container {\n  padding-inline: 10px;\n  margin-inline: auto;\n  \n  @variant sm {\n    padding-inline: 20px;\n  }\n  \n  @variant lg {\n    padding-inline: 80px;\n  }\n  \n  @variant xl {\n    padding-inline: 120px;\n  }\n}\n```\n\n```html\n<script src=\"https://unpkg.com/@tailwindcss/browser@4.0.0\"></script>\n\n<style type=\"text/tailwindcss\">\n@utility container {\n  padding-inline: 10px;\n  margin-inline: auto;\n  \n  @variant sm {\n    padding-inline: 20px;\n  }\n  \n  @variant lg {\n    padding-inline: 80px;\n  }\n  \n  @variant xl {\n    padding-inline: 120px;\n  }\n}\n</style>\n\n<div class=\"container bg-red-400\">\n  <div class=\"bg-green-400 h-10\"></div>\n</div>\n```\n\n```text\n@utility\n```\n\n```text\nDEFAULT\n```\n\n```text\n@variant\n```\n\n```css\n.container {\n    width: 100%;\n    @media (width >= 40rem) {\n      max-width: 40rem;\n    }\n    @media (width >= 48rem) {\n      max-width: 48rem;\n    }\n    @media (width >= 64rem) {\n      max-width: 64rem;\n    }\n    @media (width >= 80rem) {\n      max-width: 80rem;\n    }\n    @media (width >= 96rem) {\n      max-width: 96rem;\n    }\n  }\n```\n\n```html\n<div class=\"container mx-auto\"> Hi </div>\n```\n\n```html\n<div class=\"container mx-auto sm:px-2 md:px-3 lg:px-4\"> Hi </div>\n```\n\n========================================\n\nComments:\n- Thanks a lot... It Worked ... Also if I use apply mx-auto px-[10px] sm:px-[20px] lg:px-[120px] in just @utility container{} instead of using varient ... Will it be bad practice? Or good practice?\n- Adam Wathan (creator of Tailwind) does seem to advocate avoiding `@apply`: twitter.com/adamwathan/status/1226511611592085504, twitter.com/adamwathan/status/1559250403547652097\n- Yes, I would clearly use `@apply` only for existing classes or where it significantly simplifies the code. However, using it just to generate a specific padding like `px-[10px]`, `px-[11px]`, etc., has never been a good practice, as each of these will generate a new class. If you’re only using it once, it’s inherently a \"waste\" of space.\n- So only for styling @apply is good?!!! Except for container and some main stuffs!!! Cause, using apply on external CSS folder keeps the component structure clear.. Using in-line makes mess in the structure.\n- Using inline is the most preferrable. As per the above, try to avoid `@apply` and use regular CSS instead. Use `var()` or `--spacing()` to reference theme tokens if needed. Use `@variant` to reference variants.\n- well .. if it is better than I have to adapt using those... was using @apply always.. have to learn using theme and all those tokens 😅\n- How are these variants called then? `container-sm`, `container-[sm]`, or even something else? Maybe add a second container with a variant to clarify...\n- I think you may be incorrectly interpreting the `@variant` tags. Tailwind converts them to their equivalent variant values within the CSS rule, so in this case, `@media` queries. See the documentation on `@variant`.\n- Oh, I see. I thought this was to create tailwind rules that are customizable, like `@layer utilities` but with arbitrary values. Been looking for hours how to do that, but can't seem to find anything useful...\n- You'd use the `@utility` directive.\n- From my understanding the @variant here works similar to how extends worked in V3..someone to correct me if I'm wrong.\n- That's wrong. `@variant` is syntax sugar for adding a variant's selector modifier into the CSS. As an example, `@variant sm {}` and `@media (width >= 40rem) {}` are equivalent.","metadata":{"transformedAt":"2026-08-18T18:33:46.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":235,"estimatedTokens":1329}}122{"id":"stack-66470249","source":"stackoverflow","questionId":66470249,"title":"Vue 3 with Vite rendering blank page when not using App.vue","tags":["javascript","html","vue.js","vuejs3","vite"],"text":"Title: Vue 3 with Vite rendering blank page when not using App.vue\nTags: javascript, html, vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\n**Setup**\n\nI've initialized a new project using vite on an Arch based operating system.\n\nWhen I try to create the simple counter from the vue docs, the elemet doesn't render.\n\n**Code**\n\nindex.html:\n\n```\n\n \n \n \n \n Vite App\n \n \n \n Counter: {{ counter }}\n \n \n \n \n\n```\n\nmain.js\n\n```\nimport { createApp } from 'vue'\n\nvar CounterApp = {\n data() {\n return {\n counter: 0\n }\n },\n mounted() {\n setInterval(() => {\n this.counter++\n }, 1000)\n }\n }\n \n \ncreateApp(CounterApp).mount('#counter')\n```\n\nWhen I inspect the element it is commented out:\n\nhttps://i.sstatic.net/B88Fh.png\n\n**Question**\n\nWhy is that? And how to resolve the error?\n\n========================================\n\nTop Answer:\nBy default the runtime compiler is not included in the Vue build.\nTo include it, add the following `resolve.alias` configuration:\n\n`vite.config.js`\n\n```\nexport default defineConfig({\n plugins: [vue()],\n resolve: {\n alias: {\n vue: 'vue/dist/vue.esm-bundler.js',\n },\n },\n})\n```\n\nDocs https://vitejs.dev/config/#resolve-alias\n\n========================================\n\nCode:\n```text\n<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <link rel=\"icon\" href=\"/favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>Vite App</title>\n  </head>\n  <body>\n    <div id=\"counter\">\n      Counter: {{ counter }}\n    </div>\n    \n    <script type=\"module\" src=\"/src/main.js\"></script>\n  </body>\n</html>\n```\n\n```text\nimport { createApp } from 'vue'\n\nvar CounterApp = {\n    data() {\n      return {\n        counter: 0\n      }\n    },\n    mounted() {\n      setInterval(() => {\n        this.counter++\n      }, 1000)\n    }\n  }\n  \n  \ncreateApp(CounterApp).mount('#counter')\n```\n\n```html\n<body>\n  <div id=\"app\"></div>\n  <script type=\"module\" src=\"/src/main.js\"></script>\n</body>\n```\n\n```js\nimport { createApp } from 'vue'\nimport App from './App.vue'\n\ncreateApp(App).mount('#app')\n```\n\n```html\n<template>\n  <div id=\"counter\">\n    Counter: {{ counter }}\n  </div>\n</template>\n```\n\n```js\n<script>\nexport default {\n  name: 'App',\n  data() {\n    return {\n      counter: 0\n    }\n  },\n  mounted() {\n    setInterval(() => {\n      this.counter++\n    }, 1000)\n  }\n}\n</script>\n```\n\n```text\nApp\n```\n\n```text\nApp\n```\n\n```text\nexport default defineConfig({\n  plugins: [vue()],\n  resolve: {\n      alias: {\n        vue: 'vue/dist/vue.esm-bundler.js',\n      },\n    },\n})\n```\n\n```text\nresolve.alias\n```\n\n```text\nvite.config.js\n```\n\n========================================\n\nComments:\n- Note that this increases the size of the app by ~30%. You're not wrong about how it's done, but it would be better to simply use the recommended mounting code unless there is some special reason to use the runtime compiler.","metadata":{"transformedAt":"2026-08-18T18:33:46.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":197,"estimatedTokens":716}}123{"id":"stack-79241624","source":"stackoverflow","questionId":79241624,"title":"Integrating TailwindCSS v4 alpha with Vite and PostCSS config","tags":["tailwind-css","vite","postcss","tailwind-css-4"],"text":"Title: Integrating TailwindCSS v4 alpha with Vite and PostCSS config\nTags: tailwind-css, vite, postcss, tailwind-css-4\nSource: Stack Overflow\n\nQuestion:\nSo I've managed to get TailwindCSS v4 alpha working for starters. It uses the `postcss.config.js` file:\n\n```\nexport default {\n plugins: {\n '@tailwindcss/postcss': {},\n }\n};\n```\n\nHowever I read that I should be able to do something like this in my `vite.config.js` (and delete the `postcss.config.js` file):\n\n```\n@@ -1,5 +1,6 @@\n import { defineConfig } from \"vite\";\n import { sveltekit } from \"@sveltejs/kit/vite\";\n+import tailwind from \"tailwindcss\";\n \n // @ts-expect-error process is a nodejs global\n const host = process.env.TAURI_DEV_HOST;\n@@ -29,4 +30,9 @@ export default defineConfig(async () => ({\n ignored: [\"**/src-tauri/**\"],\n },\n },\n+ css: {\n+ postcss: {\n+ plugins: [tailwind],\n+ },\n+ },\n }));\n```\n\nUnfortunately the following error rears it's ugly head:\n\n[plugin:vite:css] [postcss] It looks like you're trying to use `tailwindcss` directly as a PostCSS plugin. The PostCSS plugin has moved to a separate package, so to continue using Tailwind CSS with PostCSS you'll need to install `@tailwindcss/postcss` and update your PostCSS configuration.\n\nMore unfortunately, my `package.json` already includes `@tailwindcss/postcss` as a dev dependency:\n\n```\n{\n \"devDependencies\": {\n \"@sveltejs/adapter-static\": \"^3.0.5\",\n \"@sveltejs/kit\": \"^2.7.0\",\n \"@sveltejs/vite-plugin-svelte\": \"^4.0.0\",\n \"@tailwindcss/postcss\": \"4.0.0-beta.4\",\n \"@tauri-apps/cli\": \"^2\",\n \"svelte\": \"^5.0.0\",\n \"svelte-check\": \"^4.0.0\",\n \"tailwindcss\": \"4.0.0-beta.4\",\n \"tslib\": \"^2.8.0\",\n \"typescript\": \"^5.5.0\",\n \"vite\": \"^5.4.10\"\n }\n}\n```\n\nWhy does this error still appear?\n\n========================================\n\nTop Answer:\nI faced the same issue despite following the migration guide from v3. Reading this answer, I created a `.postcssrc.json` file instead of `postcss.config.[js|mjs]` **and it solved it !**\n\n```\n// .postcssrc.json\n{\n \"plugins\": {\n \"@tailwindcss/postcss\": {}\n }\n}\n```\n\n========================================\n\nCode:\n```js\nexport default {\n  plugins: {\n    '@tailwindcss/postcss': {},\n  }\n};\n```\n\n```js\n@@ -1,5 +1,6 @@\n import { defineConfig } from \"vite\";\n import { sveltekit } from \"@sveltejs/kit/vite\";\n+import tailwind from \"tailwindcss\";\n \n // @ts-expect-error process is a nodejs global\n const host = process.env.TAURI_DEV_HOST;\n@@ -29,4 +30,9 @@ export default defineConfig(async () => ({\n       ignored: [\"**/src-tauri/**\"],\n     },\n   },\n+  css: {\n+    postcss: {\n+      plugins: [tailwind],\n+    },\n+  },\n }));\n```\n\n```json\n{\n  \"devDependencies\": {\n    \"@sveltejs/adapter-static\": \"^3.0.5\",\n    \"@sveltejs/kit\": \"^2.7.0\",\n    \"@sveltejs/vite-plugin-svelte\": \"^4.0.0\",\n    \"@tailwindcss/postcss\": \"4.0.0-beta.4\",\n    \"@tauri-apps/cli\": \"^2\",\n    \"svelte\": \"^5.0.0\",\n    \"svelte-check\": \"^4.0.0\",\n    \"tailwindcss\": \"4.0.0-beta.4\",\n    \"tslib\": \"^2.8.0\",\n    \"typescript\": \"^5.5.0\",\n    \"vite\": \"^5.4.10\"\n  }\n}\n```\n\n```text\npostcss.config.js\n```\n\n```text\nvite.config.js\n```\n\n```text\npostcss.config.js\n```\n\n```text\ntailwindcss\n```\n\n```text\n@tailwindcss/postcss\n```\n\n```text\npackage.json\n```\n\n```text\n@tailwindcss/postcss\n```\n\n```bash\n$ npm install tailwindcss@next @tailwindcss/vite@next\n```\n\n```ts\nimport { defineConfig } from 'vite';\nimport tailwindcss from '@tailwindcss/vite';\n\nexport default defineConfig({\n  plugins: [\n    tailwindcss()\n   ],\n});\n```\n\n```css\n@import \"tailwindcss\";\n```\n\n```text\nvite.config.ts\n```\n\n```text\n@tailwindcss/postcss\n```\n\n```text\n@tailwindcss/vite@next\n```\n\n```text\nimport\n```\n\n```text\n@tailwindcss/vite\n```\n\n```text\nplugins\n```\n\n```text\n@import \"tailwindcss\"\n```\n\n```text\nnpm uninstall autoprefixer postcss tailwindcss\nnpm install tailwindcss@^3.4.17 postcss@^8.5.0 autoprefixer@^10.4.20\n```\n\n```text\n// .postcssrc.json\n{\n   \"plugins\": {\n      \"@tailwindcss/postcss\": {}\n   }\n}\n```\n\n```text\n.postcssrc.json\n```\n\n```text\npostcss.config.[js|mjs]\n```\n\n========================================\n\nComments:\n- Related from January 2025 (when released stable v4): How to upgrade TailwindCSS? and Cannot build frontend using Vite, TailwindCSS with PostCSS and Open-sourcing our progress on Tailwind CSS v4.0 - Whats changed\n- Actually, removing autoprefixer and PostCSS is pointless since you end up reinstalling them anyway, just in a version-specific manner. The key point is that `npm install tailwindcss` installs v4, but you installed v3 using `npm install tailwindcss@3`.\n- However, the question already starts in the title by stating that they are looking for a solution for v4-alpha. But since then, the stable v4 version has also been released, see: Problem installing TailwindCSS with Vite; How to upgrade TailwindCSS?; Cannot build frontend using Vite\n- Don’t add code only answers. Explain what your code does, why it works, and how it helps to so,ve the problem\n- This one works for me. I am using astro with tailwind.","metadata":{"transformedAt":"2026-08-18T18:33:46.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":231,"estimatedTokens":1230}}124{"id":"stack-72147018","source":"stackoverflow","questionId":72147018,"title":"vitest test await async completion of onMounted callback in vue3 component","tags":["vue.js","async-await","vuejs3","vite","vitest"],"text":"Title: vitest test await async completion of onMounted callback in vue3 component\nTags: vue.js, async-await, vuejs3, vite, vitest\nSource: Stack Overflow\n\nQuestion:\nI'm playing around with Vitest and want to wait for the completion of a couple mocked fetches in the onMounted lifecycle hook in my component:\n\nMy test:\n\n```\nimport { mount } from '@vue/test-utils';\nimport HelloWorld from './HelloWorld.vue';\nimport { mockGet } from 'vi-fetch';\nimport 'vi-fetch/setup';\n\nmockGet('api/welcome-message').willResolve('Welcome message from vitest');\nmockGet('api/players').willResolve(['Mario', 'Luigi']);\n\ntest('the players have been rendered', async () => {\n const wrapper = mount(HelloWorld);\n\n const lastPlayer = await wrapper.findAll('.player');\n expect(lastPlayer).toHaveLength(2);\n});\n```\n\nMy component script:\n\n```\n\nimport { onMounted, ref } from 'vue';\n\nconst apiMessage = ref('');\nconst players = ref([]);\n\nonMounted(async () => {\n const fetchMessage = fetch('api/welcome-message')\n .then((res) => res.text())\n .then((message: string) => (apiMessage.value = message));\n\n const fetchPlayers = fetch('api/players')\n .then((res) => res.json())\n .then((playersRes: string[]) => (players.value = playersRes));\n});\n\n```\n\nThe test fails because, I assume, the code running in onMounted doesn't have time to complete before the test looks for all `.player` `` elements (rendered with a v-for) off of the `players` ref. How can I ask vitest to wait for the responses from each of these fetches before calling the test a failure.\n\nThanks.\n\n========================================\n\nCode:\n```js\nimport { mount } from '@vue/test-utils';\nimport HelloWorld from './HelloWorld.vue';\nimport { mockGet } from 'vi-fetch';\nimport 'vi-fetch/setup';\n\nmockGet('api/welcome-message').willResolve('Welcome message from vitest');\nmockGet('api/players').willResolve(['Mario', 'Luigi']);\n\n\ntest('the players have been rendered', async () => {\n  const wrapper = mount(HelloWorld);\n\n  const lastPlayer = await wrapper.findAll('.player');\n  expect(lastPlayer).toHaveLength(2);\n});\n```\n\n```html\n<script setup lang=\"ts\">\nimport { onMounted, ref } from 'vue';\n\nconst apiMessage = ref('');\nconst players = ref<string[]>([]);\n\n\nonMounted(async () => {\n  const fetchMessage = fetch('api/welcome-message')\n    .then((res) => res.text())\n    .then((message: string) => (apiMessage.value = message));\n\n  const fetchPlayers = fetch('api/players')\n    .then((res) => res.json())\n    .then((playersRes: string[]) => (players.value = playersRes));\n});\n</script>\n```\n\n```text\n.player\n```\n\n```text\n<li>\n```\n\n```text\nplayers\n```\n\n```js\ntest('...', async() => {\n  ⋮\n  await new Promise(r => setTimeout(r));\n})\n```\n\n```js\nimport { flushPromises } from '@vue/test-utils';\n\ntest('...', async() => {\n  ⋮\n  await flushPromises();\n})\n```\n\n```js\n👇\nimport { mount, flushPromises } from '@vue/test-utils';\nimport HelloWorld from './HelloWorld.vue';\nimport { mockGet } from 'vi-fetch';\nimport 'vi-fetch/setup';\n\nmockGet('api/welcome-message').willResolve('Welcome message from vitest');\nmockGet('api/players').willResolve(['Mario', 'Luigi']);\n\n\ntest('the players have been rendered', async () => {\n  const wrapper = mount(HelloWorld);\n             👇\n  await flushPromises();\n\n  const lastPlayer = await wrapper.findAll('.player');\n  expect(lastPlayer).toHaveLength(2);\n});\n```\n\n```text\nPromises\n```\n\n========================================\n\nComments:\n- Love those emoji pointers for better readability\n- I found that flushPromises works only if there is a single await. I had to use Promise.all() and convert multiple awaits to a single one.","metadata":{"transformedAt":"2026-08-18T18:33:46.401Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":150,"estimatedTokens":898}}125{"id":"stack-76471876","source":"stackoverflow","questionId":76471876,"title":"React Vite Typescript version 5 can't use new decorators","tags":["reactjs","typescript","vite","typescript-decorator"],"text":"Title: React Vite Typescript version 5 can't use new decorators\nTags: reactjs, typescript, vite, typescript-decorator\nSource: Stack Overflow\n\nQuestion:\nI created new React Typescript app using vite\n\nI executed `npm create vite@latest` then selected `typescript-swc`\n\n- Typescript version in package.json is ^5.0.2\n\n- The version in node_modules/typescript/package.json is 5.1.3\n\n- My global version is 5.1.3\n\nI can't get why I can not use the new decorators\n\n```\nfunction loggedMethod(originalMethod: any, context: ClassMethodDecoratorContext) {\n console.log(context)\n const methodName = String(context.name)\n function replacementMethod(this: any, ...args: any[]) {\n console.log(`LOG: Entering method '${methodName}'.`)\n const result = originalMethod.call(this, ...args)\n console.log(`LOG: Exiting method '${methodName}'.`)\n return result\n }\n return replacementMethod\n}\n\nclass Person {\n name: string\n\n constructor(name: string) {\n this.name = name\n }\n\n @loggedMethod\n greet() {\n console.log(`Hello, my name is ${this.name}.`)\n }\n}\nconst p = new Person('Ray')\np.greet()\n```\n\nThis is the code I am trying to execute\n\nI can't execute this without setting `tsDecorators: true` in the vite config plugin from `@vitejs/plugin-react-swc`. It is the only plugin I have, nothing more in the vite config.\n\n`console.log(context)` logs the method name `greet` as a string, just like the old decorators, but it should be object. `replacementMethod` does not get called at all\n\nI haven't set `experimentalDecorators` in `tsconfig.ts`\n\n**Why decorators work like the ones from version 4, instead of 5?**\n\n========================================\n\nCode:\n```text\nfunction loggedMethod(originalMethod: any, context: ClassMethodDecoratorContext) {\n  console.log(context)\n  const methodName = String(context.name)\n  function replacementMethod(this: any, ...args: any[]) {\n      console.log(`LOG: Entering method '${methodName}'.`)\n      const result = originalMethod.call(this, ...args)\n      console.log(`LOG: Exiting method '${methodName}'.`)\n      return result\n  }\n  return replacementMethod\n}\n\nclass Person {\n  name: string\n\n  constructor(name: string) {\n      this.name = name\n  }\n\n  @loggedMethod\n  greet() {\n      console.log(`Hello, my name is ${this.name}.`)\n  }\n}\nconst p = new Person('Ray')\np.greet()\n```\n\n```text\nnpm create vite@latest\n```\n\n```text\ntypescript-swc\n```\n\n```text\ntsDecorators: true\n```\n\n```text\n@vitejs/plugin-react-swc\n```\n\n```text\nconsole.log(context)\n```\n\n```text\ngreet\n```\n\n```text\nreplacementMethod\n```\n\n```text\nexperimentalDecorators\n```\n\n```text\ntsconfig.ts\n```\n\n========================================\n\nComments:\n- Read this article: An ESBuild Setup for TypeScript. It explicitly explains why Vite doesn't support TypeScript 5's Stage-3 decorators.\n- For tracking purposes: github.com/evanw/esbuild/issues/104\n- Same issue with modern angular since it uses those tools by default now.\n- esbuild now supports decorators from TS5. I upgraded my project from vite 4 to vite 6 and TS 5 decorators are now working.","metadata":{"transformedAt":"2026-08-18T18:33:46.401Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":131,"estimatedTokens":757}}126{"id":"stack-75846073","source":"stackoverflow","questionId":75846073,"title":"Vercel + Reactjs & Vite Returning 404 on page refresh","tags":["reactjs","vite","vercel"],"text":"Title: Vercel + Reactjs & Vite Returning 404 on page refresh\nTags: reactjs, vite, vercel\nSource: Stack Overflow\n\nQuestion:\nSo i have a code base that i built using React, TailwindCSS, and Vite using react router as the routing.\n\nFor some reason when built going to the home page and the rest of the pages work perfect, but once i refresh, i am given a 404 error.\n\ni have checked my vercel.json file. i have tried other solutions that have been posted on here and im not sure where im going wrong. I have tried adding this file in the root of my folder (where it currently is) and also inside my src folder as i seen some examples with that as well.\n\nI have tried changing\n\n```\nroutes: [\n{ \n \"src\" : //here\n }\n ]\n```\n\nper examples i have seen but to luck!\n\nlet me know what i need to do or if youd like to see any other files, but the src code is available here\n\nhttps://github.com/InsurTech-Groups/home-form-english\n\nThanks!\n\n### Additional information\n\nvercel.json\n\n```\n{\n \"version\": 2,\n \"builds\": [\n {\n \"src\": \"package.json\",\n \"use\": \"@vercel/node\",\n \"config\": {\n \"maxLambdaSize\": \"75mb\"\n }\n },\n {\n \"src\": \"index.html\",\n \"use\": \"@vercel/static-build\",\n \"config\": {\n \"distDir\": \"dist\",\n \"command\": \"npm run build\",\n \"env\": {\n \"NODE_ENV\": \"production\"\n },\n \"output\": {\n \"clean\": true\n },\n \"postbuild\": {\n \"command\": \"npm run postbuild\",\n \"env\": {\n \"BUILD_DIR\": \"$VERCEL_BUILD_OUTPUT_DIR\"\n }\n },\n \"files\": [\n \"dist/**/*\",\n \"public/**/*\",\n \"src/**/*.{js,jsx,ts,tsx}\",\n \"!**/node_modules/**\"\n ]\n }\n }\n ],\n \"routes\": [\n {\n \"src\": [{ \"src\": \"/[^.]+\", \"dest\": \"/\", \"status\": 200 }],\n \"dest\": \"/index.html\"\n }\n ]\n}\n```\n\nLinks\nGithubURL: https://github.com/InsurTech-Groups/home-form-english\nLive Vercel Site: https://home-form-english.vercel.app\n\n========================================\n\nTop Answer:\nThis issue occurs because Vercel serves static files, and when you refresh a page on a sub-route (e.g., `/dashboard` or `/profile`), it looks for a corresponding file on the server, which doesn’t exist. React Router handles routing on the client side, but Vercel doesn’t know how to redirect those routes correctly without additional configuration.\n\n### Solution: Configure `vercel.json`\n\nTo ensure all routes are served correctly, add a `vercel.json` file in the root directory with the following content:\n\n```\n{\n \"rewrites\": [\n { \"source\": \"/(.*)\", \"destination\": \"/index.html\" }\n ]\n}\n```\n\nThis rewrite rule tells Vercel to always serve `index.html`, allowing React Router to handle routing as expected.\n\n### Steps to Fix:\n\n- Create (or update) the `vercel.json` file in your project’s root directory.\n\n- Add the above rewrite rule.\n\n- Redeploy your project on Vercel.\n\n- Test refreshing a sub-route—it should now load correctly without a 404 error.\n\n### Additional Fix for Vite Projects\n\nIf you’re using Vite, update `vite.config.js` to ensure proper handling of history API fallback:\n\n```\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\nexport default defineConfig({\n plugins: [react()],\n base: \"/\",\n build: {\n outDir: \"dist\"\n },\n server: {\n historyApiFallback: true\n }\n});\n```\n\nThis configuration ensures that Vite properly handles routing in development while Vercel takes care of it in production.\n\nAfter applying these fixes, your app should no longer return a 404 error on page refresh.\n\n========================================\n\nCode:\n```json\nroutes: [\n{ \n \"src\" :  //here\n }\n ]\n```\n\n```json\n{\n  \"version\": 2,\n  \"builds\": [\n    {\n      \"src\": \"package.json\",\n      \"use\": \"@vercel/node\",\n      \"config\": {\n        \"maxLambdaSize\": \"75mb\"\n      }\n    },\n    {\n      \"src\": \"index.html\",\n      \"use\": \"@vercel/static-build\",\n      \"config\": {\n        \"distDir\": \"dist\",\n        \"command\": \"npm run build\",\n        \"env\": {\n          \"NODE_ENV\": \"production\"\n        },\n        \"output\": {\n          \"clean\": true\n        },\n        \"postbuild\": {\n          \"command\": \"npm run postbuild\",\n          \"env\": {\n            \"BUILD_DIR\": \"$VERCEL_BUILD_OUTPUT_DIR\"\n          }\n        },\n        \"files\": [\n          \"dist/**/*\",\n          \"public/**/*\",\n          \"src/**/*.{js,jsx,ts,tsx}\",\n          \"!**/node_modules/**\"\n        ]\n      }\n    }\n  ],\n  \"routes\": [\n    {\n      \"src\": [{ \"src\": \"/[^.]+\", \"dest\": \"/\", \"status\": 200 }],\n      \"dest\": \"/index.html\"\n    }\n  ]\n}\n```\n\n```json\n{\n  \"rewrites\": [{ \n      \"source\": \"/(.*)\",\n      \"destination\": \"/\" }]\n}\n```\n\n```text\n{\n  // ...\n  \"routes\": [\n    // ...\n    { \"handle\": \"filesystem\" }\n  ]\n}\n```\n\n```json\n{\n  \"rewrites\": [\n    { \"source\": \"/(.*)\", \"destination\": \"/index.html\" }\n  ]\n}\n```\n\n```js\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\nexport default defineConfig({\n  plugins: [react()],\n  base: \"/\",\n  build: {\n    outDir: \"dist\"\n  },\n  server: {\n    historyApiFallback: true\n  }\n});\n```\n\n```text\n/dashboard\n```\n\n```text\n/profile\n```\n\n```text\nvercel.json\n```\n\n```text\nvercel.json\n```\n\n```text\nindex.html\n```\n\n```text\nvercel.json\n```\n\n```text\nvite.config.js\n```\n\n========================================\n\nComments:\n- meaning any path mentioned in source `\"&#47;(.*)\"` will rewrite requests to `\"&#47;\"` destination... source : vercel docs (vercel.com/docs/projects/project-configuration#rewrites)\n- I can't find any vercel.json. Should I add it manually to the root of my project?\n- yes create one and add it\n- Thanks, in my case i create a vercel.json file and added only the rewtires property\n- Yes this fixed this issue in my case too","metadata":{"transformedAt":"2026-08-18T18:33:46.402Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":273,"estimatedTokens":1367}}127{"id":"stack-74344683","source":"stackoverflow","questionId":74344683,"title":"How to import a JSON file from public directory with Vite?","tags":["vue.js","vuejs3","vite"],"text":"Title: How to import a JSON file from public directory with Vite?\nTags: vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI have a Vue3/Vite project where some data has to be read from an **external JSON** file.\n\nbut when i build the project - the JSON file gets bundled.\n\nI need to keep the JSON file external.\n\nWhat I've tried:\n\nfirst try\n`vite.config.ts`\n\n```\nexport default defineConfig({\n optimizeDeps:{\n exclude: ['myfile.json'] // then i tried ['**/myfile.json']\n },\n})\n```\n\n- second try\n\n`vite.config.ts`\n\n```\nassetsInclude: ['**/*.json'],\nassetsInlineLimit: 0,\n```\n\n- third try\n\n`App.vue`\n\n```\nlet jsonData = import.meta.glob('/public/assets/myfile.json')\n```\n\nWhat am I doing wrong - is there a simple way to keep a JSON file external?\n\n========================================\n\nCode:\n```js\nexport default defineConfig({\n  optimizeDeps:{\n    exclude: ['myfile.json'] // then i tried ['**/myfile.json']\n  },\n})\n```\n\n```js\nassetsInclude: ['**/*.json'],\nassetsInlineLimit: 0,\n```\n\n```js\nlet jsonData = import.meta.glob('/public/assets/myfile.json')\n```\n\n```text\nvite.config.ts\n```\n\n```text\nvite.config.ts\n```\n\n```text\nApp.vue\n```\n\n```html\n<script setup>\nimport { onMounted } from \"vue\";\n\nonMounted(async () => {\n  const response = await fetch(\"/file.json\");\n  const file = await response.json();\n  console.log(\"cool file\", file);\n});\n</script>\n```\n\n```json\n{\n  \"name\": \"bob\",\n  \"age\": 29\n}\n```\n\n```text\nfetch\n```\n\n```text\nimport\n```\n\n```text\nfile.json\n```\n\n========================================\n\nComments:\n- What do you mean by external? You're both trying to exclude + import it in your examples.\n- i need to prevent myfile.json from being bundled -> so it can be visible in dist/assets production folder. Probably example 2 is where you think I try to include it - but the goal there was to inform vite that I need it as a separate asset.\n- Not sure to understand. If you DON'T want it bundled, you should store it in `public` directory. If you WANT it to be bundled, then put it in your `src` or `assets` directories. Not sure to understand how you can mix both principles of bundling + keeping as an asset.\n- probably you`re right - but the problem with keeping it in public directory is that files in public folder can't be included. and I need the App to be able to read the JSON content.\n- If it's in `public`, you can totally access it. Actually, you can access your JSON from anywhere from within your project tbh.\n- include doesn't work - vitejs.dev/guide/assets.html#the-public-directory, require neither. so how could i access it otherwise?\n- With regular frontend modern `import` pretty much.\n- Vite documentation clearly states \"Assets in public directory cannot be imported from JavaScript.\" - and i also encountered errors. Can you please direct me to some resources about \"regular frontend modern import\" that would do the job?\n- \"imported from JavaScript\" ≠ \"imported into JavaScript\", I guess the doc means that you cannot generate things on the fly while using runtime? Not sure but it goes in the opposite direction of pretty much anything so far haha (maybe a bug or a super bad wording).\n- hi this works, but the data wont be updated when updating the json file. This occurs only in the deployed app, not locally runned app.\n- @Takkie253 if you run your app as SSR, then you could update the file and read the stream of the filesystem on the fly. Nothing out of bounds of a regular Node.js behavior. If your app is SSG and generated only at build time, then yes it will stay static. You could even do it with a serverless/edge function. Plenty of possibilities there IMO.\n- Yeah that explains it, my bad, my app is probably static\n- note to future people that might be as silly as me: make sure your `public` folder is not `src&#47;public`","metadata":{"transformedAt":"2026-08-18T18:33:46.402Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":122,"estimatedTokens":945}}128{"id":"stack-76510164","source":"stackoverflow","questionId":76510164,"title":"Can I safely delete vite.config.ts.timestamp* files?","tags":["vite","sveltekit"],"text":"Title: Can I safely delete vite.config.ts.timestamp* files?\nTags: vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm working on a SvelteKit project and I have a bunch of vite.config files:\n\n```\nll vite.config.*\n```\n\nOutput:\n\n```\n.rw-rw-r-- 1.3k sas 30 May 19:49 vite.config.ts\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977000-d9424581b6c6.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977001-6954a6ac5ac19.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977001-9201cfcc774c9.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977001-ad78163483ceb.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977007-4c080a380ebd9.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977007-4cf3e5ed6cf92.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977007-a642b2ba2f4cd.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977007-bcfada510dd4.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977007-d88f9fb0e8e01.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977007-f64dce72b77b8.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977008-6e0d56c4a9827.mjs\n```\n\nCan I safely remove them (or even better, prevent them from being generated at all)?\n\n========================================\n\nCode:\n```none\nll vite.config.*\n```\n\n```none\n.rw-rw-r-- 1.3k sas 30 May 19:49 vite.config.ts\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977000-d9424581b6c6.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977001-6954a6ac5ac19.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977001-9201cfcc774c9.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977001-ad78163483ceb.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977007-4c080a380ebd9.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977007-4cf3e5ed6cf92.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977007-a642b2ba2f4cd.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977007-bcfada510dd4.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977007-d88f9fb0e8e01.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977007-f64dce72b77b8.mjs\n.rw-rw-r-- 5.3k sas 19 Jun 18:09 vite.config.ts.timestamp-1687208977008-6e0d56c4a9827.mjs\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.402Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":51,"estimatedTokens":621}}129{"id":"stack-72031615","source":"stackoverflow","questionId":72031615,"title":"Volar and vue-tsc are showing different TS errors","tags":["typescript","vue.js","vuejs3","vscode-extensions","vite"],"text":"Title: Volar and vue-tsc are showing different TS errors\nTags: typescript, vue.js, vuejs3, vscode-extensions, vite\nSource: Stack Overflow\n\nQuestion:\nIn my Vite + Vue 3 + TypeScript project I have configured **vue-tsc** to run in **watch** mode while I am developing. I use **VS Code** with **Volar**. Now on one hand I have all my TS errors printed in the console which is what I was looking for. On the other hand I have extra errors from **vue-tsc**, but I don't have them from **Volar**.\n\nFor example,\nI have one error saying that **state.month** is not assignable to type **Date**, but it is **Date**.\n\n**vue-tsc**\nhttps://i.sstatic.net/8vTh3.png\n\ncomponent, **volar** does not showing that error\nhttps://i.sstatic.net/wGQU6.png\n\nstate in the component. As you see, **state.month** is **Date**\nhttps://i.sstatic.net/KFZxU.png\n\nCould someone help me, please? Did I missed something?\n\n========================================\n\nTop Answer:\nAnother thing to check is that your vue-tsc package is up to date. Volar is a VS Code extension and gets auto-updated over time, while vue-tsc is an npm package, so npm will lock it to a version and it could get outdated.\n\nThat was the solution for me.\nTo get the latest & save for dev, run `npm i -D vue-tsc@latest`.\n\nReference in the Volar repo:\nhttps://github.com/johnsoncodehk/volar/issues/1205\n\n========================================\n\nCode:\n```text\nnpm i -D vue-tsc@latest\n```\n\n========================================\n\nComments:\n- VSCode and your compiler may run different versions of TS.\n- Try to stop and start node server / VS code to see if it is fixed\n- @Duannx, thanks for answering. Tried multiple times, nothing's changed :(\n- @CodeWhisperer, thanks for answering! How can I check compiler's version of TS?\n- @Eduardo can you show your full code of that `state`'s definition? Try to push your code to an online playground like codesandbox.io so we can have a deeper look.\n- @Duannx thanks again, but I have already figured out what was the problem. CodeWhisperer's comment pointed me in the right direction.","metadata":{"transformedAt":"2026-08-18T18:33:46.402Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":48,"estimatedTokens":517}}130{"id":"stack-71648571","source":"stackoverflow","questionId":71648571,"title":"How can I import all the images from a folder into an array with React builded in Vite?","tags":["javascript","reactjs","import","vite"],"text":"Title: How can I import all the images from a folder into an array with React builded in Vite?\nTags: javascript, reactjs, import, vite\nSource: Stack Overflow\n\nQuestion:\nHello guys I have this component in my React app builded with Vite\n\n```\nimport img1 from \"../assets/img/avatars/avatar-1.svg\";\nimport img2 from \"../assets/img/avatars/avatar-2.svg\";\nimport img3 from \"../assets/img/avatars/avatar-3.svg\";\nimport img4 from \"../assets/img/avatars/avatar-4.svg\";\nimport img5 from \"../assets/img/avatars/avatar-5.svg\";\nimport img6 from \"../assets/img/avatars/avatar-6.svg\";\nimport img7 from \"../assets/img/avatars/avatar-7.svg\";\nimport img8 from \"../assets/img/avatars/avatar-8.svg\";\n\nconst Avatar = () => {\n const imgPaths = [img1, img2, img3, img4, img5, img6, img7, img8];\n const randomAvatar = Math.floor(Math.random() * imgPaths.length);\n\n return (\n <>\n \n \n );\n};\n\nexport default Avatar;\n```\n\nI need to import all my images at once, someone knows how to do that? I have tried things like\n\n```\nconst templates = require.context('../assets/img/avatars', true, /\\.(jpg|jpeg)$/);\n```\n\nbut as long as i'm not using webpack it's not working, ¿any help? thanks 💜\n\n========================================\n\nTop Answer:\n`const images = import.meta.glob(\"../assets/img/avatars/*\")`\n\nThis solution works for Vite\n\n========================================\n\nCode:\n```text\nimport img1 from \"../assets/img/avatars/avatar-1.svg\";\nimport img2 from \"../assets/img/avatars/avatar-2.svg\";\nimport img3 from \"../assets/img/avatars/avatar-3.svg\";\nimport img4 from \"../assets/img/avatars/avatar-4.svg\";\nimport img5 from \"../assets/img/avatars/avatar-5.svg\";\nimport img6 from \"../assets/img/avatars/avatar-6.svg\";\nimport img7 from \"../assets/img/avatars/avatar-7.svg\";\nimport img8 from \"../assets/img/avatars/avatar-8.svg\";\n\nconst Avatar = () => {\n    const imgPaths = [img1, img2, img3, img4, img5, img6, img7, img8];\n    const randomAvatar = Math.floor(Math.random() * imgPaths.length);\n\n    return (\n        <>\n            <img className={css.default} src={`${imgPaths[randomAvatar]}`} alt={`Avatar numero ${randomAvatar}`} />\n        </>\n    );\n};\n\nexport default Avatar;\n```\n\n```text\nconst templates = require.context('../assets/img/avatars', true, /\\.(jpg|jpeg)$/);\n```\n\n```text\nconst images = import.meta.glob(\"../assets/img/avatars/*\")\n```\n\n```text\nfunction getImgUrl(fileName){\n    let ext = '.png' // can be anything\n    const imgUrl = new URL(`./assets/${fileName}.${ext}`, import.meta.url).href\n    return imgUrl\n}\n\n \n<img src={getImgUrl(fileName)} alt=... />\n```\n\n========================================\n\nComments:\n- works fine, but my filenames are numbers, so I changed the path with concatenation `'.&#47;assets&#47;'+fileName+'.png'`","metadata":{"transformedAt":"2026-08-18T18:33:46.402Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":96,"estimatedTokens":683}}131{"id":"stack-72773373","source":"stackoverflow","questionId":72773373,"title":"'Buffer' is not exported by __vite-browser-external:buffer","tags":["javascript","svelte","vite","sveltekit"],"text":"Title: 'Buffer' is not exported by __vite-browser-external:buffer\nTags: javascript, svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm getting this build error with vite and sveltekit using adapter-node\n\nI'm not sure why it won't build since it relies on node to server the client.\n\ndev works fine\n\n`'Buffer' is not exported by __vite-browser-external:buffer`\n\nI tried polyfills but they don't work.\n\n```\noptimizeDeps: {\n esbuildOptions: {\n // Node.js global to browser globalThis\n define: {\n global: 'globalThis'\n },\n // Enable esbuild polyfill plugins\n plugins: [\n NodeGlobalsPolyfillPlugin({\n process: true,\n buffer: true,\n webworkers: true,\n }),\n NodeModulesPolyfillPlugin()\n ]\n }\n },\n build: {\n minify: true,\n rollupOptions: {\n plugins: [\n // Enable rollup polyfills plugin\n // used during production bundling\n rollupNodePolyFill()\n ]\n }\n }\n```\n\n========================================\n\nTop Answer:\nI solved it by adding the right aliases (including `buffer` and `process`) to `config.vite.ts`. That's how mine looks like:\n\n```\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport tsconfigPaths from 'vite-tsconfig-paths'\nimport { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'\nimport { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill'\nimport rollupNodePolyFill from 'rollup-plugin-node-polyfills'\n\nexport default defineConfig({\n plugins: [react(), tsconfigPaths()],\n server: {\n port: 3001,\n open: true\n },\n resolve: {\n alias: {\n // This Rollup aliases are extracted from @esbuild-plugins/node-modules-polyfill, \n // see https://github.com/remorses/esbuild-plugins/blob/master/node-modules-polyfill/src/polyfills.ts\n util: 'rollup-plugin-node-polyfills/polyfills/util',\n sys: 'util',\n events: 'rollup-plugin-node-polyfills/polyfills/events',\n stream: 'rollup-plugin-node-polyfills/polyfills/stream',\n path: 'rollup-plugin-node-polyfills/polyfills/path',\n querystring: 'rollup-plugin-node-polyfills/polyfills/qs',\n punycode: 'rollup-plugin-node-polyfills/polyfills/punycode',\n url: 'rollup-plugin-node-polyfills/polyfills/url',\n string_decoder:\n 'rollup-plugin-node-polyfills/polyfills/string-decoder',\n http: 'rollup-plugin-node-polyfills/polyfills/http',\n https: 'rollup-plugin-node-polyfills/polyfills/http',\n os: 'rollup-plugin-node-polyfills/polyfills/os',\n assert: 'rollup-plugin-node-polyfills/polyfills/assert',\n constants: 'rollup-plugin-node-polyfills/polyfills/constants',\n _stream_duplex:\n 'rollup-plugin-node-polyfills/polyfills/readable-stream/duplex',\n _stream_passthrough:\n 'rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough',\n _stream_readable:\n 'rollup-plugin-node-polyfills/polyfills/readable-stream/readable',\n _stream_writable:\n 'rollup-plugin-node-polyfills/polyfills/readable-stream/writable',\n _stream_transform:\n 'rollup-plugin-node-polyfills/polyfills/readable-stream/transform',\n timers: 'rollup-plugin-node-polyfills/polyfills/timers',\n console: 'rollup-plugin-node-polyfills/polyfills/console',\n vm: 'rollup-plugin-node-polyfills/polyfills/vm',\n zlib: 'rollup-plugin-node-polyfills/polyfills/zlib',\n tty: 'rollup-plugin-node-polyfills/polyfills/tty',\n domain: 'rollup-plugin-node-polyfills/polyfills/domain',\n buffer: 'rollup-plugin-node-polyfills/polyfills/buffer-es6',\n process: 'rollup-plugin-node-polyfills/polyfills/process-es6'\n }\n },\n optimizeDeps: {\n esbuildOptions: {\n // Node.js global to browser globalThis\n define: {\n global: 'globalThis'\n },\n // Enable esbuild polyfill plugins\n plugins: [\n NodeGlobalsPolyfillPlugin({\n process: true,\n buffer: true\n }),\n NodeModulesPolyfillPlugin()\n ]\n }\n },\n build: {\n rollupOptions: {\n plugins: [\n // Enable rollup polyfills plugin\n // used during production bundling\n // @ts-ignore\n rollupNodePolyFill(),\n ]\n }\n }\n})\n```\n\n========================================\n\nCode:\n```text\noptimizeDeps: {\n                esbuildOptions: {\n                    // Node.js global to browser globalThis\n                    define: {\n                        global: 'globalThis'\n                    },\n                    // Enable esbuild polyfill plugins\n                    plugins: [\n                        NodeGlobalsPolyfillPlugin({\n                            process: true,\n                            buffer: true,\n                            webworkers: true,\n                        }),\n                        NodeModulesPolyfillPlugin()\n                    ]\n                }\n            },\n            build: {\n                minify: true,\n                rollupOptions: {\n                    plugins: [\n                        // Enable rollup polyfills plugin\n                        // used during production bundling\n                        rollupNodePolyFill()\n                    ]\n                }\n            }\n```\n\n```text\n'Buffer' is not exported by __vite-browser-external:buffer\n```\n\n```text\nnpm install -D buffer\n```\n\n```js\n// vite.config.js\nbuild: {\n    commonjsOptions: {\n        include: ['node_modules/buffer/index.js']\n    }\n}\n```\n\n```js\n// vite.config.js\nbuild: {\n    commonjsOptions: {\n        include: ['node_modules/**/*.js']\n    }\n}\n```\n\n```text\n.js\n```\n\n```text\nbuild: {\n        rollupOptions: {\n            plugins: [inject({ Buffer: ['Buffer', 'Buffer'] })],\n        },\n    },\n```\n\n```text\nnpm i -D buffer\n```\n\n```js\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport tsconfigPaths from 'vite-tsconfig-paths'\nimport { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'\nimport { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill'\nimport rollupNodePolyFill from 'rollup-plugin-node-polyfills'\n\nexport default defineConfig({\n    plugins: [react(), tsconfigPaths()],\n    server: {\n        port: 3001,\n        open: true\n    },\n    resolve: {\n        alias: {\n            // This Rollup aliases are extracted from @esbuild-plugins/node-modules-polyfill, \n            // see https://github.com/remorses/esbuild-plugins/blob/master/node-modules-polyfill/src/polyfills.ts\n            util: 'rollup-plugin-node-polyfills/polyfills/util',\n            sys: 'util',\n            events: 'rollup-plugin-node-polyfills/polyfills/events',\n            stream: 'rollup-plugin-node-polyfills/polyfills/stream',\n            path: 'rollup-plugin-node-polyfills/polyfills/path',\n            querystring: 'rollup-plugin-node-polyfills/polyfills/qs',\n            punycode: 'rollup-plugin-node-polyfills/polyfills/punycode',\n            url: 'rollup-plugin-node-polyfills/polyfills/url',\n            string_decoder:\n                'rollup-plugin-node-polyfills/polyfills/string-decoder',\n            http: 'rollup-plugin-node-polyfills/polyfills/http',\n            https: 'rollup-plugin-node-polyfills/polyfills/http',\n            os: 'rollup-plugin-node-polyfills/polyfills/os',\n            assert: 'rollup-plugin-node-polyfills/polyfills/assert',\n            constants: 'rollup-plugin-node-polyfills/polyfills/constants',\n            _stream_duplex:\n                'rollup-plugin-node-polyfills/polyfills/readable-stream/duplex',\n            _stream_passthrough:\n                'rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough',\n            _stream_readable:\n                'rollup-plugin-node-polyfills/polyfills/readable-stream/readable',\n            _stream_writable:\n                'rollup-plugin-node-polyfills/polyfills/readable-stream/writable',\n            _stream_transform:\n                'rollup-plugin-node-polyfills/polyfills/readable-stream/transform',\n            timers: 'rollup-plugin-node-polyfills/polyfills/timers',\n            console: 'rollup-plugin-node-polyfills/polyfills/console',\n            vm: 'rollup-plugin-node-polyfills/polyfills/vm',\n            zlib: 'rollup-plugin-node-polyfills/polyfills/zlib',\n            tty: 'rollup-plugin-node-polyfills/polyfills/tty',\n            domain: 'rollup-plugin-node-polyfills/polyfills/domain',\n            buffer: 'rollup-plugin-node-polyfills/polyfills/buffer-es6',\n            process: 'rollup-plugin-node-polyfills/polyfills/process-es6'\n        }\n    },\n    optimizeDeps: {\n        esbuildOptions: {\n            // Node.js global to browser globalThis\n            define: {\n                global: 'globalThis'\n            },\n            // Enable esbuild polyfill plugins\n            plugins: [\n                NodeGlobalsPolyfillPlugin({\n                    process: true,\n                    buffer: true\n                }),\n                NodeModulesPolyfillPlugin()\n            ]\n        }\n    },\n    build: {\n        rollupOptions: {\n            plugins: [\n                // Enable rollup polyfills plugin\n                // used during production bundling\n                // @ts-ignore\n                rollupNodePolyFill(),\n            ]\n        }\n    }\n})\n```\n\n```text\nbuffer\n```\n\n```text\nprocess\n```\n\n```text\nconfig.vite.ts\n```\n\n```text\nnpm install -D buffer\n```\n\n```js\nimport { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'\n\nexport default defineConfig({\n...\n optimizeDeps: {\n    esbuildOptions: {\n      // Node.js global to browser globalThis\n      define: {\n        global: 'globalThis'\n      },\n      // Enable esbuild polyfill plugins\n      plugins: [\n        NodeGlobalsPolyfillPlugin({\n          process: true,\n          buffer: true\n        })\n      ]\n    },\n  },\n...\n})\n```\n\n```text\nnpm install rollup-plugin-node-polyfills\n```\n\n```js\n// vite.config.ts\nresolve: {\n    alias: {\n  ...\n      buffer: 'rollup-plugin-node-polyfills/polyfills/buffer-es6',\n      process: 'rollup-plugin-node-polyfills/polyfills/process-es6'\n    }\n  },\n```\n\n========================================\n\nComments:\n- can you show where the \"inject()\" came from? I want to apply this solution but I don't know what the inject() is\n- it seems `inject` comes from `const inject = require('@rollup&#47;plugin-inject')`\n- if only I saw this earlier, thanks a lot sir. I am just wondering why it not ``` [inject({ Buffer: ['Buffer', 'buffer'] })], ``` is it because they are case insensitive?\n- I have that. Didn't work for me.\n- I edited my answer, adding the buffer alias is what made it work for me (although that's a React project, it shouldn't change anything)\n- Adding this solved my issue but then created a new error in a React default import : `RollupError: node_modules&#47;rc-util&#47;es&#47;Children&#47;toArray.js (1:7): \"default\" is not exported by \"node_modules&#47;react&#47;index.js\",`\n- You can also try `include: ['node_modules&#47;**&#47;*.js']`","metadata":{"transformedAt":"2026-08-18T18:33:46.402Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":354,"estimatedTokens":2641}}132{"id":"stack-70999468","source":"stackoverflow","questionId":70999468,"title":"Asp.net 4.8 MVC + Vite + Svelte + HMR?","tags":["asp.net-mvc","svelte","vite"],"text":"Title: Asp.net 4.8 MVC + Vite + Svelte + HMR?\nTags: asp.net-mvc, svelte, vite\nSource: Stack Overflow\n\nQuestion:\nI have a legacy application built in ASP.NET 4.8 MVC.\nI would like to start building some client side features in Svelte - having svelte components rendering inside razor views. This I have working. I can render a svelte component anywhere in the razor page.\nHowever vite has some problem (im guessing with HMR?), and it keeps refreshing the razor page (https://localhost:44300/somefeature) every few seconds.\n\n**Environment**\n\nasp.net 4.8 mvc loads to https://localhost:44300/\n\nvite is loading on http://localhost:3000/\n\nHere is what i have so far. I ran npm init vite@latest -> selected svelte + svelte TS\n\n**vite.config.js**\n\n\r\n\r\n\n```\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n svelte({\n compilerOptions: {\n customElement: true,\n }\n })\n ],\n build:{\n // generate manifest.json in outDir\n manifest: true,\n rollupOptions: {\n // overwrite default .html entry\n input: '/src/main.ts'\n }\n }\n})\n```\n\n\r\n\r\n\r\n\nThen i followed the instructions here https://vitejs.dev/guide/backend-integration.html and added this to the razor page:\n\n```\n@Html.Raw(\"\")\n\n```\n\n(Note - had to use Html.Raw because it wouldnt let me escape the @ correctly - even with @@)\n\nAt this point it is rendering my Svelte component perfectly.\n\nThe issue however is that vite is now reloading my page every 2 seconds or so - im guessing because HMR is no longer working correctly as the console just says: [vite] connecting...\n\nCan anyone point me in a direction either to get HMR working whilst using another Backend server? For some reason it works in asp.net core, but not so in ASP.NET 4.8. Any observations to help?\n\nThanks in advance!\n\n========================================\n\nTop Answer:\nTHANK YOU!!!! This is exactly what I was looking for to include my react code in my old Asp.Net 4.8 site with hot module reload!\n\nFor other's the thing I had to include in my cshtml to make the react stuff load properly was:\n\n```\n\n import RefreshRuntime from \"http://localhost:9999/@@react-refresh\"\n RefreshRuntime.injectIntoGlobalHook(window)\n window.$RefreshReg$ = () => {}\n window.$RefreshSig$ = () => (type) => type\n window.__vite_plugin_react_preamble_installed__ = true\n \n```\n\nIf you don't include this you get an error saying '@vitejs/plugin-react can't detect preamble'.\n\nI am hosting the development site in IIS locally so to serve up the local files, I just created a /src folder off of the root or my application pointing to the src in my react directory and it worked beautifullly!!\n\n========================================\n\nCode:\n```html\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    svelte({\n      compilerOptions: {\n        customElement: true,\n      }\n    })\n  ],\n  build:{\n    // generate manifest.json in outDir\n    manifest: true,\n    rollupOptions: {\n      // overwrite default .html entry\n      input: '/src/main.ts'\n    }\n  }\n})\n```\n\n```text\n@Html.Raw(\"<script type='module' src='http://localhost:3000/@vite/client'></script>\")\n<script type=\"module\" src=\"http://localhost:3000/src/main.ts\"></script>\n```\n\n```text\nexport default defineConfig({\n  plugins: [\n    svelte()\n  ],\n  build:{\n    // generate manifest.json in outDir\n    manifest: true,\n    rollupOptions: {\n      // overwrite default .html entry\n      input: 'Scripts/svelte/app.js',\n    },\n    outDir: 'Scripts/svelte/dist'\n  },\n  server: {\n    proxy:{\n      '*' : {\n        target: 'http://localhost:26688',\n        changeOrigin: true\n      }\n    },\n    hmr: {\n      protocol: 'ws'\n    }\n  }\n})\n```\n\n```text\n<script type=\"module\">\n        import RefreshRuntime from \"http://localhost:9999/@@react-refresh\"\n        RefreshRuntime.injectIntoGlobalHook(window)\n        window.$RefreshReg$ = () => {}\n        window.$RefreshSig$ = () => (type) => type\n        window.__vite_plugin_react_preamble_installed__ = true\n </script>\n```\n\n========================================\n\nComments:\n- It's working perfectly in the development, however, I could not resolve 'assets' folder for the production (if published as asp.net application)\n- What did you resolve svg issues in development environment?","metadata":{"transformedAt":"2026-08-18T18:33:46.402Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":163,"estimatedTokens":1096}}133{"id":"stack-69824229","source":"stackoverflow","questionId":69824229,"title":"Vite - \"Source map points to missing source files\"","tags":["reactjs","vite"],"text":"Title: Vite - \"Source map points to missing source files\"\nTags: reactjs, vite\nSource: Stack Overflow\n\nQuestion:\nAll of a sudden I'm getting this error for practically all modules installed.\n\nSourcemap for \"C:/.../node_modules/.vite/react.js\" points to missing source files\nSourcemap for \"C:/.../node_modules/.vite/axios.js\" points to missing source files\nSourcemap for \"C:/.../node_modules/.vite/react-dom.js\" points to missing source files\nSourcemap for \"C:/.../node_modules/.vite//react_jsx-dev-runtime.js\" points to missing source files\n\npackage.json:\n\n```\n{\n \"name\": \"ic-logistic\",\n \"version\": \"0.0.0\",\n \"proxy\": \"http://localhost:8080/\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"serve\": \"vite preview\"\n },\n \"dependencies\": {\n \"axios\": \"^0.24.0\",\n \"dotenv\": \"^10.0.0\",\n \"mapbox-gl\": \"^2.5.0\",\n \"react\": \"^17.0.0\",\n \"react-dom\": \"^17.0.0\",\n \"react-map-gl\": \"^6.1.17\",\n \"react-redux\": \"^7.2.5\",\n \"react-router-dom\": \"^5.3.0\",\n \"redux\": \"^4.1.1\",\n \"redux-devtools-extension\": \"^2.13.9\",\n \"sass\": \"^1.42.1\"\n },\n \"devDependencies\": {\n \"@vitejs/plugin-react\": \"^1.0.0\",\n \"vite\": \"^2.6.0\"\n }\n}\n```\n\n========================================\n\nTop Answer:\nExtending @nefaris answer, what solved it for me was replacing v1.0.x with 1.0.8 :\n\n```\nnpm install @vitejs/plugin-react@1.0.8 --save-dev\n```\n\n========================================\n\nCode:\n```text\n{\n  \"name\": \"ic-logistic\",\n  \"version\": \"0.0.0\",\n    \"proxy\": \"http://localhost:8080/\",\n  \"private\": true,\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"serve\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"axios\": \"^0.24.0\",\n    \"dotenv\": \"^10.0.0\",\n    \"mapbox-gl\": \"^2.5.0\",\n    \"react\": \"^17.0.0\",\n    \"react-dom\": \"^17.0.0\",\n    \"react-map-gl\": \"^6.1.17\",\n    \"react-redux\": \"^7.2.5\",\n    \"react-router-dom\": \"^5.3.0\",\n    \"redux\": \"^4.1.1\",\n    \"redux-devtools-extension\": \"^2.13.9\",\n    \"sass\": \"^1.42.1\"\n  },\n  \"devDependencies\": {\n    \"@vitejs/plugin-react\": \"^1.0.0\",\n    \"vite\": \"^2.6.0\"\n  }\n}\n```\n\n```text\n@vitejs/plugin-react\n```\n\n```text\n\"^1.0.0\"\n```\n\n```text\n\"1.0.5\"\n```\n\n```text\nnpm install @vitejs/plugin-react@1.0.8 --save-dev\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.402Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":103,"estimatedTokens":538}}134{"id":"stack-71636873","source":"stackoverflow","questionId":71636873,"title":"Vite and React: stop using \"react-refresh\"","tags":["reactjs","npm","vite"],"text":"Title: Vite and React: stop using \"react-refresh\"\nTags: reactjs, npm, vite\nSource: Stack Overflow\n\nQuestion:\nWhenever I run npm start in my project I get the following message:\n\n```\n[@vitejs/plugin-react] You should stop using \"react-refresh\" since this plugin conflicts with it.\n```\n\nVite seems to work fine regardless, but I was wondering if / how I should disable \"react refresh\"\n\n========================================\n\nCode:\n```text\n[@vitejs/plugin-react] You should stop using \"react-refresh\" since this plugin conflicts with it.\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    react({\n      babel: {\n        plugins: ['babel-plugin-macros', ... (plugins here)],\n      },\n    }),\n  ],\n});\n```\n\n```text\nvite.config.js\n```\n\n```text\n@vitejs/plugin-react\n```\n\n```text\nreactRefresh()\n```\n\n```text\n@vitejs/plugin-react-refresh\n```\n\n```text\n@vitejs/plugin-react\n```\n\n========================================\n\nComments:\n- Removing react-refresh from the list of plugins fixed it for me. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:46.402Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":60,"estimatedTokens":279}}135{"id":"stack-76983697","source":"stackoverflow","questionId":76983697,"title":"Why does my Vue/Vite/Typescript application require me to separate \"import\" and \"import type\" by default?","tags":["javascript","typescript","vuejs3","vite"],"text":"Title: Why does my Vue/Vite/Typescript application require me to separate \"import\" and \"import type\" by default?\nTags: javascript, typescript, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI've scaffolded a front-end application using create-vue. It includes TypeScript.\n\nThe following throws an error:\n\n```\nimport axios, { AxiosInstance, AxiosResponse } from \"axios\"\n```\n\nUncaught SyntaxError: The requested module '/node_modules/.vite/deps/axios.js?v=a7006e8b' does not provide an export named 'AxiosInstance'\n\nWhereas the following works:\n\n```\nimport axios from \"axios\"\nimport type { AxiosInstance, AxiosResponse } from \"axios\"\n```\n\nThis is my first time using `create-vue`, but in other projects in the past I have never had to separate my type imports.\n\nThe documentation for `verbatimModuleSyntax` states:\n\nBy default, TypeScript does something called *import elision*. TypeScript detects that you’re only using an import for types and drops the import entirely.\n\nTo be safe, I tried setting `\"verbatimModuleSyntax\": \"false\"` to my `tsconfig.json`, but this did not fix the issue. It's also flagged in VSCode with the following error:\n\nDo not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting.\n\nHow can I get the failing line (importing both classes and types/interfaces in one line) to work as it always has for me in the past?\n\n**EDIT:** Note that I'm using axios only as an example. This happens with any type, regardless of whether it's a node module or an interface I've written.\n\n========================================\n\nTop Answer:\nYou need\n\n```\nimport axios, { type AxiosInstance, type AxiosResponse } from \"axios\"\n```\n\nThe difference of \"type\" imports is they get stripped\n\nIf they wouldn't get stripped, you would try to import an actual `AxiosInstance` variable from `axios`, resulting in a runtime error *if so-named variable was not exported from there*.\n\n`verbatimModuleSyntax` disables the stripping of unused non-\"type\" imports, causing the error\n\n```\nimport { a } from './a'\nimport { type b } from './b'\nimport type { c } from './c'\nimport { d, /* type */ e, type f } from './d'\nimport { /* unused */u, /* type */ w, type y } from './u'\na(d)\n\n// JS without verbatimModuleSyntax\n// import { a } from './a';\n// import { d } from './d';\n// a(d);\n\n// JS with verbatimModuleSyntax\n// import { a } from './a';\n// import {} from './b';\n// import { d, e } from './d';\n// import { u, w } from './u';\n// a(d);\n```\n\n========================================\n\nCode:\n```text\nimport axios, { AxiosInstance, AxiosResponse } from \"axios\"\n```\n\n```text\nimport axios from \"axios\"\nimport type { AxiosInstance, AxiosResponse } from \"axios\"\n```\n\n```text\ncreate-vue\n```\n\n```text\nverbatimModuleSyntax\n```\n\n```text\n\"verbatimModuleSyntax\": \"false\"\n```\n\n```text\ntsconfig.json\n```\n\n```text\n\"verbatimModuleSyntax\": \"false\"\n```\n\n```text\n\"verbatimModuleSyntax\": false\n```\n\n```text\nimport axios, { type AxiosInstance, type AxiosResponse } from \"axios\"\n```\n\n```text\nimport { a } from './a'\nimport { type b } from './b'\nimport type { c } from './c'\nimport { d, /* type */ e, type f } from './d'\nimport { /* unused */u, /* type */ w, type y } from './u'\na<b, c, e, d, f, w>(d)\n\n\n// JS without verbatimModuleSyntax\n// import { a } from './a';\n// import { d } from './d';\n// a(d);\n\n// JS with verbatimModuleSyntax\n// import { a } from './a';\n// import {} from './b';\n// import { d, e } from './d';\n// import { u, w } from './u';\n// a(d);\n```\n\n```text\nAxiosInstance\n```\n\n```text\naxios\n```\n\n```text\nverbatimModuleSyntax\n```\n\n========================================\n\nComments:\n- Thank you. Like I mentioned though, I have never had to use a `type` import at all. Is it a typescript version thing? I'm trying to figure out why all my other projects work fine but this one does not. I've always imported interfaces and classes this way.\n- because with `verbatimModuleSyntax` they stopped being trimmed @Santi\n- Then how do I turn it off...?\n- @Santi you go to tsconfig.json and turn it off\n- As I said in the original post, I did that, and it didn't work\n- @Santi Then I'd recommend that one ESLint autofix that autoplaces `type` in imports for you, see typescript-eslint.io/rules/consistent-type-imports","metadata":{"transformedAt":"2026-08-18T18:33:46.402Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":155,"estimatedTokens":1072}}136{"id":"stack-71082688","source":"stackoverflow","questionId":71082688,"title":"Vite: Replace env vars at build time","tags":["javascript","vue.js","vite"],"text":"Title: Vite: Replace env vars at build time\nTags: javascript, vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI am using Vue + Vite + TS and I am building a few libraries that I would like to build and import somewhere else.\n\nThe point is that I set some environment variables using the dotenv, hence I can use things like import.meta.env.MY_VARIABLE.\n\nBut they are being availed during the run time of the place I run them, hence the env files need to be placed in the component that requires those libs.\n\nI would like to know if there is way so they get replaced in the build time.\n\n========================================\n\nTop Answer:\nUnfortunately, the accepted answer is wrong. First, it will fail on build-time because the date is not correctly formed.\n\nThis depends on how you build the app. In all cases, you should expose the env var like this (docs on vite and .env)\n\n```\nVITE_SENTRY_RELEASE_VERSION=something\n```\n\nLet's say you have the build script in the package.json like this\n\n```\nscripts: {\n \"build\": \"NODE_ENV=production svelte-kit sync && vite build\",\n}\n```\n\nand you use pnpm. The command would be\n\n```\nVITE_SENTRY_RELEASE_VERSION=something pnpm build\n```\n\nNow, in the code, you would reference it like this:\n\n```\nexport const sentryRelease = import.meta.env.VITE_SENTRY_RELEASE_VERSION;\n```\n\nThe value will be replaced with the correct env variable value.\n\n========================================\n\nCode:\n```text\nlet commonConfig =\n{\n\n  plugins: [vue()],\n\n  resolve: {\n    alias: {\n      \"@\": fileURLToPath(new URL(\"./src\", import.meta.url))     \n    },\n  },\n  build: {\n    rollupOptions: {\n      input: {\n        main: resolve(__dirname, 'index.html'),\n        nested: resolve(__dirname, 'auth_redirect.html')\n      }\n    }\n  }\n}\n\nexport default defineConfig(({ command, mode, ssrBuild }) => {\n  \n  if (command === 'serve')\n  {\n//\n    return commonConfig;\n\n  } \n  else \n  {\n    commonConfig.define = {\n      \"BUILD_TIMESTAMP\": new Date().toISOString()\n      \n    };\n\n    // command === 'build'\n    return commonConfig;\n  }\n})\n```\n\n```text\nconst buildNum = \"BUILD_TIMESTAMP\";//You will get right val in this\n```\n\n```text\nVITE_SENTRY_RELEASE_VERSION=something\n```\n\n```json\nscripts: {\n  \"build\": \"NODE_ENV=production svelte-kit sync && vite build\",\n}\n```\n\n```text\nVITE_SENTRY_RELEASE_VERSION=something pnpm build\n```\n\n```text\nexport const sentryRelease = import.meta.env.VITE_SENTRY_RELEASE_VERSION;\n```\n\n========================================\n\nComments:\n- +1: For anyone else reading this: note that any environment variables passed along in this way (i.e., without being loaded from an .env* file) need to be prefixed with `VITE_`, or else they'll be ignored (as mentioned in the docs linked above).","metadata":{"transformedAt":"2026-08-18T18:33:46.402Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":117,"estimatedTokens":680}}137{"id":"stack-76517758","source":"stackoverflow","questionId":76517758,"title":"How do I completely disable chunking in Vite and Rollup?","tags":["laravel","vite","rollup"],"text":"Title: How do I completely disable chunking in Vite and Rollup?\nTags: laravel, vite, rollup\nSource: Stack Overflow\n\nQuestion:\nI'm back in Laravel development after being out of practice since 2019ish. I'm more accustomed to Mix than to Vite but I like the @vite helpers in Blade. For this app I have to provide a Firebase service worker in the root public directory, accessible at https://example.com/firebase-messaging-sw.js. This is what my vite.config.js looks like:\n\n```\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\nexport default defineConfig({\n plugins: [\n laravel({\n valetTls: 'whatever.test',\n input: [\n 'resources/css/app.css',\n 'resources/js/app.js',\n 'resources/js/firebase-messaging-sw.js'\n ],\n refresh: true,\n })\n ]\n});\n```\n\nThe problem is that firebase-messaging-sw.js uses import statements to grab Firebase functions from node_modules, which also end up in the compiled public-facing file as minified gibberish. Since a service worker isn't referenced as a module, \"import\" statements fail. ALL I want is for that file to be compiled into one single JavaScript file with no imports in the final product. This is trivially easy with Mix:\n\n```\nconst mix = require('laravel-mix');\nmix.js('./build/firebase-messaging-sw.js', './public/firebase-messaging-sw.js');\n```\n\nBut I'm already in too deep to switch to Mix at this point. What can I do to my configuration to make Vite output a single clean file, preferably without a hashed filename? I see this, but it assumes a much deeper knowledge of Rollup than I have, and I'm honestly not sure where the lines between Laravel/Vite/Rollup are drawn in this case. This seems like a very simple question but I can't find a recent answer.\n\nPer this answer, I tried changing my vite.config.js to this:\n\n```\nexport default defineConfig({\n\n build: {\n rollupOptions: {\n output: {\n manualChunks: {}\n },\n }\n },\n\n plugins: [\n laravel({\n valetTls: 'whatever.test',\n input: [\n 'resources/css/app.css',\n 'resources/js/app.js',\n 'resources/js/firebase-messaging-sw.js'\n ],\n refresh: true,\n })\n ],\n\n});\n```\n\nBut this had no effect on Vite's output.\n\n========================================\n\nTop Answer:\nYou can use vite's Javascript API, to run separate builds for each entry/input file.\n\nhttps://vitejs.dev/guide/api-javascript.html#build\n\n========================================\n\nCode:\n```js\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\nexport default defineConfig({\n    plugins: [\n        laravel({\n            valetTls: 'whatever.test',\n            input: [\n                'resources/css/app.css',\n                'resources/js/app.js',\n                'resources/js/firebase-messaging-sw.js'\n            ],\n            refresh: true,\n        })\n    ]\n});\n```\n\n```js\nconst mix = require('laravel-mix');\nmix.js('./build/firebase-messaging-sw.js', './public/firebase-messaging-sw.js');\n```\n\n```js\nexport default defineConfig({\n\n    build: {\n        rollupOptions: {\n          output: {\n            manualChunks: {}\n          },\n        }\n    },\n\n    plugins: [\n        laravel({\n            valetTls: 'whatever.test',\n            input: [\n                'resources/css/app.css',\n                'resources/js/app.js',\n                'resources/js/firebase-messaging-sw.js'\n            ],\n            refresh: true,\n        })\n    ],\n\n});\n```\n\n```text\nimport { defineConfig } from 'vite';\n\nconst input = process.argv[4]?.split('=')?.[1];\nif (input) {\n    console.log('SINGLE INPUT PROVIDED: ' + input);\n}\n\nexport default defineConfig(() => {\n    return {\n        build: {\n            emptyOutDir: false,\n            rollupOptions: {\n                input: input || ['main.js', 'test.js'],\n                output: {\n                    [input ? 'inlineDynamicImports' : 'dummy']: true,\n                    entryFileNames: input || ['main.js', 'test.js']\n                }\n            },\n        },\n    };\n});\n```\n\n```text\nprintf \"test.js main.js\" | xargs -d ' ' -P0 -I% npx vite build -- --input=%\nSINGLE INPUT PROVIDED: main.js\nSINGLE INPUT PROVIDED: test.js\nvite v4.3.9 building for production...\nvite v4.3.9 building for production...\n✓ 5 modules transformed.\n✓ 3 modules transformed.\ndist/test.js  0.95 kB │ gzip: 0.59 kB\ndist/assets/javascript-8dac5379.svg  1.00 kB │ gzip: 0.60 kB\ndist/assets/vite-4a748afd.svg        1.50 kB │ gzip: 0.77 kB\ndist/assets/main-48a8825f.css        1.24 kB │ gzip: 0.65 kB\ndist/main.js                         0.75 kB │ gzip: 0.43 kB\n✓ built in 67ms\n✓ built in 68ms\n```\n\n```text\n--\n```\n\n```text\nemptyOutDir: false\n```\n\n========================================\n\nComments:\n- Thanks a ton, this gets me most of the way there. Using any of those suggestions causes this error: `Invalid value for option \"output.inlineDynamicImports\" - multiple inputs are not supported when \"output.inlineDynamicImports\" is true.`. Commenting out my other input files results in a correctly-compiled serviceworker js file that's exactly what I needed. How do I configure Vite/rollup to apply that change ONLY to resources/js/firebase-messaging-sw.js?\n- @politicoder that's a very interesting question, indeed! let me investigate... meanwhile you could accept my question (the checkbox) so i'll be motivated to dig deeper. I'll setup a new Vite project with multiple inputs...\n- @politicoder what code causes your service-worker.js to split? dynamic imports like `await import()` ? could you import statically?\n- Sure, in my userland code, the only import statements in firebase-messaging-sw.js are static ones at the top to import functions from Firebase's npm package. it's all `\"import {x} from 'firebase&#47;x'` type stuff, although I suppose dynamic import()s could be happening within Firebase's node modules.\n- @politicoder found the solution, editing the answer\n- Beautiful, thank you very much. I went with the two config file solution. All I would add for future readers is if you do this, also remember to put `build: {emptyOutDir: false}` in both config files so they don't delete each other's outputs. Thanks again!\n- @politicoder will add `build: {emptyOutDir: false}`\n- @politicoder my multi config command: stackoverflow.com/questions/76272727/&hellip;\n- It's a nice way to handle multi-build, but how do you handle having multiples manifests file at the end? Would it be possible to have Vite write in a single one or merge them ?","metadata":{"transformedAt":"2026-08-18T18:33:46.402Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":184,"estimatedTokens":1595}}138{"id":"stack-71040714","source":"stackoverflow","questionId":71040714,"title":"Write to disk option for Vite","tags":["javascript","webpack","bundle","single-page-application","vite"],"text":"Title: Write to disk option for Vite\nTags: javascript, webpack, bundle, single-page-application, vite\nSource: Stack Overflow\n\nQuestion:\nrecently I have started working with vite on a couple of small projects and found it very interesting, however got a blocker once tried to work on ExpressJS + Svelte coupled project.\n\nI usually use Express as BFF (Backend For Frontend) when it comes to working on rather more serious projects since it allows me to go for HTTPOnly cookies as well as proxy gateway for the frontend. However for development (specially when it comes to oauth2) it is hard to develop the spa separated form the server so what I usually do with webpack is activating the WriteToDisk option for devserver which then allows me to have my development build in the dist folder.\n\nExample with webpack will be something like the webpack config below for the frontend:\n\n```\nmodule.exports = {\n devServer: {\n devMiddleware: {\n writeToDisk: true,\n },\n },\n //...\n }\n```\n\nand then on the server basically rendering the dist as static folder:\n\n```\napp.get(\n \"*\",\n (req, res, next) => {\n if (req.session.isAuth) return next();\n else return res.redirect(staticURL);\n },\n (req, res) => {\n return res.sendFile(staticProxyPage());\n }\n );\n```\n\n### My problem\n\nI can not find in vite's documentation any APIs to do something like this, does anyone have any experience with such cases?\n\nif it is possible with the help of plugins, can you please provide references to the plugin or dev logs of it?\n\nMany Thanks :)\n\n========================================\n\nTop Answer:\nThere is a very simple way to get this behavior. Just set up a watch script to do a regular Vite build using something like npm-watch package.\n\n`npm install npm-watch`\n\n```\n\"watch\": {\n \"run_mybuild\": {\n \"patterns\": [\n \"src\"\n ],\n extensions: \"js,jsx\"\n }\n},\n\"scripts\": {\n \"dev\": \"npm-watch run_mybuild\",\n \"run_mybuild\": \"vite build\"\n}\n```\n\n`npm run dev`\n\nYou now have a Vite build that generates files on a watch. No it's not incremental. There is a rollup incremental build (Vite uses rollup to build when it generates files) but even though I got it \"working\" it just generates everything still.\n\nI think if you just use a different vite config and put vite in watch mode by passing:\n\n```\nbuild: {\n watch: true,\n sourcemap: true\n}\n```\n\nin your vite.config.js that probably works too. If you need to copy assets for your build they will get removed though.\n\n========================================\n\nCode:\n```js\nmodule.exports = {\n        devServer: {\n            devMiddleware: {\n                writeToDisk: true,\n            },\n        },\n        //...\n    }\n```\n\n```js\napp.get(\n      \"*\",\n      (req, res, next) => {\n        if (req.session.isAuth) return next();\n        else return res.redirect(staticURL);\n      },\n      (req, res) => {\n        return res.sendFile(staticProxyPage());\n      }\n    );\n```\n\n```text\n// https://vitejs.dev/guide/api-plugin.html#universal-hooks=\nimport {type Plugin} from 'vite';\nimport fs from 'fs/promises';\nimport path from 'path';\n\nconst writeToDisk: () => Plugin = () => ({\n    name: 'write-to-disk',\n    apply: 'serve',\n    configResolved: async config => {\n        config.logger.info('Writing contents of public folder to disk', {timestamp: true});\n        await fs.cp(config.publicDir, config.build.outDir, {recursive: true});\n    },\n    handleHotUpdate: async ({file, server: {config, ws}, read}) => {\n        if (path.dirname(file).startsWith(config.publicDir)) {\n            const destPath = path.join(config.build.outDir, path.relative(config.publicDir, file));\n            config.logger.info(`Writing contents of ${file} to disk`, {timestamp: true});\n            await fs.access(path.dirname(destPath)).catch(() => fs.mkdir(path.dirname(destPath), {recursive: true}));\n            await fs.writeFile(destPath, await read());\n        }\n    },\n});\n```\n\n```text\npublicDir\n```\n\n```text\noutDir\n```\n\n```text\npublic\n```\n\n```text\nfs.cp\n```\n\n```js\n\"watch\": {\n  \"run_mybuild\": {\n    \"patterns\": [\n      \"src\"\n    ],\n    extensions: \"js,jsx\"\n  }\n},\n\"scripts\": {\n  \"dev\": \"npm-watch run_mybuild\",\n  \"run_mybuild\": \"vite build\"\n}\n```\n\n```js\nbuild: {\n  watch: true,\n  sourcemap: true\n}\n```\n\n```text\nnpm install npm-watch\n```\n\n```text\nnpm run dev\n```\n\n========================================\n\nComments:\n- Thank you so much, I will test it out during the weekend and will get back and upon validating of its functionality I will approve the answer.\n- Unfortunately this doesn't look like a replacement for writeToDisk, as it only handles files in the `public&#47;` folder, not in the `src&#47;` folder","metadata":{"transformedAt":"2026-08-18T18:33:46.402Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":184,"estimatedTokens":1150}}139{"id":"stack-69364069","source":"stackoverflow","questionId":69364069,"title":"How do I exclude files from svelte-kit build?","tags":["sveltekit","vite"],"text":"Title: How do I exclude files from svelte-kit build?\nTags: sveltekit, vite\nSource: Stack Overflow\n\nQuestion:\nIf I run `npm run build` with SvelteKit it seems to include all files from the `src` folder. Is it possible to exclude a certain file type (eg. `*test.js`)?\n\n### Example\n\nSelect demo app with `npm init svelte@next my-app`\n\nAdd the following code to `src/routes/todos/foo.test.js`\n\n```\ndescribe('foo', () => {\n it('temp', () => {\n expect(true).toBe(false)\n })\n})\n```\n\n`npm run build`\n\n`npm run preview`\n\nResult: `describe is not defined`\n\n### Workaround\n\nMove tests outside of `src`\n\n========================================\n\nCode:\n```js\ndescribe('foo', () => {\n  it('temp', () => {\n    expect(true).toBe(false)\n  })\n})\n```\n\n```text\nnpm run build\n```\n\n```text\nsrc\n```\n\n```text\n*test.js\n```\n\n```text\nnpm init svelte@next my-app\n```\n\n```text\nsrc/routes/todos/foo.test.js\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm run preview\n```\n\n```text\ndescribe is not defined\n```\n\n```text\nsrc\n```\n\n```js\n// sveltekit.config.js\n⋮\nconst config = {\n  kit: {\n    ⋮\n    routes: filepath => {\n      return ![\n        // exclude *test.js files\n        /\\.test\\.js$/,\n\n        // original default config\n        /(?:(?:^_|\\/_)|(?:^\\.|\\/\\.)(?!well-known))/,\n      ].some(regex => regex.test(filepath))\n    },\n  },\n}\n```\n\n```text\nroutes/\n```\n\n```text\n+\n```\n\n```text\n+page.svelte\n```\n\n```text\n+page.js\n```\n\n```text\n+page.server.js\n```\n\n```text\n+error.js\n```\n\n```text\n+layout.svelte\n```\n\n```text\n+layout.js\n```\n\n```text\n+layout.server.js\n```\n\n```text\n+server.js\n```\n\n```text\nroutes/\n```\n\n```text\nroutes\n```\n\n```text\nsrc/routes\n```\n\n```text\ntrue\n```\n\n```text\nroutes\n```\n\n```text\n*.test.js\n```\n\n========================================\n\nComments:\n- `routes` option is not longer available under config. I can't figure out what's the current way of doing this. @tony19 please bless me with your knowledge\n- Thanks for coming back @tony19. My use case is more geared towards removing specific routes in build only. It goes like: I have an admin page for CRUD to my database. I use that during `npm run dev` I don't want to include that in the build. I had to do a major compromise of using adapter-static. Now I manually remove that page after build. Plus I had to give up on a lot of dynamicness just for this problem.\n- @Mooze I see. I wonder if there are simpler workarounds that don't require a special adapter. You could rename that file (e.g., from `routes&#47;admin&#47;dev&#47;page.svelte` to `routes&#47;admin&#47;dev&#47;+page.svelte`) in your `npm` script for `dev`.\n- That makes sense. It would do the job. I can keep it as `+page.svelte` and before build I can rename it to `page.svelte` inside the npm script like `mv +page.svelte page.svelte && vite build` @tony19 you're the man!","metadata":{"transformedAt":"2026-08-18T18:33:46.403Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":27,"totalLines":168,"estimatedTokens":694}}140{"id":"stack-76220594","source":"stackoverflow","questionId":76220594,"title":"plugin:vite:import-analysis Failed to resolve entry for package \"xxx\". The package may have incorrect main/module/exports specified in package.json","tags":["typescript","npm","vuejs3","bundle","vite"],"text":"Title: plugin:vite:import-analysis Failed to resolve entry for package \"xxx\". The package may have incorrect main/module/exports specified in package.json\nTags: typescript, npm, vuejs3, bundle, vite\nSource: Stack Overflow\n\nQuestion:\nmy npm package here has a wrong build (using vite), when I install it in a project, it shows the error in the title.\n\nthe whole error info:\n\n```\n] Failed to resolve entry for package \"vue3-drag-resize-rotate\". The package may have incorrect main/module/exports specified in its package.json. [plugin vite:dep-scan]\n\n node_modules/.pnpm/esbuild@0.17.18/node_modules/esbuild/lib/main.js:1360:21:\n 1360 │ let result = await callback({\n ╵ ^\n\n at packageEntryFailure (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:23384:11)\n at resolvePackageEntry (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:23381:5)\n at tryNodeResolve (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:23115:20)\n at Context.resolveId (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:22876:28)\n at Object.resolveId (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:42811:46)\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\n at async resolve (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:43109:26)\n at async file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:43286:34\n at async requestCallbacks.on-resolve (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:1360:22)\n at async handleRequest (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:723:13)\n\n This error came from the \"onResolve\" callback registered here:\n\n node_modules/.pnpm/esbuild@0.17.18/node_modules/esbuild/lib/main.js:1279:20:\n 1279 │ let promise = setup({\n ╵ ^\n\n at setup (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:43276:19)\n at handlePlugins (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:1279:21)\n at buildOrContextImpl (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:968:5)\n at Object.buildOrContext (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:776:5)\n at D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:2172:68\n at new Promise ()\n at Object.context (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:2172:27)\n at Object.context (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:2012:58)\n at prepareEsbuildScanner (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:43061:26)\n\n The plugin \"vite:dep-scan\" was triggered by this import\n\n script:D:/program/own/test-xmov-component/src/components/HelloWorld.vue?id=0:8:7:\n 8 │ import 'vue3-drag-resize-rotate'\n ╵ ~~~~~~~~~~~~~~~~~~~~~~~~~\n\n at failureErrorWithLog (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:1636:15)\n at D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:1048:25\n at runOnEndCallbacks (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:1471:45)\n at buildResponseToResult (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:1046:7)\n at D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:1058:9\n at new Promise ()\n at requestCallbacks.on-end (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:1057:54)\n at handleRequest (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:723:19)\n at handleIncomingPacket (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:745:7)\n at Socket.readFromStdout (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:673:7)\nFailed to resolve entry for package \"vue3-drag-resize-rotate\". The package may have incorrect main/module/exports specified in its package.json.\n下午11:46:05 [vite] Internal server error: Failed to resolve entry for package \"vue3-drag-resize-rotate\". The package may have incorrect main/module/exports specified in its package.json.\n Plugin: vite:import-analysis\n File: D:/program/own/test-xmov-component/src/components/HelloWorld.vue\n at packageEntryFailure (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:23384:11)\n at resolvePackageEntry (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:23381:5)\n at tryNodeResolve (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:23115:20)\n at Context.resolveId (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:22876:28)\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\n at async Object.resolveId (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:42811:32)\n at async TransformContext.resolve (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:42539:23)\n at async normalizeUrl (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:40502:34)\n at async file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:40653:47\n at async Promise.all (index 1)\n```\n\nand further, I have troble bundling the project with typescript inference. I want to it can export the type of the instance and other types, but I failed.\n\nthanks a lot for helping me.\n\nI set the vite.config.ts file:\n\n```\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [vue()],\n build: {\n outDir: 'lib',\n lib: {\n entry: 'packages/index.ts',\n name: 'vue3-drag-resize-rotate',\n fileName: 'vue3-drag-resize-rotate',\n formats: ['es', 'cjs', 'umd'],\n },\n rollupOptions: {\n external: ['vue'],\n input: 'packages/index.ts',\n output: {\n globals: {\n vue: 'Vue',\n },\n },\n },\n },\n})\n```\n\nhere is the package.json:\n\n```\n{\n \"name\": \"vue3-drag-resize-rotate\",\n \"version\": \"0.0.8\",\n \"type\": \"module\",\n \"types\": \"packages/components/drr.vue.d.ts\",\n \"main\": \"lib/vue3-drag-resize-rotate.umd.js\",\n \"module\": \"lib/vue3-drag-resize-rotate.mjs\",\n \"unpkg\": \"lib/vue3-drag-resize-rotate.umd.js\",\n \"jsdelivr\": \"lib/vue3-drag-resize-rotate.umd.js\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/AvailableForTheWorld/vue3-drag-resize-rotate\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/AvailableForTheWorld/vue3-drag-resize-rotate/issues\"\n },\n \"exports\": {\n \".\": {\n \"require\": \"./lib/vue3-drag-resize-rotate.umd.js\",\n \"import\": \"./lib/vue3-drag-resize-rotate.mjs\"\n },\n \"./package.json\": \"./package.json\",\n \"./lib/*\": \"./lib/*\"\n },\n \"files\": [\n \"lib\",\n \"packages\"\n ],\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\"\n },\n \"dependencies\": {\n \"nanoid\": \"^4.0.2\",\n \"vue\": \"^3.2.47\"\n },\n \"devDependencies\": {\n \"@vitejs/plugin-vue\": \"^4.1.0\",\n \"typescript\": \"^5.0.2\",\n \"vite\": \"^4.3.2\",\n \"vue-tsc\": \"^1.4.2\"\n }\n}\n```\n\nit didn't work , I don't know why\n\n========================================\n\nCode:\n```text\n] Failed to resolve entry for package \"vue3-drag-resize-rotate\". The package may have incorrect main/module/exports specified in its package.json. [plugin vite:dep-scan]\n\n    node_modules/.pnpm/esbuild@0.17.18/node_modules/esbuild/lib/main.js:1360:21:\n      1360 │         let result = await callback({\n           ╵                      ^\n\n    at packageEntryFailure (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:23384:11)\n    at resolvePackageEntry (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:23381:5)\n    at tryNodeResolve (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:23115:20)\n    at Context.resolveId (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:22876:28)\n    at Object.resolveId (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:42811:46)\n    at processTicksAndRejections (node:internal/process/task_queues:96:5)\n    at async resolve (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:43109:26)\n    at async file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:43286:34\n    at async requestCallbacks.on-resolve (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:1360:22)\n    at async handleRequest (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:723:13)\n\n  This error came from the \"onResolve\" callback registered here:\n\n    node_modules/.pnpm/esbuild@0.17.18/node_modules/esbuild/lib/main.js:1279:20:\n      1279 │       let promise = setup({\n           ╵                     ^\n\n    at setup (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:43276:19)\n    at handlePlugins (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:1279:21)\n    at buildOrContextImpl (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:968:5)\n    at Object.buildOrContext (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:776:5)\n    at D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:2172:68\n    at new Promise (<anonymous>)\n    at Object.context (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:2172:27)\n    at Object.context (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:2012:58)\n    at prepareEsbuildScanner (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:43061:26)\n\n  The plugin \"vite:dep-scan\" was triggered by this import\n\n    script:D:/program/own/test-xmov-component/src/components/HelloWorld.vue?id=0:8:7:\n      8 │ import 'vue3-drag-resize-rotate'\n        ╵        ~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\n    at failureErrorWithLog (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:1636:15)\n    at D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:1048:25\n    at runOnEndCallbacks (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:1471:45)\n    at buildResponseToResult (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:1046:7)\n    at D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:1058:9\n    at new Promise (<anonymous>)\n    at requestCallbacks.on-end (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:1057:54)\n    at handleRequest (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:723:19)\n    at handleIncomingPacket (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:745:7)\n    at Socket.readFromStdout (D:\\program\\own\\test-xmov-component\\node_modules\\.pnpm\\esbuild@0.17.18\\node_modules\\esbuild\\lib\\main.js:673:7)\nFailed to resolve entry for package \"vue3-drag-resize-rotate\". The package may have incorrect main/module/exports specified in its package.json.\n下午11:46:05 [vite] Internal server error: Failed to resolve entry for package \"vue3-drag-resize-rotate\". The package may have incorrect main/module/exports specified in its package.json.\n  Plugin: vite:import-analysis\n  File: D:/program/own/test-xmov-component/src/components/HelloWorld.vue\n      at packageEntryFailure (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:23384:11)\n      at resolvePackageEntry (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:23381:5)\n      at tryNodeResolve (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:23115:20)\n      at Context.resolveId (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:22876:28)\n      at processTicksAndRejections (node:internal/process/task_queues:96:5)\n      at async Object.resolveId (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:42811:32)\n      at async TransformContext.resolve (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:42539:23)\n      at async normalizeUrl (file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:40502:34)\n      at async file:///D:/program/own/test-xmov-component/node_modules/.pnpm/vite@4.3.5_@types+node@20.1.2/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:40653:47\n      at async Promise.all (index 1)\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue()],\n  build: {\n    outDir: 'lib',\n    lib: {\n      entry: 'packages/index.ts',\n      name: 'vue3-drag-resize-rotate',\n      fileName: 'vue3-drag-resize-rotate',\n      formats: ['es', 'cjs', 'umd'],\n    },\n    rollupOptions: {\n      external: ['vue'],\n      input: 'packages/index.ts',\n      output: {\n        globals: {\n          vue: 'Vue',\n        },\n      },\n    },\n  },\n})\n```\n\n```json\n{\n  \"name\": \"vue3-drag-resize-rotate\",\n  \"version\": \"0.0.8\",\n  \"type\": \"module\",\n  \"types\": \"packages/components/drr.vue.d.ts\",\n  \"main\": \"lib/vue3-drag-resize-rotate.umd.js\",\n  \"module\": \"lib/vue3-drag-resize-rotate.mjs\",\n  \"unpkg\": \"lib/vue3-drag-resize-rotate.umd.js\",\n  \"jsdelivr\": \"lib/vue3-drag-resize-rotate.umd.js\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/AvailableForTheWorld/vue3-drag-resize-rotate\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/AvailableForTheWorld/vue3-drag-resize-rotate/issues\"\n  },\n  \"exports\": {\n    \".\": {\n      \"require\": \"./lib/vue3-drag-resize-rotate.umd.js\",\n      \"import\": \"./lib/vue3-drag-resize-rotate.mjs\"\n    },\n    \"./package.json\": \"./package.json\",\n    \"./lib/*\": \"./lib/*\"\n  },\n  \"files\": [\n    \"lib\",\n    \"packages\"\n  ],\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"preview\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"nanoid\": \"^4.0.2\",\n    \"vue\": \"^3.2.47\"\n  },\n  \"devDependencies\": {\n    \"@vitejs/plugin-vue\": \"^4.1.0\",\n    \"typescript\": \"^5.0.2\",\n    \"vite\": \"^4.3.2\",\n    \"vue-tsc\": \"^1.4.2\"\n  }\n}\n```\n\n```text\n\"main\": \"./dist/package-name.umd.cjs\",\n\"exports\": {\n  \".\": {\n    \"import\": \"./dist/package-name.js\",\n    \"require\": \"./dist/package-name.umd.cjs\"\n  }\n},\n```\n\n```text\n.umd.js\n```\n\n```text\n.umd.cjs\n```\n\n```text\n.cjs\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.403Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":326,"estimatedTokens":4366}}141{"id":"stack-76921210","source":"stackoverflow","questionId":76921210,"title":"Proxy is not working in Vite js project and request is not getting redirected to the proper api","tags":["javascript","reactjs","proxy","vite","mern"],"text":"Title: Proxy is not working in Vite js project and request is not getting redirected to the proper api\nTags: javascript, reactjs, proxy, vite, mern\nSource: Stack Overflow\n\nQuestion:\nI have a basic MERN stack application which I have deployed using vercel. \n\nThe frontend is at \"https://ticketify-silk.vercel.app/\". \n\nThe backend is at \"https://ticketify-api.vercel.app/\". \n\nIn the frontend code, I have used vite and also proxy to fetch data from api. Following is the code in the vite config file.\n\r\n\r\n\n```\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n server: {\n proxy: {\n '/api': {\n target: 'https://ticketify-api.vercel.app',\n changeOrigin: true,\n secure: false,\n rewrite: (path) => path.replace(/^\\/api/, '')\n }\n },\n },\n plugins: [react()],\n});\n```\n\n\r\n\r\n\r\n\nIn the backend code as well, I have defined the following code to avoid the CORS error.\n\n\r\n\r\n\n```\napp.use(\n cors({\n origin: [\"https://ticketify-silk.vercel.app\"],\n methods: [\"GET\", \"POST\", \"PUT\", \"UPDATE\"],\n credentials: true,\n allowedHeaders: [\"Content-Type\", \"Authorization\"],\n })\n);\n```\n\n\r\n\r\n\r\n\nWhen I send a request from the frontend, instead of going to \"https://ticketify-api.vercel.app/\" it is going to \"https://ticketify-silk.vercel.app/\". This is the error that I am getting ->\n\nhttps://i.sstatic.net/6fp1V.png\n\nSo basically, the proxy is not working. And everything is running fine in my local environment, where the frontend is at \"http://localhost:5173\" and backend is at \"http://localhost:8080\".\n\nCould anyone please suggest a solution? I already tried proxy api is not working in Vite + Vue 3 project when it's deployed to Vercel, but the solutions did not work for me. Can the issue be solved by any changes to the vercel.json file? I am not sure about it because I am deploying using vercel for the first time.\n\n========================================\n\nTop Answer:\nI had the same problem today, basically, you proxy config are only valid on dev server , when you build/preview your app this proxy are no longer available to your app, it's explicitly defined on vite's docs (*\"Configure custom proxy rules **for the dev server.**\"*).\n\nSo what you want to do is to ensure that this \"proxy\" is also present on your vercel environment, I could achieve this by adding a vercel.json file under your project's root with the following content:\n\n```\n{\n \"rewrites\": [\n {\n \"source\": \"/api/(.*)\",\n \"destination\": \"https://your-api.domain/$1\"\n },\n {\n \"source\": \"/(.*)\",\n \"destination\": \"/\"\n }\n ]\n}\n```\n\nYou can read more on vercel's docs.\n\nThis worked for me, now any requests to `my-app.domain/api` are being rewritten to `my-api.domain/`. What I'm testing now is how to make this \"https://your-api.domain\" dynamic by passing an env variable to `vercel.json`, I'll let you know of any updates on this.\n\n========================================\n\nCode:\n```js\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  server: {\n    proxy: {\n        '/api': {\n          target: 'https://ticketify-api.vercel.app',\n          changeOrigin: true,\n          secure: false,\n          rewrite: (path) => path.replace(/^\\/api/, '')\n        }\n      },\n  },\n  plugins: [react()],\n});\n```\n\n```js\napp.use(\n  cors({\n    origin: [\"https://ticketify-silk.vercel.app\"],\n    methods: [\"GET\", \"POST\", \"PUT\", \"UPDATE\"],\n    credentials: true,\n    allowedHeaders: [\"Content-Type\", \"Authorization\"],\n  })\n);\n```\n\n```bash\nserver: {\n    proxy: {\n      '/api': 'your target url'\n    }\n  },\n```\n\n```text\n{\n    \"rewrites\": [\n        {\n            \"source\": \"/api/(.*)\",\n            \"destination\": \"https://your-api.domain/$1\"\n        },\n        {\n            \"source\": \"/(.*)\",\n            \"destination\": \"/\"\n        }\n    ]\n}\n```\n\n```text\nmy-app.domain/api\n```\n\n```text\nmy-api.domain/\n```\n\n```text\nvercel.json\n```\n\n```text\n{\n  \"rewrites\": [\n      {\n          \"source\": \"/api/:path(.*)\",\n          \"destination\": \"https://your-backendUrl/api/:path\"\n      },\n      {\n          \"source\": \"/(.*)\",\n          \"destination\": \"/\"\n      }\n  ]\n}\n```\n\n```text\n{\n    \"rewrites\": [\n        {\n            \"source\": \"/api/(.*)\",\n            \"destination\": \"https://your-backend-url/$1\"\n        }\n    ]\n}\n```\n\n```text\n/api/path\n```\n\n```text\nhttps://your-backend-url/path\n```\n\n```text\nservices:\n  backend:\n    \"backend related stuff\"\n  frontend:\n    \"frontend related stuff\"\n```\n\n```text\nserver: {\n  proxy: {\n    '/api': {\n      target: 'http://backend:{port}',\n      changeOrigin: true,\n      secure: false,\n  },\n},\n```\n\n```js\nproxy: {\n  // This is the path on your webserver that will receive the requests.\n  // Note this prefix is kept when calling the remote server:\n  //    /api/some/path?q=1 will be proxied to https://your-remote-server/api/some/path?q=1\n  //                                                                    ^^^^\n  '/api': {\n\n    // The target of the proxy. The client never sees this; it just calls its server\n    // as normal and the server takes the requests, sends it to the target, receives\n    // the response and sends it back to the client.\n    target: 'https://ticketify-api.vercel.app',\n\n    // This tells the server not to preserve the Origin header as sent by the client\n    changeOrigin: true,\n\n    // Sometimes you don’t want to keep the path prefix in the request you do\n    // to the remote server. With this configuration,\n    //    /api/some/path?q=1 will be proxied to https://your-remote-server/some/path?q=1\n    rewrite: (path) => path.replace(/^\\/api/, '')\n  }\n}\n```\n\n```none\nClient JS  -----1----> ticketify-silk -----2----> ticketify-api\n(browser)  <----4-----                <----3-----\n```\n\n```text\nrewrite\n```\n\n```text\nticketify-silk\n```\n\n```text\nticketify-api\n```\n\n```text\nticketify-api\n```\n\n```text\n/api\n```\n\n========================================\n\nComments:\n- `Can the issue be solved by any changes to the vercel.json file?` isn't that exactly what the answer you linked to states? Which you said you \"tried\"? Perhaps you *did something wrong™* when you tried?\n- @JaromandaX Yeah, and I also said that none of the solutions worked! Also, there are no upvotes on that solution, so I don't think it worked for anyone else either, or no one saw it.\n- Fair enough, can you show what you did?\n- The reason it works only on a dev server is that it can be very dangerous to have this in production. CORS are a security measure that exist for a reason.\n- One thing to remember with the Vite proxy implementation is that if you're trying to map something like localhost:5173/api to localhost:3000/api then you'll phrase it as: '/api': 'localhost:3000' The default for this mapping is that the path part of the URL is appended to the other domain you specify. So you don't need to put \"/api\" onto the destination if that's what you need.\n- Be aware that unless you know what you’re doing this can open a security breach.","metadata":{"transformedAt":"2026-08-18T18:33:46.403Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":273,"estimatedTokens":1743}}142{"id":"stack-75685623","source":"stackoverflow","questionId":75685623,"title":"Property 'glob' does not exist on type 'ImportMeta'.ts","tags":["typescript","laravel","laravel-blade","vite"],"text":"Title: Property 'glob' does not exist on type 'ImportMeta'.ts\nTags: typescript, laravel, laravel-blade, vite\nSource: Stack Overflow\n\nQuestion:\n### Context\n\nI am new to Vite and with very little experience in Laravel, I am trying to use Vite with Laravel for asset bundling.\n\nI'm following instructions from Laravel official documentation : https://laravel.com/docs/9.x/vite#blade-processing-static-assets\n\nSince I'm using TypeScript, So my entry point file name is : `resources/ts/app.ts`\n\nWhen I try to write\n\n```\nimport.meta.glob([ \n '../resources/img/..',\n]);\n```\n\nI am able to get `Property 'glob' does not exist on type 'ImportMeta'.ts(2339)`. I understand once files are build, I have to use\n``\nto be able to see file, But since I'm skipping to update the `app.ts` file.\n\nI am able to see `logo.png` as\n`I am trying to bundle static assets ( images ), just like how I did with css/js.\n\n========================================\n\nTop Answer:\nI'm using Vitepress with TypeScript and just fixed this issue by adding `\"vite\": \"*\"` to my `devDependencies`\n\nEdit: I also added `\"vue\": \"*\"` in the end (other similar issues)\n\n========================================\n\nCode:\n```text\nimport.meta.glob([ \n  '../resources/img/..',\n]);\n```\n\n```text\nresources/ts/app.ts\n```\n\n```text\nProperty 'glob' does not exist on type 'ImportMeta'.ts(2339)\n```\n\n```text\n<img src=\"{{ Vite::asset('resources/images/logo.png') }}\">\n```\n\n```text\napp.ts\n```\n\n```text\nlogo.png\n```\n\n```text\n<imgsrc=\"https://sensitiveUrl.com/logo.a766f7e6.js\"\n```\n\n```text\ntsconfig.json\n```\n\n```text\n\"vite\": \"*\"\n```\n\n```text\ndevDependencies\n```\n\n```text\n\"vue\": \"*\"\n```\n\n========================================\n\nComments:\n- I also needed to add `\".&#47;node_modules\"` to the typeRoots configuration for this to work\n- so how do you configure vite.config.js correctly?\n- I don't know what to say except that this doesn't work.\n- You are not supposed to use `\"*\"` for any dependency, ever. This means you will install the latest version, no matter what, even it's a major, breaking change. And if you go long enough, hunting down what version you do want will be tricky because you don't know what version worked.","metadata":{"transformedAt":"2026-08-18T18:33:46.403Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":91,"estimatedTokens":542}}143{"id":"stack-68251598","source":"stackoverflow","questionId":68251598,"title":"Vue, vite: GET http://localhost:3000/@vite/client net::ERR_ABORTED 404 (Not Found)","tags":["vue.js","http-status-code-404","vite"],"text":"Title: Vue, vite: GET http://localhost:3000/@vite/client net::ERR_ABORTED 404 (Not Found)\nTags: vue.js, http-status-code-404, vite\nSource: Stack Overflow\n\nQuestion:\nI am using Vue and vite to practice the workflow of the web application with fetching API, following this tutorial. At the end of the `yarn dev` command, I got the error. I've tried:\n\n- Directly clone the project and run the same command, still got the same error.\n\n- Search for any issue and solution on Github, but no luck.\n\nHow could I resolve this issue? Or I missed anything? Thanks.\n\n========================================\n\nTop Answer:\nHad the same issue but only in Chrome. The `/@vite/client/` url wasn't loading.\n\nMy issue was that Chrome has cached the url with the `/` in the end however it shouldn't be there. The only way to fix it was to open the Network tab in the dev tools, set a checkmark for \"Disable cache\", reload the page.\n\n========================================\n\nCode:\n```text\nyarn dev\n```\n\n```text\nNode v14.17.5\n```\n\n```text\nnpm v6.14.14\n```\n\n```text\nyarn v1.22.5\n```\n\n```text\n/@vite/client/\n```\n\n```text\n/\n```\n\n========================================\n\nComments:\n- I have a similar issue with my Vite project. Did you manage to resolve the issue? Figure out what the cause is?\n- @GuyPassy, sorry, it's been a while. The answer didn't resolve my issue as well.\n- Hi I am experiencing the same error.. Did you solve this issue by any chance?\n- Same issue but only in Chrome (after it's update). The `&#47;@vite&#47;client&#47;` url just doesn't load","metadata":{"transformedAt":"2026-08-18T18:33:46.403Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":54,"estimatedTokens":386}}144{"id":"stack-77235874","source":"stackoverflow","questionId":77235874,"title":"Vite + Chrome Extension Manifest v3 - \"Cannot use import statement outside a module\" for inpage scripts","tags":["typescript","vite","chrome-extension-manifest-v3"],"text":"Title: Vite + Chrome Extension Manifest v3 - \"Cannot use import statement outside a module\" for inpage scripts\nTags: typescript, vite, chrome-extension-manifest-v3\nSource: Stack Overflow\n\nQuestion:\nI created an extension based off https://github.com/Jonghakseo/chrome-extension-boilerplate-react-vite project.\nIn manifest I set `background` type to `module`\n\n```\nbackground: {\n service_worker: \"background.js\",\n type: \"module\",\n },\n```\n\nand in background service I dynamically create inpage content-scripts like so\n\n```\nawait chrome.scripting.registerContentScripts([\n {\n id: currInpageId,\n matches: [\"file://*/*\", \"http://*/*\", \"https://*/*\"],\n js: [`inpage-${inpageType}.js`],\n runAt: \"document_start\",\n allFrames: true,\n world: \"MAIN\",\n },\n ]);\n```\n\ninpage files are passed as individual inputs to vite.config\n\n```\ninput: {\n ...inpageTypes.reduce(\n (acc, inpageType) => ({\n ...acc,\n [`inpage-${inpageType}`]: resolve(\n inpageDir,\n `inpage-${inpageType}.ts`\n ),\n }),\n {}\n ),\n },\n```\n\nbut when I run the ext I get an error\n\nUncaught SyntaxError: Cannot use import statement outside a module\n\nHow can I resolve it?\n\nThanks!\n\n========================================\n\nCode:\n```text\nbackground: {\n    service_worker: \"background.js\",\n    type: \"module\",\n  },\n```\n\n```text\nawait chrome.scripting.registerContentScripts([\n      {\n        id: currInpageId,\n        matches: [\"file://*/*\", \"http://*/*\", \"https://*/*\"],\n        js: [`inpage-${inpageType}.js`],\n        runAt: \"document_start\",\n        allFrames: true,\n        world: \"MAIN\",\n      },\n    ]);\n```\n\n```text\ninput: {\n          ...inpageTypes.reduce(\n            (acc, inpageType) => ({\n              ...acc,\n              [`inpage-${inpageType}`]: resolve(\n                inpageDir,\n                `inpage-${inpageType}.ts`\n              ),\n            }),\n            {}\n          ),\n        },\n```\n\n```text\nbackground\n```\n\n```text\nmodule\n```\n\n```text\nbuild: {\n  emptyOutDir: false,\n  ...\n  rollupOptions: {\n    output: {\n      entryFileNames: \"[name].js\",\n      inlineDynamicImports: true,\n    }\n  }\n}\n```\n\n========================================\n\nComments:\n- Assuming the error is in the web page and not in the service worker, you need to configure the type of output produced by vite through some option (I don't know which though).\n- it is indeed returned from the webpage, since the error originate in content script and not the background service worker. wdym @wOxxOm? what should I configure? the only thing I thought about was making the imports inline, but it's unavailable when you have multiple inputs as I do.\n- It's probably something about the runtime chunk, which you shouldn't use, i.e. every file should be entirely self-sufficient and not anything.\n- Yeah I suspected as much, but I'm afraid it will break HMR and all the things I get from vite :(\n- HMR doesn't work with content scripts in the page anyway.\n- I don't understand, can you explain further? How are you creating 3 separate vite config files? How are they configured, how are you building?\n- This answer is terribly vague.","metadata":{"transformedAt":"2026-08-18T18:33:46.403Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":124,"estimatedTokens":767}}145{"id":"stack-69607736","source":"stackoverflow","questionId":69607736,"title":"Vite React app: esbuild error in Docker container","tags":["reactjs","docker","vite"],"text":"Title: Vite React app: esbuild error in Docker container\nTags: reactjs, docker, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get to grips with both vite and docker so I apologise if I've made stupid mistakes.\n\nI'm running into an issue with esbuild inside docker. I'm trying to get a dev setup going, so I want to mount my code in my containers so that changes should be reflected in real time.\n\nPreviously I used Dockerfiles which copied `/frontend` and `/backend` into their respective containers and that worked, I had my `web` and `api` containers running and happily talking to each other. However, it meant it didn't pick up any code changes so it wasn't suitable for development.\n\nSo I've switched to volume mounts in the hope that I can get my dockerized apps to hot reload, but hit this error instead.\n\nHere's my `docker-compose.yml`\n\n```\nversion: \"3.8\"\nservices:\n api:\n image: node:16-slim\n volumes:\n - ./backend:/app\n - ./shared:/shared\n working_dir: /app\n command: yarn start:dev\n ports:\n - \"3001:3001\"\n web:\n image: node:16-slim\n volumes:\n - ./frontend:/app\n - ./shared:/shared\n working_dir: /app\n command: yarn dev\n ports:\n - \"3000:3000\"\n```\n\nhere's my vite.config.js\n\n```\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n server: {\n host: \"0.0.0.0\",\n port: 3000,\n fs: {\n strict: false,\n },\n },\n plugins: [react()],\n});\n```\n\nhttps://i.sstatic.net/jCPhu.png\n\nSo this is the error that I'm trying to fix:\n\n```\nweb_1 | yarn run v1.22.15\nweb_1 | $ vite\nweb_1 | failed to load config from /app/vite.config.js\nweb_1 | error when starting dev server:\nweb_1 | Error: The package \"esbuild-linux-64\" could not be found, and is needed by esbuild.\nweb_1 |\nweb_1 | If you are installing esbuild with npm, make sure that you don't specify the\nweb_1 | \"--no-optional\" flag. The \"optionalDependencies\" package.json feature is used\nweb_1 | by esbuild to install the correct binary executable for your current platform.\nweb_1 | at generateBinPath (/app/node_modules/esbuild/lib/main.js:1643:15)\nweb_1 | at esbuildCommandAndArgs (/app/node_modules/esbuild/lib/main.js:1699:11)\nweb_1 | at ensureServiceIsRunning (/app/node_modules/esbuild/lib/main.js:1856:25)\nweb_1 | at Object.build (/app/node_modules/esbuild/lib/main.js:1749:26)\nweb_1 | at bundleConfigFile (/app/node_modules/vite/dist/node/chunks/dep-713b45e1.js:68592:34)\nweb_1 | at loadConfigFromFile (/app/node_modules/vite/dist/node/chunks/dep-713b45e1.js:68569:35)\nweb_1 | at resolveConfig (/app/node_modules/vite/dist/node/chunks/dep-713b45e1.js:68119:34)\nweb_1 | at createServer (/app/node_modules/vite/dist/node/chunks/dep-713b45e1.js:66633:26)\nweb_1 | at CAC. (/app/node_modules/vite/dist/node/cli.js:687:30)\nweb_1 | error Command failed with exit code 1.\nweb_1 | info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.\nhomepage_web_1 exited with code 1\n```\n\nI've spent most of the day reading various similar SO questions and github threads but nothing I found specifically addresses this, at least in a way I understand. I'd be really grateful if anyone could either point out where I've gone wrong, or point me at an example of a dockerized vite/react app with good dev and prod setups. Thanks!\n\n========================================\n\nTop Answer:\nI got this error when I ran Vite on an older version of Node Js. When Node and Npm were updated - the error was gone\n\n========================================\n\nCode:\n```yaml\nversion: \"3.8\"\nservices:\n  api:\n    image: node:16-slim\n    volumes:\n      - ./backend:/app\n      - ./shared:/shared\n    working_dir: /app\n    command: yarn start:dev\n    ports:\n      - \"3001:3001\"\n  web:\n    image: node:16-slim\n    volumes:\n      - ./frontend:/app\n      - ./shared:/shared\n    working_dir: /app\n    command: yarn dev\n    ports:\n      - \"3000:3000\"\n```\n\n```js\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  server: {\n    host: \"0.0.0.0\",\n    port: 3000,\n    fs: {\n      strict: false,\n    },\n  },\n  plugins: [react()],\n});\n```\n\n```text\nweb_1  | yarn run v1.22.15\nweb_1  | $ vite\nweb_1  | failed to load config from /app/vite.config.js\nweb_1  | error when starting dev server:\nweb_1  | Error: The package \"esbuild-linux-64\" could not be found, and is needed by esbuild.\nweb_1  |\nweb_1  | If you are installing esbuild with npm, make sure that you don't specify the\nweb_1  | \"--no-optional\" flag. The \"optionalDependencies\" package.json feature is used\nweb_1  | by esbuild to install the correct binary executable for your current platform.\nweb_1  |     at generateBinPath (/app/node_modules/esbuild/lib/main.js:1643:15)\nweb_1  |     at esbuildCommandAndArgs (/app/node_modules/esbuild/lib/main.js:1699:11)\nweb_1  |     at ensureServiceIsRunning (/app/node_modules/esbuild/lib/main.js:1856:25)\nweb_1  |     at Object.build (/app/node_modules/esbuild/lib/main.js:1749:26)\nweb_1  |     at bundleConfigFile (/app/node_modules/vite/dist/node/chunks/dep-713b45e1.js:68592:34)\nweb_1  |     at loadConfigFromFile (/app/node_modules/vite/dist/node/chunks/dep-713b45e1.js:68569:35)\nweb_1  |     at resolveConfig (/app/node_modules/vite/dist/node/chunks/dep-713b45e1.js:68119:34)\nweb_1  |     at createServer (/app/node_modules/vite/dist/node/chunks/dep-713b45e1.js:66633:26)\nweb_1  |     at CAC.<anonymous> (/app/node_modules/vite/dist/node/cli.js:687:30)\nweb_1  | error Command failed with exit code 1.\nweb_1  | info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.\nhomepage_web_1 exited with code 1\n```\n\n```text\n/frontend\n```\n\n```text\n/backend\n```\n\n```text\nweb\n```\n\n```text\napi\n```\n\n```text\ndocker-compose.yml\n```\n\n```text\ndocker-compose.yml\n```\n\n```text\ncommand: sh -c \"npm rebuild esbuild && yarn dev\"\n```\n\n```json\n\"optionalDependencies\": {\n    \"@esbuild/linux-x64\": \"^0.20.1\"\n  }\n```\n\n```text\n@esbuild/linux-64\n```\n\n```text\nThe package \"@esbuild/linux-x64\" could not be found, and is needed by esbuild\n```\n\n```text\nnpm i @esbuild/linux-64\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- Thanks for providing this answer!","metadata":{"transformedAt":"2026-08-18T18:33:46.403Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":213,"estimatedTokens":1552}}146{"id":"stack-75049311","source":"stackoverflow","questionId":75049311,"title":"Nuxt 3 SSR - No console logs of server API in dev environment","tags":["server-side-rendering","vite","pnpm","nuxt3.js"],"text":"Title: Nuxt 3 SSR - No console logs of server API in dev environment\nTags: server-side-rendering, vite, pnpm, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nWhen you do a simple console log in server API side, it doesn't show up when you build it using `pnpm run dev`.\n\nhttps://i.sstatic.net/IRCFE.png\n\nBut if you build it using `pnpm run build` and run the `index.mjs`, the console log will show up.\n\nCode:\n\n```\nexport default defineEventHandler(async (event) => {\n console.log('HAHAHAHAHA');\n\n return 'LOGIN!';\n});\n```\n\nHere is my `npx nuxi info`:\n\n```\n------------------------------\n- Operating System: `Linux`\n- Node Version: `v18.12.1`\n- Nuxt Version: `3.0.0`\n- Nitro Version: `1.0.0`\n- Package Manager: `pnpm@7.22.0`\n- Builder: `vite`\n- User Config: `app`, `runtimeConfig`, `modules`, `ssr`, `vite`, `typescript`, `css`, `build`\n- Runtime Modules: `@app/ui@1.0.0-alpha`, `nuxt-icon@0.1.8`, `@pinia/nuxt@0.4.6`\n- Build Modules: `-`\n------------------------------\n```\n\n========================================\n\nCode:\n```text\nexport default defineEventHandler(async (event) => {\n  console.log('HAHAHAHAHA');\n\n  return 'LOGIN!';\n});\n```\n\n```text\n------------------------------\n- Operating System: `Linux`\n- Node Version:     `v18.12.1`\n- Nuxt Version:     `3.0.0`\n- Nitro Version:    `1.0.0`\n- Package Manager:  `pnpm@7.22.0`\n- Builder:          `vite`\n- User Config:      `app`, `runtimeConfig`, `modules`, `ssr`, `vite`, `typescript`, `css`, `build`\n- Runtime Modules:  `@app/ui@1.0.0-alpha`, `nuxt-icon@0.1.8`, `@pinia/nuxt@0.4.6`\n- Build Modules:    `-`\n------------------------------\n```\n\n```text\npnpm run dev\n```\n\n```text\npnpm run build\n```\n\n```text\nindex.mjs\n```\n\n```text\nnpx nuxi info\n```\n\n```text\nconsole.log()\n```\n\n```text\npnpm run dev\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.403Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":85,"estimatedTokens":437}}147{"id":"stack-74491876","source":"stackoverflow","questionId":74491876,"title":"Vite-proxy ECONNREFUSED with node v17+","tags":["vue.js","vite"],"text":"Title: Vite-proxy ECONNREFUSED with node v17+\nTags: vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI am using Node v18.12.1 and vite v3.0.4. Below is my proxy code to connect to a Node.js REST API from the Vue.js vite dev server:\n\n```\nproxy: {\n \"/api\": {\n target: \"http://localhost:3000\",\n changeOrigin: true,\n }\n}\n```\n\nAfter updating my node version from v16 I now get this error from vite-proxy:\n\n```\n[vite] http proxy error:\nError: connect ECONNREFUSED ::1:3000\nat TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16) (x3)\n```\n\nI have heard that sine v17, Node favours ipv6 for localhost. How do I fix this?\n\n========================================\n\nCode:\n```text\nproxy: {\n  \"/api\": {\n    target: \"http://localhost:3000\",\n    changeOrigin: true,\n  }\n}\n```\n\n```text\n[vite] http proxy error:\nError: connect ECONNREFUSED ::1:3000\nat TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16) (x3)\n```\n\n```text\n::1\n```\n\n```text\nhttp://127.0.0.1:3000\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.403Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":51,"estimatedTokens":242}}148{"id":"stack-76340554","source":"stackoverflow","questionId":76340554,"title":"How to mock dependency of dependency with Vitest","tags":["mocking","dependencies","vite","vitest"],"text":"Title: How to mock dependency of dependency with Vitest\nTags: mocking, dependencies, vite, vitest\nSource: Stack Overflow\n\nQuestion:\nI have a test setup with vite and have a dependency of a dependency that needs some mocked options in order to run properly, I currently have it in a `__mocks__/nestedDependency.js` file.\nAlso in my `test/setup.ts` file I have a `vi.mock('nestedDependency')`, however it does not seem to catch it in any way\n\nI previously had the setup with `jest` and this exact setup worked. Only thing I have migrated from that setup is instead of using `jest.requireActual('nestedDependency')` I am now using `vi.importActual('nestedDependency')` for my mocking purposes.\n\n========================================\n\nCode:\n```text\n__mocks__/nestedDependency.js\n```\n\n```text\ntest/setup.ts\n```\n\n```text\nvi.mock('nestedDependency')\n```\n\n```text\njest\n```\n\n```text\njest.requireActual('nestedDependency')\n```\n\n```text\nvi.importActual('nestedDependency')\n```\n\n```js\n// the source code only uses import\nconst unbundledState = resolve(__dirname, '../state/src/index');\n\nexport default defineConfig({\n  test: {\n    environment: 'jsdom',\n    setupFiles: ['./tests/test.setup'],\n    globalSetup: ['./tests/test.global'],\n    alias: {\n      '@cai/state': unbundledState,\n    },\n  },\n});\n```\n\n```text\npanel\n```\n\n```text\nstate\n```\n\n```text\ncommon\n```\n\n```text\nstate\n```\n\n```text\ncommon\n```\n\n```text\ncommon\n```\n\n```text\nstate\n```\n\n```text\npanel\n```\n\n```text\nstate\n```\n\n```text\nrequire\n```\n\n```text\nvitest\n```\n\n```text\nalias\n```\n\n```text\nvitest\n```\n\n```text\nimport\n```\n\n```text\nrequire\n```\n\n```text\nimport\n```\n\n========================================\n\nComments:\n- I am running into the same issue. I realize that my nested dependency is bundled to use `require` and `vitest` won't mock a `require` call. Trying to sort it now.","metadata":{"transformedAt":"2026-08-18T18:33:46.403Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":121,"estimatedTokens":457}}149{"id":"stack-73693685","source":"stackoverflow","questionId":73693685,"title":"Why am I getting vite:command not found error?","tags":["vite"],"text":"Title: Why am I getting vite:command not found error?\nTags: vite\nSource: Stack Overflow\n\nQuestion:\nI have installed vite in my vue.js app. I start the app by typing npm run dev in the main project directory. In the package.json this is defined as:\n\n```\n\"dev\": \"vite\"\n```\n\nbut if I try do run this command (or eg. vite build) 'manually' from main directory, I get an error:\n\n```\nbash: vite: command not found\n```\n\nI also figured out that when I set a new script:\n\n```\n\"build\": \"vite build\"\n```\n\nI can run this command also, although, again, running it manually will result in error as above.\n\nThis seems quite illogical to me. Can anybody explain how is it possible?\n\n========================================\n\nCode:\n```text\n\"dev\": \"vite\"\n```\n\n```text\nbash: vite: command not found\n```\n\n```text\n\"build\": \"vite build\"\n```\n\n```text\nnpm install -g\n```\n\n```text\nnode_modules/.bin\n```\n\n```text\nnpm run\n```\n\n```text\n./node_modules/.bin/vite\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.403Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":57,"estimatedTokens":234}}150{"id":"stack-78567007","source":"stackoverflow","questionId":78567007,"title":"How do I solve the error \"Failed to resolve import \"src/lib/utils\" from ... Does the file exist?\"","tags":["html","reactjs","user-interface","tailwind-css","vite"],"text":"Title: How do I solve the error \"Failed to resolve import \"src/lib/utils\" from ... Does the file exist?\"\nTags: html, reactjs, user-interface, tailwind-css, vite\nSource: Stack Overflow\n\nQuestion:\nI am a beginner in react and am trying to this tutorial (https://www.youtube.com/watch?v=_W3R2VwRyF4) on youtube. I am trying to test out the button component I am building, but I keep getting an error message:\n\n\"[plugin:vite:import-analysis] Failed to resolve import \"src/lib/utils\" from \"src/components/ui/button.tsx\". Does the file exist?\"\n\nFor reference, I am using vite + react + tailwind.\n\nI have attached a screen shot with the rest of the error message.\n\nThis is the code button.tsx:\n\n```\nimport * as React from \"react\"\nimport { Slot } from \"@radix-ui/react-slot\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\n\nimport { cn } from \"src/lib/utils\"\n```\n\nThis is the code in utils.ts:\n\n```\nimport { type ClassValue, clsx } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs))\n}\n```\n\nI am importing the button component from @/components/ui/button to SignupForm.tsx with this command:\n\n```\nimport { Button } from \"@/components/ui/button\"\n```\n\nI deleted \"@\", but when I remove it from the path \"@/components/ui/button\", I get the error: \"Cannot find module 'components/ui/button' or its corresponding type declarations.\"\n\nI am assuming that it is a syntax OR a path error I am overlooking. Does anyone have any thoughts? Thank you.\n\n========================================\n\nTop Answer:\nWell what i did is to change the @ instances to src\n\nvite.config.ts\n\n```\nimport path from \"path\";\nimport react from \"@vitejs/plugin-react\";\nimport { defineConfig } from \"vite\";\n\nexport default defineConfig({\n plugins: [react()],\n resolve: {\n alias: {\n src: path.resolve(__dirname, \"./src\"),\n },\n },\n});\n```\n\ntsconfig.app.json\n\n```\n\"baseUrl\": \".\",\n\"paths\": {\n \"src/*\": [\"./src/*\"]\n},\n```\n\n========================================\n\nCode:\n```text\nimport * as React from \"react\"\nimport { Slot } from \"@radix-ui/react-slot\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\n\nimport { cn } from \"src/lib/utils\"\n```\n\n```text\nimport { type ClassValue, clsx } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n```\n\n```text\nimport { Button } from \"@/components/ui/button\"\n```\n\n```json\n{\n  \"compilerOptions\": {\n    // ...\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@/*\": [\n        \"./src/*\"\n      ]\n    }\n    // ...\n  }\n}\n```\n\n```js\nimport path from \"path\"\nimport react from \"@vitejs/plugin-react\"\nimport { defineConfig } from \"vite\"\n\nexport default defineConfig({\n  plugins: [react()],\n  resolve: {\n    alias: {\n      \"@\": path.resolve(__dirname, \"./src\"),\n    },\n  },\n})\n```\n\n```bash\nnpm i -D @types/node\n```\n\n```bash\nnpx shadcn-ui init\nnpx shadcn-ui add button\n```\n\n```text\n@/\n```\n\n```text\ntsconfig.json\n```\n\n```text\nvite.config.ts\n```\n\n```text\n@types/node\n```\n\n```text\npath\n```\n\n```text\n@/path/to/whatever\n```\n\n```text\n./src/path/to/whatever\n```\n\n```text\nimport path from \"path\";\nimport react from \"@vitejs/plugin-react\";\nimport { defineConfig } from \"vite\";\n\nexport default defineConfig({\n  plugins: [react()],\n  resolve: {\n    alias: {\n      src: path.resolve(__dirname, \"./src\"),\n    },\n  },\n});\n```\n\n```text\n\"baseUrl\": \".\",\n\"paths\": {\n  \"src/*\": [\"./src/*\"]\n},\n```\n\n```text\nnpx shadcn@canary init\n```\n\n========================================\n\nComments:\n- Try `\".&#47;src&#47;lib&#47;utils\"` (with the `.&#47;` at the start).\n- I tried doing this and still got the same error.\n- Can you a repo or Sandbox?\n- Here is the link to my github repo: github.com/tmhourani/snapgram\n- Move `utils.ts` file to `lib` and remove `@` directory or run the commands at the end of the answer again\n- I moved utils.ts file to lib and removed the @ directory, and now I am getting the error in localhost:5173: \"[plugin:vite:import-analysis] Failed to resolve import \"src/lib/utils\" from \"src/components/ui/button.tsx\". Does the file exist?\"\n- I went into my SignupForm.tsx file and changed the import statement from \"@/components/ui/button\" to \"src/components/ui/button\", and I am getting this error now: \"[plugin:vite:import-analysis] Failed to resolve import \"src/components/ui/button\" from \"src/_auth/forms/SignupForm.tsx\". Does the file exist?\"\n- See this stackoverflow.com/a/77249092/18079514\n- I did everything and resolved the issue, but my button component is not showing up on my UI.\n- Create a new question explaining what's going on\n- Here is the link to my new question: stackoverflow.com/questions/78572199/&hellip;\n- Exact this answer worked for me!","metadata":{"transformedAt":"2026-08-18T18:33:46.403Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":207,"estimatedTokens":1181}}151{"id":"stack-72016669","source":"stackoverflow","questionId":72016669,"title":"How to config vite HMR port in Nuxt3 config?","tags":["nuxt.js","vite"],"text":"Title: How to config vite HMR port in Nuxt3 config?\nTags: nuxt.js, vite\nSource: Stack Overflow\n\nQuestion:\nI'm using Nuxt3 within a Docker compose setup where port 8001 is the accessible port for the node container running Nuxt3 channeled via an nginx reverse proxy.\n\nMy nuxt.config.ts looks like this:\n\n```\nimport { defineNuxtConfig } from 'nuxt'\n\n// https://v3.nuxtjs.org/api/configuration/nuxt.config\nexport default defineNuxtConfig({\n vite: {\n server: {\n hmr: {\n clientPort: 8001,\n }\n }\n }\n})\n```\n\nSomehow it seems the clientPort setting for the HMR of vite is not picked up by Nuxt3. The page is constantly reloading in the dev setup.\n\nAny idea whether I've misconfigured this or this is not yet possible in Nuxt3?\n\nIn a similar setup with Vue this setting in the vite.config.js is working properly?\n\n========================================\n\nTop Answer:\nyou need to add this port beside the main port like in your docker-compose.yaml\n\n```\nports:\n - \"3000:3000\"\n - \"24678:24678\"\n```\n\nalso be sure the vite config is like\n\n```\n//nuxt.config.{js,ts}\nexport default defineNuxtConfig({\n vite: {\n server: {\n hmr: {\n protocol: \"ws\",\n host: \"0.0.0.0\",\n },\n },\n },\n});\n```\n\n========================================\n\nCode:\n```js\nimport { defineNuxtConfig } from 'nuxt'\n\n// https://v3.nuxtjs.org/api/configuration/nuxt.config\nexport default defineNuxtConfig({\n    vite: {\n        server: {\n            hmr: {\n                clientPort: 8001,\n            }\n        }\n    }\n})\n```\n\n```text\n# Your Nuxt 3 service\n\n  ports:\n    - \"24678:24678\" # or in your case: - \"8001:8001\"\n```\n\n```text\nexport default {\n  server: {\n    hmr: {\n      protocol: 'ws',\n      host: '0.0.0.0',\n    }\n  }\n}\n```\n\n```text\n:24678\n```\n\n```text\nvite.config.js\n```\n\n```text\nports:\n  - \"3000:3000\"\n  - \"24678:24678\"\n```\n\n```text\n//nuxt.config.{js,ts}\nexport default defineNuxtConfig({\n  vite: {\n    server: {\n      hmr: {\n        protocol: \"ws\",\n        host: \"0.0.0.0\",\n      },\n    },\n  },\n});\n```\n\n```bash\nexport default defineNuxtConfig({\n  devtools: { enabled: true },\n  vite: {\n    server: {\n      hmr: {\n        protocol: 'ws',\n        host: '0.0.0.0',  \n      }\n    }\n  }});\n```\n\n```bash\nports:\n      - 3000:3000\n      - 24678:24678\n```\n\n```bash\nexport default defineNuxtConfig({\n  devtools: { enabled: true },\ndevServer: {\n    host: \"0.0.0.0\",\n    port: 8000, // you can replace this port with any port\n  }});\n```\n\n```bash\nports:\n      - 8000:8000\n```\n\n```text\nhooks: {\n    'vite:extendConfig': (config) => {\n      if (typeof config.server!.hmr === 'object') {\n        config.server!.hmr.protocol = 'wss';\n      }\n    },\n  },\n```\n\n```text\nnuxt.config\n```\n\n```text\nvite: {\n    server: {\n      watch: {\n        usePolling: true\n      }\n    }\n  }\n```\n\n```text\nCMD npm run dev -- --host 0.0.0.0\n```\n\n```text\n24678\n```\n\n```text\ndocker-compose\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nDockerfile\n```\n\n========================================\n\nComments:\n- Thank you! Adding a vite.config.js with these settings did not work, but opening port 24678 to the node container did work!\n- Man, opening port 24678 was absolute nugget! Was looking for that whole day. Thank you!\n- With Nuxt 3.2.3 seems to not working.. I get GET localhost:3010/_nuxt net::ERR_EMPTY_RESPONSE error every time. Where actualy the _nuxt folder should be? I can't find it.\n- Working like a charm. I used in nuxt 3.x configuration. Be aware that nuxt documentation says no all vite configuration can be used within nuxt 3.x Maybe it will change in the future version. I don`t know","metadata":{"transformedAt":"2026-08-18T18:33:46.403Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":205,"estimatedTokens":879}}152{"id":"stack-69039093","source":"stackoverflow","questionId":69039093,"title":"How to change antd theme in Vite config?","tags":["reactjs","typescript","antd","vite"],"text":"Title: How to change antd theme in Vite config?\nTags: reactjs, typescript, antd, vite\nSource: Stack Overflow\n\nQuestion:\nIt is a project composed of Vite & React & antd.\n\nI want to handle antd theme dynamically in vite.config.ts.\n\nI would appreciate it if you could tell me how to modify less.modifyVars value in React component.\n\nThis is the current screen.\n\nlight state /\ndark state\n\nIn dark mode, the style of the select component does not work properly.\n\n```\nimport { getThemeVariables } from 'antd/dist/theme'\n\n...\n\ncss: {\n modules: {\n localsConvention: 'camelCaseOnly'\n },\n preprocessorOptions: {\n less: {\n javascriptEnabled: true,\n modifyVars: {\n ...getThemeVariables({\n dark: true // dynamic\n })\n }\n }\n }\n }\n}\n```\n\n========================================\n\nTop Answer:\n- You need to import 'antd/dist/antd.less' instead of 'antd/dist/antd.css'\n\n- Install dependency for less `npm add -D less`. Vite will automatically catch it.\n\n- Use the following config:\n\n```\ncss: {\n preprocessorOptions:{ \n less: {\n modifyVars: {\n 'primary-color': '#1DA57A',\n 'heading-color': '#f00',\n },\n javascriptEnabled: true,\n },\n },\n },\n```\n\n========================================\n\nCode:\n```text\nimport { getThemeVariables } from 'antd/dist/theme'\n\n...\n\ncss: {\n  modules: {\n    localsConvention: 'camelCaseOnly'\n  },\n  preprocessorOptions: {\n    less: {\n      javascriptEnabled: true,\n        modifyVars: {\n          ...getThemeVariables({\n            dark: true // dynamic\n          })\n        }\n      }\n    }\n  }\n}\n```\n\n```text\nimport vitePluginImp from 'vite-plugin-imp';\nimport { getThemeVariables } from 'antd/dist/theme';\n\nexport default defineConfig({\n  plugins: [\n    // ...\n    vitePluginImp({\n      libList: [\n        {\n          libName: 'antd',\n          style: (name) => `antd/es/${name}/style`,\n        },\n      ],\n    }),\n  ],\n  resolve: {\n    alias: [\n      // { find: '@', replacement: path.resolve(__dirname, 'src') },\n      // fix less import by: @import ~\n      // https://github.com/vitejs/vite/issues/2185#issuecomment-784637827\n      { find: /^~/, replacement: '' },\n    ],\n  },\n  css: {\n    preprocessorOptions: {\n      less: {\n        // modifyVars: { 'primary-color': '#13c2c2' },\n        modifyVars: getThemeVariables({\n          dark: true,\n          // compact: true,\n        }),\n        javascriptEnabled: true,\n      },\n    },\n  },\n});\n```\n\n```text\nvite-plugin-imp\n```\n\n```text\ngetThemeVariables\n```\n\n```text\ncss: {\n     preprocessorOptions:{ \n       less: {\n         modifyVars: {\n           'primary-color': '#1DA57A',\n           'heading-color': '#f00',\n         },\n         javascriptEnabled: true,\n       },\n     },\n   },\n```\n\n```text\nnpm add -D less\n```\n\n========================================\n\nComments:\n- Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.\n- When linking to your own site or content (or content that you are affiliated with), you must disclose your affiliation *in the answer* in order for it not to be considered spam. Having the same text in your username as the URL or mentioning it in your profile is not considered sufficient disclosure under Stack Exchange policy.\n- @cigien Thanks for your reminder of the policy. Maybe it is okey now?\n- With the above method, it is difficult to switch between dark and light themes.\n- @Chad.K You want change themes on runtime? Maybe you can try this: ant.design/docs/react/customize-theme-variable\n- I'm trying to change variables with this, and it does not work at all.\n- @SalahAdDin You should make sure you import antd less correctly.\n- This works perfectly! However, in my case, I had antd 4.x, so I had to install less 3.x","metadata":{"transformedAt":"2026-08-18T18:33:46.403Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":166,"estimatedTokens":935}}153{"id":"stack-73942710","source":"stackoverflow","questionId":73942710,"title":"\"vitest --ui\" causing \"Error: spawn xdg-open ENOENT\"","tags":["node.js","vite","vitest"],"text":"Title: \"vitest --ui\" causing \"Error: spawn xdg-open ENOENT\"\nTags: node.js, vite, vitest\nSource: Stack Overflow\n\nQuestion:\nI'm trying to check out Vitest's fancy UI server in my node docker container. But can't get it up and running. When running the npm script `vitest --ui` I get a node error `spawn xdg-open ENOENT`.\n\nHere the full error message:\n\n```\n$ npm run test-ui\n```\n\n```\n> wpvite@0.0.0 test-ui\n> vitest --ui\n\n DEV v0.23.4 /home/node/apps/main/frontend\n UI started at http://localhost:51204/__vitest__/\n\nnode:events:491\n throw er; // Unhandled 'error' event\n ^\n\nError: spawn xdg-open ENOENT\n at ChildProcess._handle.onexit (node:internal/child_process:283:19)\n at onErrorNT (node:internal/child_process:476:16)\n at process.processTicksAndRejections (node:internal/process/task_queues:82:21)\nEmitted 'error' event on ChildProcess instance at:\n at ChildProcess._handle.onexit (node:internal/child_process:289:12)\n at onErrorNT (node:internal/child_process:476:16)\n at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {\n errno: -2,\n code: 'ENOENT',\n syscall: 'spawn xdg-open',\n path: 'xdg-open',\n spawnargs: [ 'https://localhost:51204/__vitest__/' ]\n}\n\nNode.js v18.10.0\n```\n\nGoogle is no help at all - nothing related to Vitest even close. Also I'm obviously not a Node.js expert.\n\n========================================\n\nTop Answer:\nIf you want to open the FE in a browser, do this:\n\n```\nsudo apt install xdg-utils\n```\n\nIf you don't want to open the UI, like in a server, edit your `package.json` file:\n\n```\n...\n \"scripts\": {\n \"start\": \"vite --no-open\",\n ...\n }\n ...\n```\n\n========================================\n\nCode:\n```bash\n$ npm run test-ui\n```\n\n```text\n> wpvite@0.0.0 test-ui\n> vitest --ui\n\n\n DEV  v0.23.4 /home/node/apps/main/frontend\n      UI started at http://localhost:51204/__vitest__/\n\nnode:events:491\n      throw er; // Unhandled 'error' event\n      ^\n\nError: spawn xdg-open ENOENT\n    at ChildProcess._handle.onexit (node:internal/child_process:283:19)\n    at onErrorNT (node:internal/child_process:476:16)\n    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)\nEmitted 'error' event on ChildProcess instance at:\n    at ChildProcess._handle.onexit (node:internal/child_process:289:12)\n    at onErrorNT (node:internal/child_process:476:16)\n    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {\n  errno: -2,\n  code: 'ENOENT',\n  syscall: 'spawn xdg-open',\n  path: 'xdg-open',\n  spawnargs: [ 'https://localhost:51204/__vitest__/' ]\n}\n\nNode.js v18.10.0\n```\n\n```text\nvitest --ui\n```\n\n```text\nspawn xdg-open ENOENT\n```\n\n```bash\napt install xdg-utils --fix-missing\n```\n\n```text\nxdg-open\n```\n\n```text\nvitest --ui\n```\n\n```text\n/__vitest__/\n```\n\n```text\nhttp://localhost:51204/__vitest__/\n```\n\n```text\nCMD [\"pnpm\",\"run\", \"dev\"]\n```\n\n```text\nvitest --ui\n```\n\n```text\nsudo apt install xdg-utils\n```\n\n```text\n...\n  \"scripts\": {\n    \"start\": \"vite --no-open\",\n    ...\n  }\n  ...\n```\n\n```text\npackage.json\n```\n\n```json\nserver: {    \n        host: true,\n        port: 3000, \n        open: false\n    }\n```\n\n```text\nopen\n```\n\n```text\nfalse\n```\n\n```text\nvite-config.ts\n```\n\n```text\npackage.json\n```\n\n```text\n\"start\": \"vite\"\n```\n\n```text\n\"start\": \"vite --no-open\"\n```\n\n========================================\n\nComments:\n- What do you mean by your \"proxied local url\"? Were you just going to \"localhost:51204\" before? Or did you add \"__vitest__\" to something in the configuration? I'm coming across the same issue where (only in Docker, and I've added the apt-get install xdg-utils to my docker compose), it says \"UI started at localhost:51204/__vitest__\", but still getting a 404 when trying to visit that URL in a browser.\n- @18thletter hey, I have an nginx proxy server running on my local machine to be able to use descriptive domain names (like mynewapp.mycastle) instead of localhost:8015 for local web apps. I configure for each app a custom server block / virtual host.\n- Ah, I see @FullStack Alex. Hmm, I just figured it out on my end. For my setup, I needed a vite server option. Needed server: { host: '0.0.0.0' } as an entry in my vite config.","metadata":{"transformedAt":"2026-08-18T18:33:46.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":192,"estimatedTokens":1036}}154{"id":"stack-76286801","source":"stackoverflow","questionId":76286801,"title":"Vitest CLI not recognized","tags":["vite","vitest"],"text":"Title: Vitest CLI not recognized\nTags: vite, vitest\nSource: Stack Overflow\n\nQuestion:\ninstalled `pnpm add -D vitest` and `pnpm add -D @vitest/ui` in my project dir, when i try `vitest --ui`, I get this error\n\n```\nvitest : The term 'vitest' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try \nagain.\n```\n\n========================================\n\nTop Answer:\nYou should install the package globally using npm or yarn. Don't forget to use `sudo` if you are in Mac or Linux.\n\n```\nnpm install -g vitest\n```\n\n========================================\n\nCode:\n```text\nvitest : The term 'vitest' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try \nagain.\n```\n\n```text\npnpm add -D vitest\n```\n\n```text\npnpm add -D @vitest/ui\n```\n\n```text\nvitest --ui\n```\n\n```text\n\"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"test\": \"vitest --ui\",\n  },\n```\n\n```text\npnpm install\n```\n\n```text\npackage.json\n```\n\n```text\npnpm run test\n```\n\n```text\nnpm install -g vitest\n```\n\n```text\nsudo\n```\n\n```text\nnpx vitest\n```\n\n========================================\n\nComments:\n- without install to global , this is the best way","metadata":{"transformedAt":"2026-08-18T18:33:46.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":77,"estimatedTokens":344}}155{"id":"stack-72223553","source":"stackoverflow","questionId":72223553,"title":"Ignore coverage HTML files from Vite + React HMR","tags":["vite","hot-module-replacement"],"text":"Title: Ignore coverage HTML files from Vite + React HMR\nTags: vite, hot-module-replacement\nSource: Stack Overflow\n\nQuestion:\nI have a project set up using `vite` with the `@vitejs/plugin-react` extension. I'm using the basic config of\n\n```\nexport default defineConfig({\n plugins: [react({ include: ['src'] })]\n})\n```\n\nIn the dev server output I'm seeing page reloads of my coverage HTML files, for example\n\n```\n8:09:45 PM [vite] page reload coverage/lcov-report/App.tsx.html\n```\n\nMy coverage files are located in the project root with a directory of `coverage`. I've tried a number of settings in the Vite config, such as\n\n```\noptimizeDeps: {\n entries: ['index.html'],\n exclude: ['coverage']\n}\n```\n\nand\n\n```\nserver: {\n watch: {\n exclude: ['coverage']\n }\n}\n```\n\nhowever neither of these seem to have any effect. I also tried the following on the React plugin itself\n\n```\nexclude: /coverage/\n```\n\nbut no dice. I would expect that a path like `coverage` would be excluded by default.\n\n========================================\n\nTop Answer:\nI found this to be a consequence of Storybook's internal Vite server being reconfigured on the fly and overriding the base configuration for Vite described above.\n\nIn addition to\n\n```\nserver: {\n watch: {\n exclude: ['coverage']\n }\n}\n```\n\nin `vite.config.ts` I *also* had to configure the following in `.storybook/main.ts`:\n\n```\nimport { InlineConfig, mergeConfig } from 'vite'\n\nconst config: StorybookConfig = {\n /* ... */\n viteFinal: (config: InlineConfig) => mergeConfig(config, {\n server: {\n watch: { ignored: ['**/coverage/**'] },\n },\n }),\n /* ... */\n}\n```\n\n========================================\n\nCode:\n```text\nexport default defineConfig({\n  plugins: [react({ include: ['src'] })]\n})\n```\n\n```text\n8:09:45 PM [vite] page reload coverage/lcov-report/App.tsx.html\n```\n\n```text\noptimizeDeps: {\n  entries: ['index.html'],\n  exclude: ['coverage']\n}\n```\n\n```text\nserver: {\n  watch: {\n    exclude: ['coverage']\n  }\n}\n```\n\n```text\nexclude: /coverage/\n```\n\n```text\nvite\n```\n\n```text\n@vitejs/plugin-react\n```\n\n```text\ncoverage\n```\n\n```text\ncoverage\n```\n\n```json\nserver: {\n    watch: {\n      ignored: ['**/coverage/**'],\n    },\n  }\n```\n\n```text\nserver: {\n  watch: {\n    exclude: ['coverage']\n  }\n}\n```\n\n```js\nimport { InlineConfig, mergeConfig } from 'vite'\n\nconst config: StorybookConfig = {\n  /* ... */\n  viteFinal: (config: InlineConfig) => mergeConfig(config, {\n    server: {\n      watch: { ignored: ['**/coverage/**'] },\n    },\n  }),\n  /* ... */\n}\n```\n\n```text\nvite.config.ts\n```\n\n```text\n.storybook/main.ts\n```\n\n========================================\n\nComments:\n- Either I'm blind, or this wasn't in the documentation before. Thanks!\n- Or rather than `'**&#47;coverage&#47;**` you can do `path.resolve(__dirname, '.&#47;coverage')` to ignore only the top level `coverage` folder","metadata":{"transformedAt":"2026-08-18T18:33:46.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":168,"estimatedTokens":705}}156{"id":"stack-75657294","source":"stackoverflow","questionId":75657294,"title":"Use Vite to create webview in VSCode Extension","tags":["vscode-extensions","vite"],"text":"Title: Use Vite to create webview in VSCode Extension\nTags: vscode-extensions, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use Vite (react-ts) to generate script used in webview on VSCode Extension. (Extension is also written in Typescript.)\n\nIs this possible? And how can I configure?\n\nThanks!","metadata":{"transformedAt":"2026-08-18T18:33:46.404Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":10,"estimatedTokens":76}}157{"id":"stack-74895016","source":"stackoverflow","questionId":74895016,"title":"How to determine if Vue is running via Vite or Webpack in development mode?","tags":["vue.js","webpack","vuejs3","vite"],"text":"Title: How to determine if Vue is running via Vite or Webpack in development mode?\nTags: vue.js, webpack, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nVite and Webpack use different strategies to import modules.\n\nI am writting a package that contains Vue files that recursively require components.\nThat logic is different in Vite and in Webpack.\n\nIs there a way to determine if the code is being run in Vite or Webpack from within the component vue file?\n\nI cannot seem to find a way to determine that.\n\nI tried accessing `process.env` but it doesn't have that info there, i also tried `getCurrrentInstance()` and analyzed its object, but there is no info there either.\n\nIs it possible to determine?\n\n========================================\n\nCode:\n```text\nprocess.env\n```\n\n```text\ngetCurrrentInstance()\n```\n\n```text\nimport.meta.env\n```\n\n```text\nimport.meta.env !== undefined\n```\n\n```text\nprocess.env\n```\n\n```text\nprocess.env !== undefined\n```\n\n========================================\n\nComments:\n- thank you! i also started checking for defined variables, but you are spot on about these particular variables for checking webpack vs vite.","metadata":{"transformedAt":"2026-08-18T18:33:46.404Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":49,"estimatedTokens":286}}158{"id":"stack-74747710","source":"stackoverflow","questionId":74747710,"title":"vitejs build with jsx returning MIME error on aws amplify","tags":["reactjs","amazon-web-services","aws-amplify","vite","mime"],"text":"Title: vitejs build with jsx returning MIME error on aws amplify\nTags: reactjs, amazon-web-services, aws-amplify, vite, mime\nSource: Stack Overflow\n\nQuestion:\nSo I am using Vitejs with a react project.\nI am using the jsx extension for all the react files in the appplication.\nWhen using the npm build, then npm run preview the applicaiton is working fine on my computer locally\nhowever when I am using aws amplify, the page is giving me a MIME error:\n\nFailed to load module script: Expected a JavaScript module script but the server responded with a MIME type of \"text/jsx\". Strict MIME type checking is enforced for module scripts per HTML spec.\n\nNow I tried many configurations for Vite, yet nothing is working, here is my config file\n\n```\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport fs from 'fs/promises';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n esbuild: {\n loader: 'jsx',\n },\n resolve: {\n alias: {\n './runtimeConfig': './runtimeConfig.browser',\n },\n },\n optimizeDeps: {\n esbuildOptions: {\n loader: {\n '.js': 'jsx',\n },\n },\n },\n})\n```\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport fs from 'fs/promises';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  esbuild: {\n    loader: 'jsx',\n  },\n  resolve: {\n    alias: {\n      './runtimeConfig': './runtimeConfig.browser',\n    },\n  },\n  optimizeDeps: {\n    esbuildOptions: {\n      loader: {\n        '.js': 'jsx',\n      },\n    },\n  },\n})\n```\n\n```text\nbaseDirectory: /\n```\n\n```text\nbaseDirectory: /dist\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.404Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":76,"estimatedTokens":417}}159{"id":"stack-69332819","source":"stackoverflow","questionId":69332819,"title":"Svelte +Vite: writable store in Typescript, cannot import Writable interface","tags":["typescript","svelte","vite"],"text":"Title: Svelte +Vite: writable store in Typescript, cannot import Writable interface\nTags: typescript, svelte, vite\nSource: Stack Overflow\n\nQuestion:\nIn a Svelte project scaffolded using Vite I try to write a Svelte store in Typescript; having troubles with importing `Writable` interface like below:\n\n```\nimport { Writable, writable, derived } from 'svelte/store';\n```\n\nThis results in the following error in a browser console:\n\n```\nUncaught SyntaxError: The requested module '/node_modules/.vite/svelte_store.js?v=16f52463' does not provide an export named 'Writable'.\n```\n\nIs there any way to import `Writable` interface in such a setup?\n\n========================================\n\nCode:\n```text\nimport { Writable, writable, derived } from 'svelte/store';\n```\n\n```text\nUncaught SyntaxError: The requested module '/node_modules/.vite/svelte_store.js?v=16f52463' does not provide an export named 'Writable'.\n```\n\n```text\nWritable<T>\n```\n\n```text\nWritable<T>\n```\n\n```text\nimport type { Writable } from 'svelte/store';\nimport { writable, derived } from 'svelte/store';\n```\n\n```text\nimport { type Writable, writable, derived } from 'svelte/store';\n```\n\n```text\nimport type { Writable } from 'svelte/store';\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.404Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":50,"estimatedTokens":302}}160{"id":"stack-77355876","source":"stackoverflow","questionId":77355876,"title":"Vite not respecting server.watch.ignored option (Laravel)","tags":["laravel","vite"],"text":"Title: Vite not respecting server.watch.ignored option (Laravel)\nTags: laravel, vite\nSource: Stack Overflow\n\nQuestion:\nI'm using Laravel 10 with Inertia and Vite. The `/resources/stuff/` folder contains a very large amount of subfolders and files which I don't want to be watched while running Vite. This is to avoid getting \"`ENOSPC: System limit for number of file watchers reached`\".\n\nMy vite.config.js contains the following option:\n\n```\nexport default defineConfig({\n server: {\n watch: {\n ignored: [\"/resources/stuff/\"],\n },\n },\n ...\n});\n```\n\nYet when I do `npm run dev`, I still get `ENOSPC: System limit for number of file watchers reached` on a file inside the ignored folder.\n\nHow can I get Vite to skip `/resources/stuff/` while watching for file changes? I'm on Ubuntu 22.04. I'd rather not just increase the operating system's maximum file watchers, as the folder contains more than 80,000 files.\n\n========================================\n\nTop Answer:\nThe accepted answer works *only* *if you're ok with doing a regex match that also catches subdirectories*. To use a relative path to avoid that issue requires some understanding of what's happening under the hood.\n\nVite defines its defaults in `watch.ts`: https://github.com/vitejs/vite/blob/main/packages/vite/src/node/watch.ts\n\nWhich in turn are merely passed on to the dead chokidar project: https://github.com/paulmillr/chokidar/blob/main/src/index.ts\n\nThat project will match paths three ways:\n\nAbsolute paths\n\nRegex matching (which is what adding `**` to the front triggers)\n\nRelative paths, by combining with the current working directory (`cwd`)\n\nThe problem with number three is that chokidar defaults to an empty string for the `cwd` if it's not passed in. And by default, vite doesn't pass anything in for that option. So we have to do it manually:\n\n```\nexport default defineConfig({\n server: {\n watch: {\n cwd: process.cwd(),\n ignored: [\"resources/stuff/\"],\n },\n },\n ...\n});\n```\n\nShould work (note also removing the leading slash from the `resources` directory so it's not absolute).\n\n========================================\n\nCode:\n```text\nexport default defineConfig({\n  server: {\n    watch: {\n      ignored: [\"/resources/stuff/\"],\n    },\n  },\n  ...\n});\n```\n\n```text\n/resources/stuff/\n```\n\n```text\nENOSPC: System limit for number of file watchers reached\n```\n\n```text\nnpm run dev\n```\n\n```text\nENOSPC: System limit for number of file watchers reached\n```\n\n```text\n/resources/stuff/\n```\n\n```js\nexport default defineConfig({\n  server: {\n    watch: {\n      ignored: [\"**/resources/stuff/**\"],\n    },\n  },\n  // ...\n});\n```\n\n```text\n/resources\n```\n\n```ts\nexport default defineConfig({\n  server: {\n    watch: {\n      cwd: process.cwd(),\n      ignored: [\"resources/stuff/\"],\n    },\n  },\n  ...\n});\n```\n\n```text\n**\n```\n\n```text\ncwd\n```\n\n```text\ncwd\n```\n\n```text\nresources\n```\n\n========================================\n\nComments:\n- Thanks! I thought the path on server.watch.ignored was relative to the project's root.\n- @lampyridae it might be, but paths starting with `&#47;` are not relative. You might have been thinking of `.&#47;`\n- \"resources/stuff/\" doesn't work either so it seems the recursive wildcards are necessary.\n- Yeah, that surprises me as well. I haven't managed to get any relative dir (without leading `**`) to work.","metadata":{"transformedAt":"2026-08-18T18:33:46.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":141,"estimatedTokens":826}}161{"id":"stack-75189443","source":"stackoverflow","questionId":75189443,"title":"How to do named slots in Vue3 project?","tags":["vue.js","vuejs3","vite","slot"],"text":"Title: How to do named slots in Vue3 project?\nTags: vue.js, vuejs3, vite, slot\nSource: Stack Overflow\n\nQuestion:\nIn my vue 3 script setup component, I have this\n\n```\n\n \n \n \n \n \n {{ header.title }}\n \n \n \n \n \n \n \n \n \n \n\nconst componentProps = defineProps();\n\n```\n\nBut I get this error\n\nhttps://i.sstatic.net/afo6e.png\n\nAnd vite complains this too\n\n```\nCodegen node is missing for element/if/for node. Apply appropriate transforms first.\n4:00:10 PM [vite] Internal server error: Codegen node is missing for element/if/for node. Apply appropriate transforms first.\n Plugin: vite:vue\n```\n\nHow can I resolve this?\n\n========================================\n\nCode:\n```text\n<template>\n    <table>\n        <tbody>\n            <template v-for=\"(row, i) in componentProps.rows\">\n                <tr v-for=\"(header, j) in componentProps.headers\" :key=\"i + '-' + j\" :data-alternating=\"i%2===0 ? 'even' : 'odd'\">\n                    <td class=\"font-weight-bold text-caption\">\n                        {{ header.title }}\n                    </td>\n                    <td>\n                        <template #test>\n                            \n                        </template>\n                    </td>\n                </tr>\n            </template>\n        </tbody>\n    </table>\n</template>\n\n<script setup lang='ts'>\nconst componentProps = defineProps<{\n    headers: TableHeader[];\n    rows: {[name:string]:any}[];\n}>();\n</script>\n```\n\n```text\nCodegen node is missing for element/if/for node. Apply appropriate transforms first.\n4:00:10 PM [vite] Internal server error: Codegen node is missing for element/if/for node. Apply appropriate transforms first.\n  Plugin: vite:vue\n```\n\n```html\n<template>\n  <slot name=\"test\">\n    Fallback content\n  </slot>\n  More child component content\n</template>\n```\n\n```html\n<template>\n  Some parent content...\n  <component-a>\n    <template #test>\n      I am injected content\n    </template>\n  </component-a>\n  More parent content...\n</template>\n```\n\n```text\nSome parent content...\nI am injected content\nMore child component content\nMore parent content...\n```\n\n```text\nSome parent content...\nFallback content\nMore child component content\nMore parent content...\n```\n\n```html\n<template>\n  <slot />\n  Bla bla...\n</template>\n```\n\n```html\n<component-a>\n  Whatever\n</component-a>\n```\n\n```html\nWhatever\nBla bla...\n```\n\n```html\n<component-a>\n  <template #default>\n    Whatever\n  </template>\n</component-a>\n```\n\n```text\n<slot name=\"test\" />\n```\n\n```text\n<template>\n```\n\n```text\n<template #test>\n```\n\n```text\n<component-a />\n```\n\n```text\n<template #test>\n```\n\n```text\n<slot name=\"test\" />\n```\n\n```text\n<template #test>\n```\n\n```text\n<slot />\n```\n\n```text\ndefault\n```\n\n========================================\n\nComments:\n- Could you create a *runnable* minimal reproducible example? Consider using codesandbox or similar. Slots can only be used inside components which have those slots defined. You don't seem to be using any vue component in your template.\n- Consider adding the component in which you defined ``, where the `` content is supposed to be injected. Also, make sure you read the docs on named slots. Or perhaps you could explain the problem you're attempting to solve with slots.","metadata":{"transformedAt":"2026-08-18T18:33:46.404Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":183,"estimatedTokens":799}}162{"id":"stack-77445761","source":"stackoverflow","questionId":77445761,"title":"How to add matchers from jest-extended","tags":["jestjs","vite","vitest"],"text":"Title: How to add matchers from jest-extended\nTags: jestjs, vite, vitest\nSource: Stack Overflow\n\nQuestion:\nI'm porting Jest tests to Vitest.\n\nThese tests use matchers from `jest-extended` like `expect(val).toBeString()`.\nI tried to put `import \"jest-extended\"` in the test file, but the result is the error: `Error: Invalid Chai property: toBeString`.\n\nI tried also to put in `vite.config.ts`:\n\n```\ntest: {\n environment: \"happy-dom\",\n globals: true,\n reporters: [\"default\", \"html\"],\n setupFiles: [\n \"node_modules/jest-extended/dist/index.js\",\n ]\n }\n```\n\nwithout change.\nEven tried to use the `vitest-extended` package but also no change.\nAny suggestion?\n\n========================================\n\nCode:\n```text\ntest: {\n        environment: \"happy-dom\",\n        globals: true,\n        reporters: [\"default\", \"html\"],\n        setupFiles: [\n            \"node_modules/jest-extended/dist/index.js\",\n        ]\n    }\n```\n\n```text\njest-extended\n```\n\n```text\nexpect(val).toBeString()\n```\n\n```text\nimport \"jest-extended\"\n```\n\n```text\nError: Invalid Chai property: toBeString\n```\n\n```text\nvite.config.ts\n```\n\n```text\nvitest-extended\n```\n\n```js\n// vitest.setup.js\nimport { expect } from 'vitest';\nimport * as matchers from 'jest-extended';\n\nexpect.extend(matchers);\n```\n\n```js\n// vitest.config.js\nexport default defineConfig({\n  test: {\n    setupFiles: ['./vitest.setup.js'],\n  },\n});\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.404Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":81,"estimatedTokens":344}}163{"id":"stack-71176962","source":"stackoverflow","questionId":71176962,"title":"Vite - change static assets' directoy","tags":["reactjs","spring","vue.js","vite"],"text":"Title: Vite - change static assets' directoy\nTags: reactjs, spring, vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI had build an app using **create-react-app**. And our server is set up as such that all files except `index.html` are in a folder named **static**.\n\n```\n\n \n \n \n App\n \n \n \n \n\n```\n\nSo `JS` file's path is `./static/js/main.836d2eb0.js`.\n\nAnd then I decided to go for Vite.\n\nAs you may know, Vite's default assets' directory is callled assets. I managed to change it to `static` by changing `build.assetsDir` to `static` in `vite.config.js`\n\n```\nbuild: {\n assetsDir: \"static\",\n outDir: \"./../backend/src/main/resources/static/app/\",\n },\n```\n\n**I changed the output's directory too.**\n\nAfter runing `npm run build`, all of the files are generated in the correct directory. However, CSS, JS, and other assets have wrong path, for ex, my JS file's path is `/static/vendor.ba9c442b.js` **It lacks dot(.) before the first slush**\n\n```\n\n \n \n \n Fiken Kundestøtte\n \n \n \n \n\n```\n\n**info:** It is a spring boot app.\n\n### So how to fix the files' path?\n\n========================================\n\nCode:\n```text\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\" />\n  <link rel=\"icon\" type=\"image/svg+xml\" href=\"./static/favicon.f99d69b1.ico\" />\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n  <title>App</title>\n  \n  <script type=\"module\" crossorigin src=\"./static/index.81e5d079.js\"></script>\n  <link rel=\"modulepreload\" href=\"./static/vendor.ba9c442b.js\">\n  <link rel=\"stylesheet\" href=\"./static/index.f28d7853.css\">\n</head>\n<body>\n<div id=\"root\"></div>\n\n</body>\n</html>\n```\n\n```text\nbuild: {\n    assetsDir: \"static\",\n    outDir: \"./../backend/src/main/resources/static/app/\",\n  },\n```\n\n```text\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\" />\n  <link rel=\"icon\" type=\"image/svg+xml\" href=\"/static/favicon.f99d69b1.ico\" />\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n  <title>Fiken Kundestøtte</title>\n  \n  <script type=\"module\" crossorigin src=\"/static/index.81e5d079.js\"></script>\n  <link rel=\"modulepreload\" href=\"/static/vendor.ba9c442b.js\">\n  <link rel=\"stylesheet\" href=\"/static/index.f28d7853.css\">\n</head>\n<body>\n<div id=\"root\"></div>\n\n</body>\n</html>\n```\n\n```text\nindex.html\n```\n\n```text\nJS\n```\n\n```text\n./static/js/main.836d2eb0.js\n```\n\n```text\nstatic\n```\n\n```text\nbuild.assetsDir\n```\n\n```text\nstatic\n```\n\n```text\nvite.config.js\n```\n\n```text\nnpm run build\n```\n\n```text\n/static/vendor.ba9c442b.js\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  base: './', 👈\n})\n```\n\n```text\nbase\n```\n\n```text\n./\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.404Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":156,"estimatedTokens":663}}164{"id":"stack-73326994","source":"stackoverflow","questionId":73326994,"title":"How to apply proper styles of element-plus message box?","tags":["css","vue.js","vite","element-plus"],"text":"Title: How to apply proper styles of element-plus message box?\nTags: css, vue.js, vite, element-plus\nSource: Stack Overflow\n\nQuestion:\nThis is how element-plus message box looks on a minimal page I built:\nhttps://i.sstatic.net/XjONG.png\n\nI was expecting it to look like on the element-plus documentation.\n\nI am using **Vue** with **vite** and **ElementPlus**. I copied the setup from vite and element plus documentation. I played with a lot other elements and they all render correctly. The minimal `App.vue` component which can reproduce the problem:\n\n```\n\n Click to open the Message Box\n\nimport { ElMessageBox } from 'element-plus'\n\nconst open = () => {\n ElMessageBox.alert('This is a message', 'Title', {\n confirmButtonText: 'OK'\n })\n}\n\n```\n\nMy `vite.config.js`\n\n```\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport AutoImport from 'unplugin-auto-import/vite'\nimport Components from 'unplugin-vue-components/vite'\nimport { ElementPlusResolver } from 'unplugin-vue-components/resolvers'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n vue(),\n AutoImport({\n resolvers: [ElementPlusResolver()],\n }),\n Components({\n resolvers: [ElementPlusResolver()],\n })\n ],\n base: ''\n})\n```\n\nThe page is minimal:\n\n```\n\nVite + Vue\n\n```\n\nAnd so is the script:\n\n```\nimport { createApp } from 'vue'\nimport App from './App.vue'\ncreateApp(App).mount('#app')\n```\n\nFinally my `package.json`:\n\n```\n{\n \"name\": \"v2\",\n \"private\": true,\n \"version\": \"0.0.0\",\n \"main\": \"main.js\",\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\",\n \"start\": \"electron .\"\n },\n \"dependencies\": {\n \"electron\": \"^20.0.2\",\n \"element-plus\": \"^2.2.12\",\n \"vue\": \"^3.2.37\"\n },\n \"devDependencies\": {\n \"@vitejs/plugin-vue\": \"^3.0.2\",\n \"unplugin-auto-import\": \"^0.11.1\",\n \"unplugin-vue-components\": \"^0.22.4\",\n \"vite\": \"^3.0.6\"\n }\n}\n```\n\n========================================\n\nTop Answer:\nif you have use 'unplugin-auto-import/vite' and 'unplugin-vue-components/vite', this is not needed:\n\n```\nimport { ElMessageBox } from 'element-plus';\n```\n\n========================================\n\nCode:\n```html\n<template>\n  <el-button text @click=\"open\">Click to open the Message Box</el-button>\n</template>\n\n<script setup>\nimport { ElMessageBox } from 'element-plus'\n\nconst open = () => {\n  ElMessageBox.alert('This is a message', 'Title', {\n    confirmButtonText: 'OK'\n  })\n}\n</script>\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport AutoImport from 'unplugin-auto-import/vite'\nimport Components from 'unplugin-vue-components/vite'\nimport { ElementPlusResolver } from 'unplugin-vue-components/resolvers'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    vue(),\n    AutoImport({\n      resolvers: [ElementPlusResolver()],\n    }),\n    Components({\n      resolvers: [ElementPlusResolver()],\n    })\n  ],\n  base: ''\n})\n```\n\n```html\n<!DOCTYPE html>\n<title>Vite + Vue</title>\n<div id=\"app\"></div>\n<script type=\"module\" src=\"/src/main.js\"></script>\n```\n\n```js\nimport { createApp } from 'vue'\nimport App from './App.vue'\ncreateApp(App).mount('#app')\n```\n\n```json\n{\n  \"name\": \"v2\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"main\": \"main.js\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"preview\": \"vite preview\",\n    \"start\": \"electron .\"\n  },\n  \"dependencies\": {\n    \"electron\": \"^20.0.2\",\n    \"element-plus\": \"^2.2.12\",\n    \"vue\": \"^3.2.37\"\n  },\n  \"devDependencies\": {\n    \"@vitejs/plugin-vue\": \"^3.0.2\",\n    \"unplugin-auto-import\": \"^0.11.1\",\n    \"unplugin-vue-components\": \"^0.22.4\",\n    \"vite\": \"^3.0.6\"\n  }\n}\n```\n\n```text\nApp.vue\n```\n\n```text\nvite.config.js\n```\n\n```text\npackage.json\n```\n\n```html\n<template>\n  <el-button text @click=\"open\">Click to open the Message Box</el-button>\n</template>\n\n<script setup>\nimport { ElMessageBox } from 'element-plus';\nimport 'element-plus/es/components/message/style/css'; // this is only needed if the page also used ElMessage\nimport 'element-plus/es/components/message-box/style/css';\n\nconst open = () => {\n  ElMessageBox.alert('This is a message', 'Title', {\n    confirmButtonText: 'OK'\n  })\n}\n</script>\n```\n\n```text\nElMessage\n```\n\n```text\nElMessageBox\n```\n\n```text\nimport { ElMessageBox } from 'element-plus';\n```\n\n========================================\n\nComments:\n- All the code shared above is irrelevant. Because you're not showing us how you're loading Element styles. It sounds like you're loading and scoping them to your app's DOM element (e.g: everything else looks as it should), but they don't apply outside of the app element (the message box and modals are direct children of `` so, technically, they're not inside the app element). Please take time to read installation.\n- Well, that is the point - I do not style the elements myself here. What I am doing is described in **On-demand Import** section here element-plus.org/en-US/guide/quickstart.html#on-demand-impor&zwnj;&#8203;t\n- I actually exactly followed the steps described in installation / Using Package Manager and quick start / On-demand Import. They do not mention anything about the styles and most elements work out of the box. @tao could you advise on which parts did I ignore? The installation guide only mentions importing all styles when using unpkg and jsDelivr but I do not use them.\n- 2023: Still needs to be manually imported, now it is via `import 'element-plus&#47;theme-chalk&#47;src&#47;message-box.scss'`\n- You can also import inside main.js `import ElementPlus from 'element-plus';` `import 'element-plus&#47;theme-chalk&#47;index.css';` `app.use(ElementPlus);`\n- Actually, based on his usage, I believe it still is. `unplugin-auto-import` doesn't handle the fact he's using the method `ElMessageBox.alert` in ``. It handles component usage in ``.","metadata":{"transformedAt":"2026-08-18T18:33:46.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":236,"estimatedTokens":1458}}165{"id":"stack-71107701","source":"stackoverflow","questionId":71107701,"title":"How to build web component with styling library using vite and vue 3?","tags":["vue.js","web-component","vite"],"text":"Title: How to build web component with styling library using vite and vue 3?\nTags: vue.js, web-component, vite\nSource: Stack Overflow\n\nQuestion:\nI am able to build vue web component and load it in other pages, but I can't find document how to correctly include a UI framework. It seems the web component is under shadowDOM and import css using style tag won't work.\n\n(Add the CDN link in the template and style is applied)\nhttps://i.sstatic.net/C9cnu.png\n\nAny hint on any framework, Vuetify or Ant Design or Tailwind CSS will be appreciated.\n\nSimilar question: Vuetify build as Web component style not showing\n\n========================================\n\nCode:\n```text\n// Read SCSS file as a raw CSS text using Webpack/Rollup/Parcel\nimport styleText from './my-component.scss';\n\nconst sheet = new CSSStyleSheet();sheet.replaceSync(styleText);\n\n// Use the sheet inside the web component constructor\nshadowRoot.adoptedStyleSheets = [sheet];\n```\n\n```text\nimport styleText from 'ant/button.css';\n\nclass FancyComponent extends HTMLElement {\n\n  constructor() {\n    super();\n\n    const shadowRoot = this.attachShadow({ mode: 'open' });\n\n    shadowRoot.innerHTML = `\n      <!-- Styles are scoped -->\n      <style>\n        ${styleText}\n      </style>\n      <div>\n        <p>Hello World</p>\n      </div>\n    `;\n  }\n}\n\ncustomElements.define('fancy-comp', FacyComponent);\n```\n\n```text\ncss\n```\n\n```text\nstyle\n```\n\n```text\nlink\n```\n\n========================================\n\nComments:\n- The whole point of using web components is making them impermeable at context styling. If you don't need/want that, just export them as SFC's and use them as normal components.\n- Thank you! A bit surprised that very few material talking about those details.\n- @Harsha, can you do an example for vuetify please ?\n- This seems to work now on Safari and iOS, too. Great solution.","metadata":{"transformedAt":"2026-08-18T18:33:46.404Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":71,"estimatedTokens":462}}166{"id":"stack-74912353","source":"stackoverflow","questionId":74912353,"title":"I just deployed my Vite React site but my icons/images aren't deployed","tags":["reactjs","frontend","web-deployment","vite","netlify"],"text":"Title: I just deployed my Vite React site but my icons/images aren't deployed\nTags: reactjs, frontend, web-deployment, vite, netlify\nSource: Stack Overflow\n\nQuestion:\nI deployed my Vite React site on Netlify but my skill icons aren't rendered!!\nhttps://i.sstatic.net/DUMSU.png\nHere's the site..\nI did execute npm run build before deploying, I got the dist folder and deployed that on Netlify.\nBut at first the assets folder didn't had the icons so I added it in the assets (of dist folder) folder too, but no success!!\nPlease help.\n\nI wanna render my skill icons of my portfolio site.\n\n========================================\n\nTop Answer:\nReferring to the `Vite` documentation You should put Your **assets files** into `public` folder directly.\n\nNotice that:\n\nYou should always reference public assets using root absolute path -\nfor example, `public/icon.png` should be referenced in source code as\n`/icon.png`.\n\n**folder&file** structure:\n\nhttps://i.sstatic.net/N9PIz.png\n\n**Skills.jsx** (*icons*)\n\n```\nimport React from \"react\";\n// import Skill from \"./Skill\";\n\nfunction Skills() {\n return (\n <>\n \n \n \n \n HTML\n\n \n \n \n CSS3\n\n \n \n \n JavaScript\n\n \n \n \n ReactJs\n\n \n \n \n MongoDB\n\n \n \n \n ExpressJs\n\n \n \n \n GitHub\n\n \n \n \n NodeJs\n\n \n \n \n Authentication\n\n \n \n \n API\n\n \n \n \n \n );\n}\n\nexport default Skills;\n```\n\n**Intro.jsx** (*hero.gif*)\n\n```\nimport React from \"react\";\nimport hero from \"/hero.gif\";\nfunction Intro() {\n return (\n <>\n \n \n \n Hey, I'm\n\n \n\n### Shubham Pawar\n\n I'm a MERN stack Developer.\n\n Contact Me\n Resume\n \n \n \n \n \n \n \n );\n}\n\nexport default Intro;\n```\n\n**Footer.jsx** (*icons*)\n\n```\nimport React from \"react\";\n\nfunction Footer() {\n return (\n <>\n \n \n #\n \n \n \n \n \n \n \n \n \n \n \n \n \n\n \n \n \n Home\n \n\n About\n\n Contact\n \n\n \n @mjshubham21 Copyright &copy; {new Date().getFullYear()} All Rights\n Reserved.\n \n\n \n \n \n );\n}\n\nexport default Footer;\n```\n\n**Output in browser**:\n\nhttps://i.sstatic.net/MwZlt.png\n\n========================================\n\nCode:\n```js\n{\n    id: 1,\n    icon: \"/assets/html5.svg\",\n    iconName: \"HTML\",\n},\n```\n\n```text\nassets\n```\n\n```text\npublic\n```\n\n```text\n./src\n```\n\n```text\nimport React from \"react\";\n// import Skill from \"./Skill\";\n\nfunction Skills() {\n  return (\n    <>\n      <section className=\"skills\">\n        <div className=\"card\">\n          <div className=\"content\">\n            <img className=\"skillIcon\" src=\"/html5.svg\" alt=\"Icon\" />\n            <p className=\"skillName\">HTML</p>\n          </div>\n          <div className=\"content\">\n            <img className=\"skillIcon\" src=\"/css3.svg\" alt=\"Icon\" />\n            <p className=\"skillName\">CSS3</p>\n          </div>\n          <div className=\"content\">\n            <img className=\"skillIcon\" src=\"/js.svg\" alt=\"Icon\" />\n            <p className=\"skillName\">JavaScript</p>\n          </div>\n          <div className=\"content\">\n            <img className=\"skillIcon\" src=\"/react.svg\" alt=\"Icon\" />\n            <p className=\"skillName\">ReactJs</p>\n          </div>\n          <div className=\"content\">\n            <img className=\"skillIcon\" src=\"/mongodb.svg\" alt=\"Icon\" />\n            <p className=\"skillName\">MongoDB</p>\n          </div>\n          <div className=\"content\">\n            <img className=\"skillIcon\" src=\"/express.svg\" alt=\"Icon\" />\n            <p className=\"skillName\">ExpressJs</p>\n          </div>\n          <div className=\"content\">\n            <img className=\"skillIcon\" src=\"/github.svg\" alt=\"Icon\" />\n            <p className=\"skillName\">GitHub</p>\n          </div>\n          <div className=\"content\">\n            <img className=\"skillIcon\" src=\"/node.svg\" alt=\"Icon\" />\n            <p className=\"skillName\">NodeJs</p>\n          </div>\n          <div className=\"content\">\n            <img className=\"skillIcon\" src=\"/password.svg\" alt=\"Icon\" />\n            <p className=\"skillName\">Authentication</p>\n          </div>\n          <div className=\"content\">\n            <img className=\"skillIcon\" src=\"/api.svg\" alt=\"Icon\" />\n            <p className=\"skillName\">API</p>\n          </div>\n        </div>\n      </section>\n    </>\n  );\n}\n\nexport default Skills;\n```\n\n```text\nimport React from \"react\";\nimport hero from \"/hero.gif\";\nfunction Intro() {\n  return (\n    <>\n      <main>\n        <section id=\"intro\" className=\"hero\">\n          <div className=\"heroText\">\n            <p className=\"topData\">Hey, I'm</p>\n            <h1 className=\"title\">Shubham Pawar</h1>\n            <p className=\"heroData\">I'm a MERN stack Developer.</p>\n            <button className=\"btn\">Contact Me</button>\n            <button className=\"btn\">Resume</button>\n          </div>\n          <div className=\"heroImg\">\n            <img className=\"heroGif\" src={hero} alt=\"hero img\" />\n          </div>\n        </section>\n      </main>\n    </>\n  );\n}\n\nexport default Intro;\n```\n\n```text\nimport React from \"react\";\n\nfunction Footer() {\n  return (\n    <>\n      <footer className=\"Footer\">\n        <div className=\"footer-right\">\n          <a href=\"#\"></a>\n          <a href=\"#\">\n            <img className=\"footerIcon\" src=\"/linkedin2.png\" alt=\"linkedIn\" />\n          </a>\n          <a href=\"#\">\n            <img className=\"footerIcon\" src=\"/github2.png\" alt=\"GitHub\" />\n          </a>\n          <a href=\"#\">\n            <img className=\"footerIcon\" src=\"/instagram.png\" alt=\"Instagram\" />\n          </a>\n          <a href=\"#\">\n            <img className=\"footerIcon\" src=\"/twitter.png\" alt=\"Twitter\" />\n          </a>\n        </div>\n\n        <div className=\"footer-left\">\n          <p className=\"footer-links\">\n            <a className=\"link-1\" href=\"#\">\n              Home\n            </a>\n\n            <a href=\"#about\">About</a>\n\n            <a href=\"#contact\">Contact</a>\n          </p>\n          <p>\n            @mjshubham21 Copyright &copy; {new Date().getFullYear()} All Rights\n            Reserved.\n          </p>\n        </div>\n      </footer>\n    </>\n  );\n}\n\nexport default Footer;\n```\n\n```text\nVite\n```\n\n```text\npublic\n```\n\n```text\npublic/icon.png\n```\n\n```text\n/icon.png\n```\n\n```text\npublic/icon.png\n```\n\n```text\n/icon.png\n```\n\n========================================\n\nComments:\n- Could You provide link to the repo please?\n- github.com/mjshubham21/Mjshubham21Portfolio\n- Thanks, it worked in my local host, but not on my deployed site... mjshubham21.live thoughts?? console says \" Failed to load resource: the server responded with a status of 404 () \" for the icons...\n- Thanks, it worked in my local host but not on the live site... mjshubham21.live\n- @mjshubham21 Are You sure ? :-) I see icons ...:-P\n- Yeah it was fixed...","metadata":{"transformedAt":"2026-08-18T18:33:46.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":374,"estimatedTokens":1627}}167{"id":"stack-77284472","source":"stackoverflow","questionId":77284472,"title":"Importing SVG as ReactComponent in Vite - ambiguous indirect export: ReactComponent","tags":["reactjs","typescript","vite"],"text":"Title: Importing SVG as ReactComponent in Vite - ambiguous indirect export: ReactComponent\nTags: reactjs, typescript, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to import a SVG as a ReactComponent with Vite and the `vite-plugin-svgr` plugin, and I'm running into an error that I believe to be Type-related.\n\nHere's my import statement and usage:\n\n```\nimport { ReactComponent as ProfileIcon } from '../assets/profile.svg'\n\nexport function Example() {\n return (\n \n blahblahblah\n\n \n \n }\n}\n```\n\nThe page doesn't load at all, and my browser console shows the following error:\n\nUncaught SyntaxError: ambiguous indirect export: ReactComponent\n\nI think this is related to my **custom.d.ts** file, which contains the following declaration:\n\n```\ndeclare module '*.svg' {\n import * as React from 'react'\n\n export const ReactComponent: React.FunctionComponent & { title?: string }\n >\n export default ReactComponent\n}\n```\n\nI added this declaration after troubleshooting another TypeScript error, many StackOverflow users posted the same suggestion but here's one example.\n\nI can't seem to find a guide for React + Vite + TypeScript SVG components that works for me.\n\nFor reference, here's some other changes I have in place:\n\n**tsconfig.json**\n\n```\n{\n \"compilerOptions\": {\n ...\n \"types\": [\"vite-plugin-svgr/client\"]\n },\n ...\n \"include\": [\"src\", \"custom.d.ts\"]\n}\n```\n\n**vite-env.d.ts**\n\n```\n/// \n/// \n```\n\n========================================\n\nCode:\n```text\nimport { ReactComponent as ProfileIcon } from '../assets/profile.svg'\n\nexport function Example() {\n    return (\n        <div>\n            <p>blahblahblah</p>\n            <ProfileIcon />\n        <div>\n    }\n}\n```\n\n```text\ndeclare module '*.svg' {\n    import * as React from 'react'\n\n    export const ReactComponent: React.FunctionComponent<\n        React.ComponentProps<'svg'> & { title?: string }\n    >\n    export default ReactComponent\n}\n```\n\n```text\n{\n    \"compilerOptions\": {\n        ...\n        \"types\": [\"vite-plugin-svgr/client\"]\n    },\n    ...\n    \"include\": [\"src\", \"custom.d.ts\"]\n}\n```\n\n```text\n/// <reference types=\"vite-plugin-svgr/client\" />\n/// <reference types=\"vite/client\" />\n```\n\n```text\nvite-plugin-svgr\n```\n\n```text\n$ npm install @svgr/rollup\n```\n\n```text\nimport svgr from \"@svgr/rollup\";\nimport react from \"@vitejs/plugin-react\";\nimport { defineConfig } from \"vite\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react(), svgr()],\n});\n```\n\n```text\ndeclare module \"*.svg\" {\n  import React = require(\"react\");\n  export const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;\n  const src: string;\n  export default src;\n}\n```\n\n========================================\n\nComments:\n- Thank you this is only one from hundreds on SO, that worked for me.\n- @aegor You are welcome, glad it helped","metadata":{"transformedAt":"2026-08-18T18:33:46.404Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":141,"estimatedTokens":699}}168{"id":"stack-75044874","source":"stackoverflow","questionId":75044874,"title":"Why actions in SveltKit give \"Error: Cannot prerender pages with actions\"?","tags":["javascript","vite","sveltekit"],"text":"Title: Why actions in SveltKit give \"Error: Cannot prerender pages with actions\"?\nTags: javascript, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a SvelteKit application, just following the example from the docs https://learn.svelte.dev/tutorial/named-form-actions, the problem is that everything works until I try to write an action:\n\nat: `+page.server.js`\n\n```\nexport const actions = {\n default: async () => {\n console.log('test')\n }\n};\n```\n\nvite immediately fails with:\n\"Cannot prerender pages with actions\"\n\n```\nError: Cannot prerender pages with actions\n at render_page (file:///mydir/node_modules/@sveltejs/kit/src/runtime/server/page/index.js:87:11)\n at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n at async resolve (file:///mydir/node_modules/@sveltejs/kit/src/runtime/server/index.js:356:17)\n at async respond (file:///mydir/node_modules/@sveltejs/kit/src/runtime/server/index.js:229:20)\n at async file:///mydir/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js:444:22\n```\n\nProbably I'm missing some configuration or forgot some basics, any idea?\n\n========================================\n\nCode:\n```text\nexport const actions = {\n    default: async () => {\n        console.log('test')\n    }\n};\n```\n\n```text\nError: Cannot prerender pages with actions\n    at render_page (file:///mydir/node_modules/@sveltejs/kit/src/runtime/server/page/index.js:87:11)\n    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n    at async resolve (file:///mydir/node_modules/@sveltejs/kit/src/runtime/server/index.js:356:17)\n    at async respond (file:///mydir/node_modules/@sveltejs/kit/src/runtime/server/index.js:229:20)\n    at async file:///mydir/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js:444:22\n```\n\n```text\n+page.server.js\n```\n\n```js\nexport const prerender = false;\n```\n\n```text\n+page.ts\n```\n\n========================================\n\nComments:\n- Thanks, i just missed to switch \"export const prerender = false;\" in +page.ts.","metadata":{"transformedAt":"2026-08-18T18:33:46.404Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":67,"estimatedTokens":503}}169{"id":"stack-69481783","source":"stackoverflow","questionId":69481783,"title":"HTTP requests stuck in Pending state when using Vite","tags":["vue.js","google-chrome","chromium","vite"],"text":"Title: HTTP requests stuck in Pending state when using Vite\nTags: vue.js, google-chrome, chromium, vite\nSource: Stack Overflow\n\nQuestion:\nI have a rather large Vue 3 application (~550 components). It takes two minutes just to run `vue-cli-service serve` and around 20 seconds to re-build it after each change. Hot reload stopped working a long time ago so it always needs to be refreshed in the browser even after a small style change. Moreover, the app is still not finished and it will probably get 2-3 times this big in the next year so it will probably be even worse.\n\nBecause of these problems, I've decided to migrate it from Vue CLI to Vite. I have already resolved a lot of problems and the app seems to work with Vite now with so much better loading times.\n\nHowever, it sometimes gets stuck when I start a dev server (`vite` command) and open it in a browser. The page keeps loading and I can see a lot of pending requests in the Network tab of Chrome DevTools. There's nothing special in the output of `vite --debug` and running `vite --force` doesn't help either.\n\nhttps://i.sstatic.net/6L9Im.png\n\nWhen this problem occurs, the browser always loads a lot of modules (~900) and then it gets stuck on 10-20 modules. The status of all these HTTP requests is simply `Pending` and they never finish. There are no errors in the browser or on the command line.\n\nI don't think any particular file causes this. Maybe the problem is in my deeply nested folder structure with a lot of re-exports using `index.ts` file on each level. It mostly gets stuck on my own modules but I've also seen cases when it was waiting for a module of some external library.\n\nHas anybody experienced a similar problem? How did you solve it?\n\n**EDIT:** I have discovered that this issue only occurs in Chromium-based browsers (Google Chrome, Brave, etc.) on Linux. It works without any problems in Chrome on MacOS and Windows as well as in other browsers (Firefox, GNOME Web, etc.) on Linux.\n\n========================================\n\nTop Answer:\nin my case, I'm using laravel with vite and I had the same issue multiple time, couldn't figure out why or how to fix. Which is frustrating spending so much time trying to figure out the issue, some times it works by it self after hours and I ignore the issue and continuo with developing the app.\n\nToday, I might found that it's a network related issue or misconfiguration. Because as soon as I turned Airplane mode ON on `Windows 11`, turned it back off, it worked and everything loading fine as it supposed to.\n\n========================================\n\nCode:\n```text\nvue-cli-service serve\n```\n\n```text\nvite\n```\n\n```text\nvite --debug\n```\n\n```text\nvite --force\n```\n\n```text\nPending\n```\n\n```text\nindex.ts\n```\n\n```text\nDefaultLimitNOFILE=65536\n```\n\n```text\n/etc/systemd/system.conf\n```\n\n```text\n/etc/systemd/user.conf\n```\n\n```text\nWindows 11\n```\n\n========================================\n\nComments:\n- Can you a link to a reproduction?\n- I can't really the source of code of this project. And I doubt I would be able to reproduce it if I created another project from scratch. But I can try.\n- I've realized that this issue only occurs in Chromium-based browser. My application works without any problems in Firefox. I was able to create a reproducer and I also reported a bug in Vite.\n- It's not reproducible in macOS. I see you're using Manjaro Linux, so it might be a problem only with Chromium-based browsers in that OS.\n- This is also reproducible on Ubuntu 21.04 (Chrome browser) if you try setting up github.com/directus/directus in your local","metadata":{"transformedAt":"2026-08-18T18:33:46.405Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":79,"estimatedTokens":894}}170{"id":"stack-70980379","source":"stackoverflow","questionId":70980379,"title":"SvelteKit(ViteJS) + TailwindCSS not hot reloading components","tags":["tailwind-css","svelte","vite","sveltekit"],"text":"Title: SvelteKit(ViteJS) + TailwindCSS not hot reloading components\nTags: tailwind-css, svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm trying to code an app using TailwindCSS and SvelteKit, which uses ViteJS under the hood, and while coding I realized that my *Header* component that is inside `./src/components/common/Header.svelte` was not **hot reloading** on changes. No matter how big or small the change to the component, Svelte would not display them until I terminated script in the console and re-ran `npm run dev`.\n\nThe normal behaviour would be that the whole page updated **WITH** changes to the components other than pages.\n\n*Note that adding and removing changes to any routes the changes are instantly visible but the components stay the same.*\n\nThis issue got quite annoying after some time and I tried finding the fix in TailwindCSS and in the `svelte.config.js` (Not a .cjs file in Svelte-Kit) file.\n\nAfter searching for a ton of answers I could not find anything that worked.\n\nThis behaviour is quite weird since in the other projects that I work on that use this same architecture of TailwindCSS and Svelte-kit the HMR works like a charm.\n\nHere is the code for my `Header.svelte` file and the `__layout.svelte`\n\n***Header.svelte***\n\n```\n\n \n \n \n \n \n- Home\n \n- About\n \n- Contact\n \n \n- Random Change\n \n \n\n```\n\n**__layout.svelte**\n\n```\n\n import '../css/tailwind.css';\n import Header from '../components/common/Header.svelte';\n\n```\n\nalso my config files:\n\n***tailwind.config.cjs***\n\n```\nmodule.exports = {\n content: ['./src/**/*.svelte', './src/app.html'],\n plugins: []\n};\n```\n\n***svelte.config.js***\n\n```\nimport preprocess from 'svelte-preprocess';\nimport path from 'path';\n\n// @type {import('@sveltejs/kit').Config\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: preprocess(),\n\n kit: {\n vite: {\n resolve: {\n alias: {\n '@components': path.resolve('./src/components'),\n '@routes': path.resolve('./src/routes'),\n '@utils': path.resolve('./src/utils'),\n '@data': path.resolve('./src/data')\n }\n }\n }\n }\n};\n\nexport default config;\n```\n\n========================================\n\nCode:\n```html\n<script>\n</script>\n\n<header>\n    <!-- TEST HEADER -->\n    <nav>\n        <ul class=\"flex gap-5 bg-red-500\">\n            <!--These classes are tests and won't change the appearance of the Header unless I restart the script-->\n            <li><a href=\"/\">Home</a></li>\n            <li><a href=\"/about\">About</a></li>\n            <li><a href=\"/contact\">Contact</a></li>\n            <!--Other random change that won't update-->\n            <li>Random Change</li>\n        </ul>\n    </nav>\n</header>\n```\n\n```html\n<script>\n    import '../css/tailwind.css';\n    import Header from '../components/common/Header.svelte';\n</script>\n\n<Header />\n<slot />\n```\n\n```js\nmodule.exports = {\n    content: ['./src/**/*.svelte', './src/app.html'],\n    plugins: []\n};\n```\n\n```js\nimport preprocess from 'svelte-preprocess';\nimport path from 'path';\n\n\n// @type {import('@sveltejs/kit').Config\nconst config = {\n    // Consult https://github.com/sveltejs/svelte-preprocess\n    // for more information about preprocessors\n    preprocess: preprocess(),\n\n    kit: {\n        vite: {\n            resolve: {\n                alias: {\n                    '@components': path.resolve('./src/components'),\n                    '@routes': path.resolve('./src/routes'),\n                    '@utils': path.resolve('./src/utils'),\n                    '@data': path.resolve('./src/data')\n                }\n            }\n        }\n    }\n};\n\nexport default config;\n```\n\n```text\n./src/components/common/Header.svelte\n```\n\n```text\nnpm run dev\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nHeader.svelte\n```\n\n```text\n__layout.svelte\n```\n\n========================================\n\nComments:\n- I know this is unhelpful, but I put all this code into a SvelteKit project with Tailwind configured and HMR worked fine in `Header.svelte`. Perhaps you could isolate the offending code by starting with a fresh SvelteKit project and seeing if HMR works, then install Tailwind, then make the changes in `svelte.config.js`—something is not right but I don't think it is included in what you posted here.\n- Yeah seems to work. That's odd. I'll have to take a look at my dependencies.\n- I have the same problem. I work with Svelte (not SvelteKit), Tailwind and Vite. Right now I force a restart with \"vite-plugin-restart\"\n- Do you have any updates on that problem? I was not able to solve this. Somewhere else here on Stackoverflow I saw that movin the svelte plugin in the vite config to end helps and it does, but not fully.\n- @Woww Unfortunately I still haven't found the cause of this problem. I solved it by simply creating a new SvelteKit skeleton project and starting from there.\n- I found it happens when the component is outside the routes folder. Probably Vite is not tracking folders outside routes folder.\n- This issue is still valid with the current version of SvelteKit. All of my components are inside the routes folder, none of my import paths use uppercase letters, and I'm not even using a layout file yet.\n- Amazingly, I can also reproduce this with `SvelteKit v1.0.0-next.350`. If the case is not correct in the import path, the module will load and display but the hot reloading does not work. Good catch!","metadata":{"transformedAt":"2026-08-18T18:33:46.405Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":188,"estimatedTokens":1341}}171{"id":"stack-73518294","source":"stackoverflow","questionId":73518294,"title":"vite: Adding static assets(with cache busting) to the build","tags":["vue.js","webpack","vite","http-caching","esbuild"],"text":"Title: vite: Adding static assets(with cache busting) to the build\nTags: vue.js, webpack, vite, http-caching, esbuild\nSource: Stack Overflow\n\nQuestion:\nI have large static files which should be busted with a hash for HTTP-caching. If I put them into the `public` directory, vite only copies them without appending a hash to the filenames. If I put them into the `assets` directory, vite ignores them, because they are not referenced directly from code, but loaded via XHR requests.\nThe directory structure is pretty standard:\n\n```\n/\n├─ src/\n│ ├─ assets/\n│ │ ├─ locales/\n│ │ │ ├─ en.json\n│ │ │ ├─ de.json\n│ │ │ ├─ ru.json\n│ ├─ main.js\n├─ public/\n├─ dist/\n├─ index.html\n```\n\nHow do I tell vite to copy those files with hash added to filenames and how do I get the resulting filenames to use them in XHR requests?\n\n========================================\n\nCode:\n```text\n/\n├─ src/\n│  ├─ assets/\n│  │  ├─ locales/\n│  │  │  ├─ en.json\n│  │  │  ├─ de.json\n│  │  │  ├─ ru.json\n│  ├─ main.js\n├─ public/\n├─ dist/\n├─ index.html\n```\n\n```text\npublic\n```\n\n```text\nassets\n```\n\n```js\n// BEFORE:\n// fetch('@/assets/locales/en.json').then(res => res.json()).then(json => /*...*/)\n\n// AFTER:                                   👇\nimport enUrl from '@/assets/locales/en.json?url'\nfetch(enUrl).then(res => res.json()).then(json => /*...*/)\n```\n\n```js\nasync function loadLocales() {\n  const localeFiles = await import.meta.glob('@/assets/locales/*.json', { as: 'url', eager: true })\n\n  // get basename of file from path\n  const basename = s => s.split('/').at(-1).split('.').at(0)\n\n  // create map of locale name to file -> { en: '/src/assets/locales/en-abc123.json' }\n  const resolvedUrls = {}\n  for (const [key, filePath] of Object.entries(localeFiles)) {\n    resolvedUrls[basename(key)] = filePath\n  }\n  return resolvedUrls\n}\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  build: {\n    assetsInlineLimit: 0,\n  },\n})\n```\n\n```js\n// vite.config.js\nimport { normalizePath, defineConfig } from 'vite'\n\nexport default defineConfig({\n  build: {\n    rollupOptions: {\n      output: {\n        assetFileNames(assetInfo) {\n         // output src/assets/locales/*.json files to dist/locales\n          const pathToFile = normalizePath(assetInfo.name)\n          if (/\\/src\\/assets\\/locales\\/.*\\.json$/.test(pathToFile)) {\n            return 'locales/[name]-[hash].json'\n          }\n\n          return 'assets/[name]-[hash][extname]'\n        },\n      },\n    },\n  },\n})\n```\n\n```text\nurl\n```\n\n```text\n.json\n```\n\n```text\nimport.meta.glob\n```\n\n```text\nbuild.assetsInlineLimit\n```\n\n```text\n0\n```\n\n```text\ndist/locales\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.405Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":131,"estimatedTokens":658}}172{"id":"stack-76881057","source":"stackoverflow","questionId":76881057,"title":"Vite reloading full page on every change","tags":["javascript","reactjs","vite"],"text":"Title: Vite reloading full page on every change\nTags: javascript, reactjs, vite\nSource: Stack Overflow\n\nQuestion:\nOn the newer version of vite, it was causing full page reload even on all the changes, wheather i change a text or remove a heading tag. Adding **import.meta.hot.accept()** in my index.js file fixed the issue but it caused the build to fail **causing the error:**\n\n```\nindex-f28df0af.js:1195 Uncaught TypeError: Cannot read properties of undefined (reading 'accept')\n at index-f28df0af.js:1195:82439\n at index-f28df0af.js:1:23\n at index-f28df0af.js:1195:82709\n```\n\nOn every change the vite compiler says **Full page reload**, instead of doing a **HMR update**. On previous version of vite 3.0.*, i was not getting full page reload and HMR update was working fine, after updating to the latest version I started encountering this full page reload, making the development experience slow and worse.\n\npackage.json file\n\n```\n{\n \"name\": \"Lala-Intl\",\n \"homepage\": \"http://lalaintltravel.pk/\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"dependencies\": {\n \"@fortawesome/fontawesome-svg-core\": \"^6.2.0\",\n \"@fortawesome/free-regular-svg-icons\": \"^6.2.0\",\n \"@fortawesome/free-solid-svg-icons\": \"^6.2.0\",\n \"@fortawesome/react-fontawesome\": \"^0.2.0\",\n \"@mui/icons-material\": \"^5.14.3\",\n \"@mui/x-date-pickers-pro\": \"^6.6.0\",\n \"@testing-library/jest-dom\": \"^5.16.5\",\n \"@testing-library/react\": \"^13.4.0\",\n \"@testing-library/user-event\": \"^13.5.0\",\n \"@vitejs/plugin-react\": \"^4.0.4\",\n \"antd\": \"^5.8.1\",\n \"axios\": \"^0.27.2\",\n \"jquery\": \"^3.6.1\",\n \"mdb-react-ui-kit\": \"^6.1.0\",\n \"moment\": \"^2.29.4\",\n \"pickadate\": \"^3.6.4\",\n \"react\": \"^18.2.0\",\n \"react-bootstrap\": \"^2.5.0\",\n \"react-date-range\": \"^1.4.0\",\n \"react-datepicker\": \"^4.12.0\",\n \"react-dom\": \"^18.2.0\",\n \"react-helmet\": \"^6.1.0\",\n \"react-multi-carousel\": \"^2.8.2\",\n \"react-redux\": \"^8.1.2\",\n \"react-router-dom\": \"^6.13.0\",\n \"react-select\": \"^5.7.4\",\n \"react-spinners\": \"^0.13.8\",\n \"redux\": \"^4.2.1\",\n \"redux-persist\": \"^6.0.0\",\n \"redux-thunk\": \"^2.4.2\",\n \"usehooks-ts\": \"^2.7.0\",\n \"vite\": \"^4.4.8\",\n \"vite-plugin-svgr\": \"^3.2.0\",\n \"web-vitals\": \"^2.1.4\"\n },\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"serve\": \"vite preview\"\n },\n \"eslintConfig\": {\n \"extends\": [\n \"react-app\",\n \"react-app/jest\"\n ]\n },\n \"browserslist\": {\n \"production\": [\n \">0.2%\",\n \"not dead\",\n \"not op_mini all\"\n ],\n \"development\": [\n \"last 1 chrome version\",\n \"last 1 firefox version\",\n \"last 1 safari version\"\n ]\n }\n }\n```\n\nIndex.js\n\n```\nimport React from \"react\";\n import ReactDOM from \"react-dom/client\";\n import { Provider } from \"react-redux\";\n import { store, persistor } from \"./store\";\n import { PersistGate } from \"redux-persist/integration/react\";\n import { BrowserRouter } from \"react-router-dom\";\n\n // meta.hot.accept is required for HMR update\n // import.meta.hot.accept();\n\n import \"./index.css\";\n import App from \"./App\";\n\n ReactDOM.createRoot(document.getElementById(\"root\")).render(\n \n \n \n \n \n \n \n \n \n \n \n );\n```\n\n========================================\n\nTop Answer:\n```\n\"assumeChangesOnlyAffectDirectDependencies\": true,\n```\n\nadded in tsconfig.node.json and it worked\n\nlearn more at https://www.typescriptlang.org/tsconfig/#assumeChangesOnlyAffectDirectDependencies\n\n========================================\n\nCode:\n```text\nindex-f28df0af.js:1195  Uncaught TypeError: Cannot read properties of undefined (reading 'accept')\n    at index-f28df0af.js:1195:82439\n    at index-f28df0af.js:1:23\n    at index-f28df0af.js:1195:82709\n```\n\n```text\n{\n    \"name\": \"Lala-Intl\",\n    \"homepage\": \"http://lalaintltravel.pk/\",\n    \"version\": \"0.1.0\",\n    \"private\": true,\n    \"dependencies\": {\n        \"@fortawesome/fontawesome-svg-core\": \"^6.2.0\",\n        \"@fortawesome/free-regular-svg-icons\": \"^6.2.0\",\n        \"@fortawesome/free-solid-svg-icons\": \"^6.2.0\",\n        \"@fortawesome/react-fontawesome\": \"^0.2.0\",\n        \"@mui/icons-material\": \"^5.14.3\",\n        \"@mui/x-date-pickers-pro\": \"^6.6.0\",\n        \"@testing-library/jest-dom\": \"^5.16.5\",\n        \"@testing-library/react\": \"^13.4.0\",\n        \"@testing-library/user-event\": \"^13.5.0\",\n        \"@vitejs/plugin-react\": \"^4.0.4\",\n        \"antd\": \"^5.8.1\",\n        \"axios\": \"^0.27.2\",\n        \"jquery\": \"^3.6.1\",\n        \"mdb-react-ui-kit\": \"^6.1.0\",\n        \"moment\": \"^2.29.4\",\n        \"pickadate\": \"^3.6.4\",\n        \"react\": \"^18.2.0\",\n        \"react-bootstrap\": \"^2.5.0\",\n        \"react-date-range\": \"^1.4.0\",\n        \"react-datepicker\": \"^4.12.0\",\n        \"react-dom\": \"^18.2.0\",\n        \"react-helmet\": \"^6.1.0\",\n        \"react-multi-carousel\": \"^2.8.2\",\n        \"react-redux\": \"^8.1.2\",\n        \"react-router-dom\": \"^6.13.0\",\n        \"react-select\": \"^5.7.4\",\n        \"react-spinners\": \"^0.13.8\",\n        \"redux\": \"^4.2.1\",\n        \"redux-persist\": \"^6.0.0\",\n        \"redux-thunk\": \"^2.4.2\",\n        \"usehooks-ts\": \"^2.7.0\",\n        \"vite\": \"^4.4.8\",\n        \"vite-plugin-svgr\": \"^3.2.0\",\n        \"web-vitals\": \"^2.1.4\"\n    },\n    \"scripts\": {\n        \"dev\": \"vite\",\n        \"build\": \"vite build\",\n        \"serve\": \"vite preview\"\n    },\n    \"eslintConfig\": {\n        \"extends\": [\n            \"react-app\",\n            \"react-app/jest\"\n        ]\n    },\n    \"browserslist\": {\n        \"production\": [\n            \">0.2%\",\n            \"not dead\",\n            \"not op_mini all\"\n        ],\n        \"development\": [\n            \"last 1 chrome version\",\n            \"last 1 firefox version\",\n            \"last 1 safari version\"\n           ]\n        }\n    }\n```\n\n```text\nimport React from \"react\";\n    import ReactDOM from \"react-dom/client\";\n    import { Provider } from \"react-redux\";\n    import { store, persistor } from \"./store\";\n    import { PersistGate } from \"redux-persist/integration/react\";\n    import { BrowserRouter } from \"react-router-dom\";\n\n    // meta.hot.accept is required for HMR update\n    // import.meta.hot.accept();\n\n    import \"./index.css\";\n    import App from \"./App\";\n\n    ReactDOM.createRoot(document.getElementById(\"root\")).render(\n        <Provider store={store}>\n            <PersistGate loading={null} persistor={persistor}>\n                <React.StrictMode>\n                    <React.StrictMode>\n                        <BrowserRouter basename=\"/\">\n                            <App />\n                        </BrowserRouter>\n                    </React.StrictMode>\n                </React.StrictMode>\n            </PersistGate>\n        </Provider>\n     );\n```\n\n```text\nif (import.meta.hot) {\n    import.meta.hot.accept();\n}\n```\n\n```text\n\"assumeChangesOnlyAffectDirectDependencies\": true,\n```\n\n========================================\n\nComments:\n- Seems the question is not related to typescript. (Tag is `javascript`)\n- This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review","metadata":{"transformedAt":"2026-08-18T18:33:46.405Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":250,"estimatedTokens":1698}}173{"id":"stack-74587962","source":"stackoverflow","questionId":74587962,"title":"Using require in vite","tags":["javascript","node.js","vite"],"text":"Title: Using require in vite\nTags: javascript, node.js, vite\nSource: Stack Overflow\n\nQuestion:\nI try to use import(xxx) in vite to replace require(xxx), but import(xxx) will return a promise(async), how can I write like require(xxx) in vite?\n\n```\nlet lang = require(`./${path}.json`)\n```\n\nCode Image\n\nI try to change it to import(`./${path}.json`) but it will return a Promise, so that I can't get the index with file.\n\n========================================\n\nTop Answer:\nThis question is solved, just install package `vite-require` than require is work on vite.\n\n========================================\n\nCode:\n```js\nlet lang = require(`./${path}.json`)\n```\n\n```text\nconst lang = await import(`./${path}.json`, { assert: { type: \"json\" } })\n```\n\n```text\nvite-require\n```\n\n========================================\n\nComments:\n- Inside the package.json file add a line `\"type\": \"commonjs\"` and see tell me if its working\n- did yo find final resolution for this ?","metadata":{"transformedAt":"2026-08-18T18:33:46.405Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":40,"estimatedTokens":241}}174{"id":"stack-74359277","source":"stackoverflow","questionId":74359277,"title":"Running vite build using tsconfig.build.ts","tags":["typescript","build","config","vite"],"text":"Title: Running vite build using tsconfig.build.ts\nTags: typescript, build, config, vite\nSource: Stack Overflow\n\nQuestion:\n### Question\n\nIs there a way to specify which `tsconfig` file to use when running the `vite build` command?\n\n### Problem\n\nI am building a component library with Vite and TypeScript. My test suite is running the new Cypress component testing feature and so I've included `\"src/**/*.cy.ts\"` in my `tsconfig.json`. TypeScript needed some type definitions which I put in `cypress/support/components.d.ts`, and included `\"cypress/**/*.ts\"` in my `tsconfig.json`. Everything is working as it should, but `cypress/support/components.d.ts` is included in my `dist` directory on build.\n\nI've gone through the docs for both Vite and Rollup, but was unable to find a way to exclude Cypress when building. Now I want to simply have a `tsconfig.build.json` that extends `tsconfig.json`, but excludes all Cypress related files. The only thing left is to tell Vite that I want to use `tsconfig.build.json` during the build process.\n\nI imagine this would be done either through `vite.config.ts` or as a flag (`vite build --config tsconfig.build.json`).\n\nI made a `tsconfig.build.json`:\n\n```\n{\n \"extends\": \"./tsconfig.json\",\n \"exclude\": [\n \"node_modules\",\n \"cypress\"\n ]\n}\n```\n\nBut I'm not sure how to instruct Vite to use this config on build.\n\ntypescript@4.8.4\nvite@3.2.2\n\n========================================\n\nTop Answer:\nI ended up writing a tsconfig file swapping plugin to fit our needs and I believe it would be a workaround for your problem: https://github.com/alienfast/vite-plugin-tsconfig\n\n- allows a default `tsconfig.json`, in the end it will be put back in place\n\n- allows specifying `workspaces` for monorepo packages to be swapped at the same time as the root\n\nWe were dealing with failed CI storybook/vite builds only to learn that vite tries to discover the nearest `tsconfig.json` at the `package.json` level regardless if one exists. The readme explains more.\n\nOur use case: the `tsconfig.json` in our monorepos is setup for development with the use of project references and `paths`. We use `tsconfig.build.json` in our CI/production build scripts to build without path dependencies. Vite seems to be coded with no knowledge of a multi-environment type of use case.\n\nHopefully this kind of thing is considered in vite itself and this type of hack/plugin can be archived in the future.\n\n========================================\n\nCode:\n```json\n{\n  \"extends\": \"./tsconfig.json\",\n  \"exclude\": [\n    \"node_modules\",\n    \"cypress\"\n  ]\n}\n```\n\n```text\ntsconfig\n```\n\n```text\nvite build\n```\n\n```text\n\"src/**/*.cy.ts\"\n```\n\n```text\ntsconfig.json\n```\n\n```text\ncypress/support/components.d.ts\n```\n\n```text\n\"cypress/**/*.ts\"\n```\n\n```text\ntsconfig.json\n```\n\n```text\ncypress/support/components.d.ts\n```\n\n```text\ndist\n```\n\n```text\ntsconfig.build.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\ntsconfig.build.json\n```\n\n```text\nvite.config.ts\n```\n\n```text\nvite build --config tsconfig.build.json\n```\n\n```text\ntsconfig.build.json\n```\n\n```js\n// vite.config.ts\n\nimport vue from '@vitejs/plugin-vue'\nimport { defineConfig } from 'vite'\nimport dts from 'vite-plugin-dts'\n\nexport default defineConfig({\n  build: { ... },\n  plugins: [\n    vue(),\n    dts({\n      tsConfigFilePath: 'tsconfig.build.json',\n    }),\n  ],\n})\n```\n\n```js\n// vite.config.ts\n\nimport vue from '@vitejs/plugin-vue'\nimport { defineConfig } from 'vite'\nimport dts from 'vite-plugin-dts'\n\nexport default defineConfig({\n  build: { ... },\n  plugins: [\n    vue(),\n    dts({\n      exclude: [\n        'node_modules',\n        'cypress'\n      ],\n    }),\n  ],\n})\n```\n\n```text\nvite-plugin-dts\n```\n\n```text\nvite-plugin-dts\n```\n\n```text\ntsconfig.json\n```\n\n```text\ntsconfig.build.json\n```\n\n```text\n// tsconfig.build.json\n{\n  \"compilerOptions\": {\n   ...\n  },\n  \"include\": [\"src\"],\n  \"exclude\": [\"**/cypress/*\"],\n  \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\n```text\n\"scripts\":{\n  \"build\": \"tsc --project tsconfig.build.json && vite build -d\",\n}\n```\n\n```text\ntsc\n```\n\n```text\n--project\n```\n\n```text\npackage.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\nworkspaces\n```\n\n```text\ntsconfig.json\n```\n\n```text\npackage.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\npaths\n```\n\n```text\ntsconfig.build.json\n```\n\n========================================\n\nComments:\n- doesnt work for me...\n- works well, but using the latest `\"vite-plugin-dts\": \"^4.2.1\"` the syntax now is `tsconfigPath: 'tsconfig.build.json',`\n- Vite uses esbuild to tsc?","metadata":{"transformedAt":"2026-08-18T18:33:46.405Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":241,"estimatedTokens":1124}}175{"id":"stack-70591125","source":"stackoverflow","questionId":70591125,"title":"Replacement for require in Vuejs 3 with Vite for image array","tags":["javascript","vue.js","vuejs3","vite"],"text":"Title: Replacement for require in Vuejs 3 with Vite for image array\nTags: javascript, vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI'm currently switching to vite with vuejs and have the following problem:\n\nI have a component in debugging that displays images from a folder:\n\n```\nimageArray: [\n require (\"../ assets / dummies / Mission -1.jpg\"),\n require (\"../ assets / dummies / Mission -2.jpg\"),\n require (\"../ assets / dummies / Mission -3.jpg\"),\n require (\"../ assets / dummies / Mission -4.jpg\")\n]\n```\n\nin the component is the following div\n\n```\n \n```\n\nthere is then the following dynamic class with de rich simple that can scroll through the images.\n\n```\ncomputed: {\n bgClass: function () {\n \n return {\n backgroundImage: 'url (' + this.imageArray [this.imagePos] + ')',\n ...\n }\n }\n }\n```\n\nRequired is not available in Vite, and I would not like to convert the old vue2 components to the vue3 composition API.\n\nhow can I simply load the images into an array and scroll through the component.\n\n========================================\n\nTop Answer:\nI started using Vite and had the same problem. I read other people's advice and experimented. Here's an example using v-for, in case it helps others.\n\n```\n\n \n \n \n\n```\n\n```\n\nexport default {\n setup() {\n const imageUrl = new URL(\"../assets/images/\", import.meta.url).href;\n return { imageUrl };\n },\n props: {\n items: {\n type: Object,\n default: function() {\n return {};\n },\n },\n },\n};\n\n```\n\n========================================\n\nCode:\n```text\nimageArray: [\n     require (\"../ assets / dummies / Mission -1.jpg\"),\n     require (\"../ assets / dummies / Mission -2.jpg\"),\n     require (\"../ assets / dummies / Mission -3.jpg\"),\n     require (\"../ assets / dummies / Mission -4.jpg\")\n]\n```\n\n```text\n<div: class = \"bgClass\" v-if = \"isDebug () == true\"> </div>\n```\n\n```text\ncomputed: {\n     bgClass: function () {\n      \n       return {\n           backgroundImage: 'url (' + this.imageArray [this.imagePos] + ')',\n           ...\n       }\n     }\n   }\n```\n\n```text\nconst useImage = ((url) => {\n  return new URL(`/src/${url}`, import.meta.url).href;\n});\n```\n\n```text\napp.config.globalProperties.$image = useImage;\n```\n\n```text\n$image(imageUrl)\n```\n\n```html\n<template>\n    <div\n        v-for=\"item in items\"\n        :key=\"item.id\"\n    >\n        <img\n            :src=\"`${imageUrl}${item.image}.jpg`\"\n            :alt=\"item.description\"\n        >\n    </div>\n</template>\n```\n\n```js\n<script>\nexport default {\n    setup() {\n        const imageUrl = new URL(\"../assets/images/\", import.meta.url).href;\n        return { imageUrl };\n    },\n    props: {\n        items: {\n            type: Object,\n            default: function() {\n                return {};\n            },\n        },\n    },\n};\n</script>\n```\n\n========================================\n\nComments:\n- Tried `import()`instead?\n- do you need to add a build target to es2020? still cant get this method to work.\n- This solution works, but not for Nuxt3. After the hydration step the Nuxt3 if SSR is enabled. In this case you have to query the image element and update the `src` attribute manually.\n- I tried multiple versions of this, for dynamic imports, but the output is","metadata":{"transformedAt":"2026-08-18T18:33:46.405Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":156,"estimatedTokens":795}}176{"id":"stack-74723484","source":"stackoverflow","questionId":74723484,"title":"How to get Vite to not import/bundle an external dependency","tags":["typescript","vite"],"text":"Title: How to get Vite to not import/bundle an external dependency\nTags: typescript, vite\nSource: Stack Overflow\n\nQuestion:\nI have several libraries that I am forced to include via `` tags. I would still, however, like to use the equivalent import statements in my .ts for those external libraries, so that I get proper typing. How do I tell Vite to not bundle those particular imports, and expunge the import statements for those?\n\n========================================\n\nTop Answer:\nIf you only need the types from an `import`, then you should use `import type` instead. That was introduced in Typescript 3.8. Importing only the types should prevent the bundling of any actual code.\n\n```\nimport type { Counter } from './Counter';\n\ndeclare global {\n interface Window {\n ExternalCounter: typeof Counter;\n }\n}\n\n// Then `ExternalCounter` will be a fully typed interface to the Counter class\n```\n\nHere is a full example on StackBlitz. I used a script tag and then imported the class definition from a `.ts` file and used it.\n\n========================================\n\nCode:\n```text\n<script>\n```\n\n```text\nnpm install --save-dev rollup-plugin-hypothetical\nnpm install --save-dev @stadtlandnetz/rollup-plugin-postprocess\n```\n\n```text\n// vite.config.js\n\nimport hypothetical from 'rollup-plugin-hypothetical';\nimport postprocess from '@stadtlandnetz/rollup-plugin-postprocess';\n\nexport default {\n    build: {\n        rollupOptions: {\n            external: ['masonry-layout', 'typeahead-standalone', 'video.js']\n        }\n    },\n    plugins: [\n        hypothetical({\n            allowFallthrough: true,\n            files: {\n                'typeahead-standalone/': ``,\n                'masonry-layout/': ``,\n                'video.js/': ``\n            }\n        }),\n        postprocess([\n            [/import[^;]*/, '']\n        ])\n    ]\n}\n```\n\n```text\nimport type { Counter } from './Counter';\n\ndeclare global {\n  interface Window {\n    ExternalCounter: typeof Counter;\n  }\n}\n\n// Then `ExternalCounter` will be a fully typed interface to the Counter class\n```\n\n```text\nimport\n```\n\n```text\nimport type\n```\n\n```text\n.ts\n```\n\n========================================\n\nComments:\n- Thanks for this useful link and explanation. It seems like the ideal thing might be to pre-process the files and simply remove the import. This would make the ‘hypothetical’ step unnecessary. Though I’m not sure if a vite plug-in exists to do that.\n- While this is true, it doesn't help you with accessing functions or classes declared in the module, which would very likely be necessary in this scenario.\n- Not true. All you need is a handle to the class object or instance that has been cast to the correct type, as imported using `import type` (cast using the `as` operator). Then, everything will work.\n- I've added a StackBlitz example in case what I'm saying was not clear\n- That's actually my point. I currently use the same gymnastics that you do for wrangling in classes and functions. What I was saying is that import type alone does not solve the problem. Adding this cruft would be unnecessary if the TypeScript folks actually cared about these fairly common use cases. Also, in your StackBlitz, ExternalCounter is still not recognized by TS as a known class -- it has the red squiggly under it (though in true JavaScript fashion, it still runs).\n- Thanks for pointing out the error. I fixed the squiggly. The reason I still prefer my solution is that it is based on code only and would work with any build system. It doesn't require mucking with the Vite config.","metadata":{"transformedAt":"2026-08-18T18:33:46.405Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":99,"estimatedTokens":887}}177{"id":"stack-76015181","source":"stackoverflow","questionId":76015181,"title":"The Yarn Plug'n'Play manifest forbids importing \"XYZ\" here because it's not listed as a dependency of this package","tags":["yarnpkg","vite"],"text":"Title: The Yarn Plug'n'Play manifest forbids importing \"XYZ\" here because it's not listed as a dependency of this package\nTags: yarnpkg, vite\nSource: Stack Overflow\n\nQuestion:\nYarn 3.5 (stable) using ViteJS - I keep getting this same error for various third party packages. I'm lost on how to properly solve this. The message says I can mark \"react\" as external, 1) no docs on how to do that, and 2) that would remove it from the bundle which is definitely not a valid solution since my app runs on react.\n\nHow do I solve this?\n\n`yarn dev` - start start development\n\nyarn created `.yarn` folder, `.pnp.cjs`, `yarn.lock`, and `.pnpn.loader.mjs` files in the root of my repo that it maintains. I don't really have any control over how those things are generated/maintained.\n\n**package.json:**\n\n```\n...\n \"packageManager\": \"yarn@3.5.0\",\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"vite --config vite.config.ts\",\n \"build\": \"tsc && vite build\",\n \"preview\": \"vite preview --config vite.config.ts\"\n },\n \"dependencies\": {\n \"@apollo/client\": \"^3.7.10\",\n \"chroma-js\": \"^2.4.2\",\n \"graphql\": \"^16.6.0\",\n \"graphql-ws\": \"^5.12.0\",\n \"howler\": \"^2.2.3\",\n \"linq\": \"^4.0.1\",\n \"lodash.clonedeep\": \"^4.5.0\",\n \"luxon\": \"^3.3.0\",\n \"primeflex\": \"^3.3.0\",\n \"primeicons\": \"^6.0.1\",\n \"primereact\": \"^9.2.1\",\n \"quill\": \"^1.3.7\",\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\",\n \"react-router-dom\": \"^6.9.0\",\n \"react-use\": \"^17.4.0\",\n \"recoil\": \"^0.7.7\",\n \"recoil-sync\": \"^0.2.0\",\n \"uuid\": \"^9.0.0\"\n },\n \"devDependencies\": {\n \"@types/chroma-js\": \"^2\",\n \"@types/howler\": \"^2\",\n \"@types/jest\": \"^29.5.0\",\n \"@types/linq\": \"^2.2.33\",\n \"@types/lodash.clonedeep\": \"^4\",\n \"@types/luxon\": \"^3.2.0\",\n \"@types/node\": \"^18.15.11\",\n \"@types/quill\": \"^2.0.10\",\n \"@types/react\": \"^18.0.28\",\n \"@types/react-dom\": \"^18.0.11\",\n \"@types/uuid\": \"^9.0.1\",\n \"@vitejs/plugin-react-swc\": \"^3.0.0\",\n \"@yarnpkg/sdks\": \"^3.0.0-rc.40\",\n \"autoprefixer\": \"^10.4.14\",\n \"concurrently\": \"^7.6.0\",\n \"cross-env\": \"^7.0.3\",\n \"graphql-config\": \"^4.5.0\",\n \"graphql-tag\": \"^2.12.6\",\n \"jest\": \"^29.5.0\",\n \"postcss\": \"^8.4.21\",\n \"prettier\": \"2.8.6\",\n \"sass\": \"^1.60.0\",\n \"typescript\": \"^5.0.2\",\n \"vite\": \"^4.2.0\"\n }\n```\n\n**.yarnrc.yml:**\n\n```\nnodeLinker: pnp\n\nplugins:\n - path: .yarn/plugins/@yarnpkg/plugin-typescript.cjs\n spec: \"@yarnpkg/plugin-typescript\"\n\nyarnPath: .yarn/releases/yarn-3.5.0.cjs\n```\n\n**`yarn dev` output:**\n\n```\nError: Build failed with 1 error:\n../../../.yarn/__virtual__/recoil-sync-virtual-1d8ed1cd8b/0/cache/recoil-sync-npm-0.2.0-8a627829eb-a0bd98acbc.zip/node_modules/recoil-sync/es/index.js:2:18: ERROR: Could not resolve \"react\"\n at failureErrorWithLog (F:\\git\\aperture\\.yarn\\unplugged\\esbuild-npm-0.17.13-538abc913d\\node_modules\\esbuild\\lib\\main.js:1636:15)\n at F:\\git\\aperture\\.yarn\\unplugged\\esbuild-npm-0.17.13-538abc913d\\node_modules\\esbuild\\lib\\main.js:1048:25\n at runOnEndCallbacks (F:\\git\\aperture\\.yarn\\unplugged\\esbuild-npm-0.17.13-538abc913d\\node_modules\\esbuild\\lib\\main.js:1471:45)\n at buildResponseToResult (F:\\git\\aperture\\.yarn\\unplugged\\esbuild-npm-0.17.13-538abc913d\\node_modules\\esbuild\\lib\\main.js:1046:7)\n at F:\\git\\aperture\\.yarn\\unplugged\\esbuild-npm-0.17.13-538abc913d\\node_modules\\esbuild\\lib\\main.js:1058:9\n at new Promise ()\n at requestCallbacks.on-end (F:\\git\\aperture\\.yarn\\unplugged\\esbuild-npm-0.17.13-538abc913d\\node_modules\\esbuild\\lib\\main.js:1057:54)\n at handleRequest (F:\\git\\aperture\\.yarn\\unplugged\\esbuild-npm-0.17.13-538abc913d\\node_modules\\esbuild\\lib\\main.js:723:19)\n at handleIncomingPacket (F:\\git\\aperture\\.yarn\\unplugged\\esbuild-npm-0.17.13-538abc913d\\node_modules\\esbuild\\lib\\main.js:745:7)\n at Socket.readFromStdout (F:\\git\\aperture\\.yarn\\unplugged\\esbuild-npm-0.17.13-538abc913d\\node_modules\\esbuild\\lib\\main.js:673:7) {\n errors: [\n {\n detail: undefined,\n id: '',\n location: {\n column: 18,\n file: '../../../.yarn/__virtual__/recoil-sync-virtual-1d8ed1cd8b/0/cache/recoil-sync-npm-0.2.0-8a627829eb-a0bd98acbc.zip/node_modules/recoil-sync/es/index.js',\n length: 7,\n line: 2,\n lineText: \"import react from 'react';\",\n namespace: '',\n suggestion: ''\n },\n notes: [\n {\n location: {\n column: 33,\n file: '../../../.pnp.cjs',\n length: 504,\n line: 10028,\n lineText: ' \"packageDependencies\": [\\\\',\n namespace: '',\n suggestion: ''\n },\n text: `The Yarn Plug'n'Play manifest forbids importing \"react\" here because it's not listed as a dependency of this package:`\n },\n {\n location: null,\n text: 'You can mark the path \"react\" as external to exclude it from the bundle, which will remove this error.'\n }\n ],\n pluginName: '',\n text: 'Could not resolve \"react\"'\n }\n ],\n warnings: []\n}\n```\n\n========================================\n\nTop Answer:\nThis error comes from the esbuild resolver, not Yarn. I ran into this where the first step didn't quite work, even after downgrading to Yarn V1.\n\nFirst, `yarn -v` to see what version you are on then:\n\n### Yarn 2/3+\n\n```\nrm -rf node_modules .yarn .pnp.* yarn.lock\n```\n\nIf you want to keep using pnp nodeLinker, Update `.yarnrc.yml` to include or change to loose:\n\n```\nnodeLinker: pnp\npnpMode: \"loose\"\n```\n\nOtherwise, if you'd rather go for the classic node_modules approach and forgo the pnp benefits, consider changing the nodeLinker to `node_modules`:\n\n```\nnodeLinker: node_modules\n```\n\nThen reinstall with `yarn install` and attempt to build again.\n\n### Yarn 1 or if the above does not work\n\nIf you are still running into this error, look in each of your upstream directories for .pnp.cjs files that may be picked up by Esbuild automatically.\n\nThis was my case where my app directory `~/projects/myApp` was clear of yarn files, but `~/projects/.pnp.cjs` is present in the directory above probably generated when I ran yarn accidentally in the wrong dir.\n\nHead back to your project directory and try to build again.\n\n========================================\n\nCode:\n```text\n...\n  \"packageManager\": \"yarn@3.5.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite --config vite.config.ts\",\n    \"build\": \"tsc && vite build\",\n    \"preview\": \"vite preview --config vite.config.ts\"\n  },\n  \"dependencies\": {\n    \"@apollo/client\": \"^3.7.10\",\n    \"chroma-js\": \"^2.4.2\",\n    \"graphql\": \"^16.6.0\",\n    \"graphql-ws\": \"^5.12.0\",\n    \"howler\": \"^2.2.3\",\n    \"linq\": \"^4.0.1\",\n    \"lodash.clonedeep\": \"^4.5.0\",\n    \"luxon\": \"^3.3.0\",\n    \"primeflex\": \"^3.3.0\",\n    \"primeicons\": \"^6.0.1\",\n    \"primereact\": \"^9.2.1\",\n    \"quill\": \"^1.3.7\",\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\",\n    \"react-router-dom\": \"^6.9.0\",\n    \"react-use\": \"^17.4.0\",\n    \"recoil\": \"^0.7.7\",\n    \"recoil-sync\": \"^0.2.0\",\n    \"uuid\": \"^9.0.0\"\n  },\n  \"devDependencies\": {\n    \"@types/chroma-js\": \"^2\",\n    \"@types/howler\": \"^2\",\n    \"@types/jest\": \"^29.5.0\",\n    \"@types/linq\": \"^2.2.33\",\n    \"@types/lodash.clonedeep\": \"^4\",\n    \"@types/luxon\": \"^3.2.0\",\n    \"@types/node\": \"^18.15.11\",\n    \"@types/quill\": \"^2.0.10\",\n    \"@types/react\": \"^18.0.28\",\n    \"@types/react-dom\": \"^18.0.11\",\n    \"@types/uuid\": \"^9.0.1\",\n    \"@vitejs/plugin-react-swc\": \"^3.0.0\",\n    \"@yarnpkg/sdks\": \"^3.0.0-rc.40\",\n    \"autoprefixer\": \"^10.4.14\",\n    \"concurrently\": \"^7.6.0\",\n    \"cross-env\": \"^7.0.3\",\n    \"graphql-config\": \"^4.5.0\",\n    \"graphql-tag\": \"^2.12.6\",\n    \"jest\": \"^29.5.0\",\n    \"postcss\": \"^8.4.21\",\n    \"prettier\": \"2.8.6\",\n    \"sass\": \"^1.60.0\",\n    \"typescript\": \"^5.0.2\",\n    \"vite\": \"^4.2.0\"\n  }\n```\n\n```text\nnodeLinker: pnp\n\nplugins:\n  - path: .yarn/plugins/@yarnpkg/plugin-typescript.cjs\n    spec: \"@yarnpkg/plugin-typescript\"\n\nyarnPath: .yarn/releases/yarn-3.5.0.cjs\n```\n\n```text\nError: Build failed with 1 error:\n../../../.yarn/__virtual__/recoil-sync-virtual-1d8ed1cd8b/0/cache/recoil-sync-npm-0.2.0-8a627829eb-a0bd98acbc.zip/node_modules/recoil-sync/es/index.js:2:18: ERROR: Could not resolve \"react\"\n    at failureErrorWithLog (F:\\git\\aperture\\.yarn\\unplugged\\esbuild-npm-0.17.13-538abc913d\\node_modules\\esbuild\\lib\\main.js:1636:15)\n    at F:\\git\\aperture\\.yarn\\unplugged\\esbuild-npm-0.17.13-538abc913d\\node_modules\\esbuild\\lib\\main.js:1048:25\n    at runOnEndCallbacks (F:\\git\\aperture\\.yarn\\unplugged\\esbuild-npm-0.17.13-538abc913d\\node_modules\\esbuild\\lib\\main.js:1471:45)\n    at buildResponseToResult (F:\\git\\aperture\\.yarn\\unplugged\\esbuild-npm-0.17.13-538abc913d\\node_modules\\esbuild\\lib\\main.js:1046:7)\n    at F:\\git\\aperture\\.yarn\\unplugged\\esbuild-npm-0.17.13-538abc913d\\node_modules\\esbuild\\lib\\main.js:1058:9\n    at new Promise (<anonymous>)\n    at requestCallbacks.on-end (F:\\git\\aperture\\.yarn\\unplugged\\esbuild-npm-0.17.13-538abc913d\\node_modules\\esbuild\\lib\\main.js:1057:54)\n    at handleRequest (F:\\git\\aperture\\.yarn\\unplugged\\esbuild-npm-0.17.13-538abc913d\\node_modules\\esbuild\\lib\\main.js:723:19)\n    at handleIncomingPacket (F:\\git\\aperture\\.yarn\\unplugged\\esbuild-npm-0.17.13-538abc913d\\node_modules\\esbuild\\lib\\main.js:745:7)\n    at Socket.readFromStdout (F:\\git\\aperture\\.yarn\\unplugged\\esbuild-npm-0.17.13-538abc913d\\node_modules\\esbuild\\lib\\main.js:673:7) {\n  errors: [\n    {\n      detail: undefined,\n      id: '',\n      location: {\n        column: 18,\n        file: '../../../.yarn/__virtual__/recoil-sync-virtual-1d8ed1cd8b/0/cache/recoil-sync-npm-0.2.0-8a627829eb-a0bd98acbc.zip/node_modules/recoil-sync/es/index.js',\n        length: 7,\n        line: 2,\n        lineText: \"import react from 'react';\",\n        namespace: '',\n        suggestion: ''\n      },\n      notes: [\n        {\n          location: {\n            column: 33,\n            file: '../../../.pnp.cjs',\n            length: 504,\n            line: 10028,\n            lineText: '          \"packageDependencies\": [\\\\',\n            namespace: '',\n            suggestion: ''\n          },\n          text: `The Yarn Plug'n'Play manifest forbids importing \"react\" here because it's not listed as a dependency of this package:`\n        },\n        {\n          location: null,\n          text: 'You can mark the path \"react\" as external to exclude it from the bundle, which will remove this error.'\n        }\n      ],\n      pluginName: '',\n      text: 'Could not resolve \"react\"'\n    }\n  ],\n  warnings: []\n}\n```\n\n```text\nyarn dev\n```\n\n```text\n.yarn\n```\n\n```text\n.pnp.cjs\n```\n\n```text\nyarn.lock\n```\n\n```text\n.pnpn.loader.mjs\n```\n\n```text\nyarn dev\n```\n\n```text\nnodeLinker: pnp\npnpMode: \"loose\"\n\nplugins:\n  - path: .yarn/plugins/@yarnpkg/plugin-typescript.cjs\n    spec: \"@yarnpkg/plugin-typescript\"\n\nyarnPath: .yarn/releases/yarn-3.5.0.cjs\n```\n\n```text\npnpMode\n```\n\n```text\n.yarnrc.yml\n```\n\n```text\nloose\n```\n\n```text\nyarn install\n```\n\n```text\nyarn dev\n```\n\n```text\n.yarnrc.yml:\n```\n\n```text\nrm -rf node_modules .yarn .pnp.* yarn.lock\n```\n\n```text\nnodeLinker: pnp\npnpMode: \"loose\"\n```\n\n```text\nnodeLinker: node_modules\n```\n\n```text\nyarn -v\n```\n\n```text\n.yarnrc.yml\n```\n\n```text\nnode_modules\n```\n\n```text\nyarn install\n```\n\n```text\n~/projects/myApp\n```\n\n```text\n~/projects/.pnp.cjs\n```\n\n========================================\n\nComments:\n- It doesnt work for me :(\n- Did for me, but this feels wrong.\n- The important part of this ^ answer for me was finding and removing `.pnp.cjs` (for me it was in the directory that held the cloned repo). See more details here -- github.com/storybookjs/storybook/issues/20876","metadata":{"transformedAt":"2026-08-18T18:33:46.405Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":400,"estimatedTokens":2774}}178{"id":"stack-74695028","source":"stackoverflow","questionId":74695028,"title":"Vite Typescript for React 17","tags":["reactjs","typescript","frontend","vite"],"text":"Title: Vite Typescript for React 17\nTags: reactjs, typescript, frontend, vite\nSource: Stack Overflow\n\nQuestion:\nIs there any way to install **Vite** and **Typescript** for **React 17** instead of **18**? We are using React 17.0.2 at work and considering to move Typescript.\n\n========================================\n\nCode:\n```text\nnpm i react@17 react-dom@17\n```\n\n```text\nnpm i -D @types/react@17 @types/react-dom@17\n```\n\n```text\n...\nimport ReactDOM from \"react-dom\"\n...\n\nReactDOM.render(\n  <React.StrictMode>\n    <App />\n  </React.StrictMode>,\n  document.getElementById(\"root\")\n);\n```\n\n```text\nmain.jsx\n```\n\n```text\nmain.tsx\n```\n\n```text\nrender\n```\n\n========================================\n\nComments:\n- Yes, there shouldn't be any issues","metadata":{"transformedAt":"2026-08-18T18:33:46.405Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":47,"estimatedTokens":185}}179{"id":"stack-76886227","source":"stackoverflow","questionId":76886227,"title":"Can I silence \"Module externalized for browser compatibility\" warnings in vite?","tags":["node.js","vite","polyfills"],"text":"Title: Can I silence \"Module externalized for browser compatibility\" warnings in vite?\nTags: node.js, vite, polyfills\nSource: Stack Overflow\n\nQuestion:\nI am using various third party npm modules, whose source code I do not control, and which have no alternatives.\n\nWhen I run `npm run build` using Vite, I see a few pages of\n\n```\ntransforming (556) node_modules/is-stream/index.js[plugin:vite:resolve] Module \"crypto\" has been externalized for browser compatibility, imported by \"myapp/node_modules/@bundlr-network/client/build/common/upload.js\". See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\ntransforming (637) node_modules/@portal-payments/solana-wallet-names/node_modules/buffer/index.js[plugin:vite:resolve] Module \"crypto\" has been externalized for browser compatibility, imported by \"myapp/node_modules/@bundlr-network/client/build/common/transaction.js\". See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\ntransforming (719) node_modules/semver/functions/satisfies.js[plugin:vite:resolve] Module \"crypto\" has been externalized for browser compatibility, imported by \"myapp/node_modules/arbundles/src/Bundle.js\". See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\n[plugin:vite:resolve] Module \"crypto\" has been externalized for browser compatibility, imported by \"myapp/node_modules/arbundles/src/DataItem.js\". See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\n[plugin:vite:resolve] Module \"crypto\" has been externalized for browser compatibility, imported by \"myapp/node_modules/arbundles/src/deepHash.js\". See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\ntransforming (965) node_modules/@ethereumjs/rlp/dist/index.js[plugin:vite:resolve] Module \"http\" has been externalized for browser compatibility, imported by \"myapp/node_modules/micro-ftch/index.js\". See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\n```\n\nI understand vite is 'excluding' these modules, and while vite doesn't explicitly state what externalizing means, there is another part of the docs that states:\n\nDependencies are \"externalized\" from Vite's SSR transform module system by default when running SSR. This speeds up both dev and build.\n\nWhich seems to indicate that the polyfills are not being optimised. Understood.\n\nIt's very hard for me to use a different module, make major changes to the upstream third party module, or rewrite the third party module.\n\nI am satisfied that the node polyfills are not being optimised. My problem is rather than otherwise useful build output is drowned in many pages of warnings.\n\nHow can I disable the warning?\n\n========================================\n\nTop Answer:\nYou can also install a polyfill for node.js modules.\n\nIn my case, installing `vite-plugin-node-polyfills` solved the issue.\n\n```\n# npm\nnpm install --save-dev vite-plugin-node-polyfills\n\n# pnpm\npnpm install --save-dev vite-plugin-node-polyfills\n\n# yarn\nyarn add --dev vite-plugin-node-polyfills\n```\n\nAnd then in your `vite.config` file:\n\n```\nimport { defineConfig } from 'vite'\nimport { nodePolyfills } from 'vite-plugin-node-polyfills'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n nodePolyfills(),\n ],\n})\n```\n\nBy default, the plugin polyfills multiple node modules, but you can include/exclude the modules you do/don't need.\n\nSee: All `vite-plugin-node-polyfill` polyfills (GitHub)\n\n========================================\n\nCode:\n```text\ntransforming (556) node_modules/is-stream/index.js[plugin:vite:resolve] Module \"crypto\" has been externalized for browser compatibility, imported by \"myapp/node_modules/@bundlr-network/client/build/common/upload.js\". See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\ntransforming (637) node_modules/@portal-payments/solana-wallet-names/node_modules/buffer/index.js[plugin:vite:resolve] Module \"crypto\" has been externalized for browser compatibility, imported by \"myapp/node_modules/@bundlr-network/client/build/common/transaction.js\". See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\ntransforming (719) node_modules/semver/functions/satisfies.js[plugin:vite:resolve] Module \"crypto\" has been externalized for browser compatibility, imported by \"myapp/node_modules/arbundles/src/Bundle.js\". See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\n[plugin:vite:resolve] Module \"crypto\" has been externalized for browser compatibility, imported by \"myapp/node_modules/arbundles/src/DataItem.js\". See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\n[plugin:vite:resolve] Module \"crypto\" has been externalized for browser compatibility, imported by \"myapp/node_modules/arbundles/src/deepHash.js\". See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\ntransforming (965) node_modules/@ethereumjs/rlp/dist/index.js[plugin:vite:resolve] Module \"http\" has been externalized for browser compatibility, imported by \"myapp/node_modules/micro-ftch/index.js\". See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\n```\n\n```text\nnpm run build\n```\n\n```bash\n# npm\nnpm install --save-dev vite-plugin-node-polyfills\n\n# pnpm\npnpm install --save-dev vite-plugin-node-polyfills\n\n# yarn\nyarn add --dev vite-plugin-node-polyfills\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport { nodePolyfills } from 'vite-plugin-node-polyfills'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    nodePolyfills(),\n  ],\n})\n```\n\n```text\nvite-plugin-node-polyfills\n```\n\n```text\nvite.config\n```\n\n```text\nvite-plugin-node-polyfill\n```\n\n========================================\n\nComments:\n- This is also a solution when trying to use jwt, if anyone encountered that problem as I did.","metadata":{"transformedAt":"2026-08-18T18:33:46.405Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":121,"estimatedTokens":1567}}180{"id":"stack-67835072","source":"stackoverflow","questionId":67835072,"title":"Vue 3 on Vite.js with Eslint — Unable to resolve path to module eslint(import/no-unresolved)","tags":["javascript","vue.js","eslint","vite","eslintrc"],"text":"Title: Vue 3 on Vite.js with Eslint — Unable to resolve path to module eslint(import/no-unresolved)\nTags: javascript, vue.js, eslint, vite, eslintrc\nSource: Stack Overflow\n\nQuestion:\nI use Vue 3 on Vite.js with Eslint + Airbnb config. Airbnb config has a rule `eslint(import/no-unresolved)`, which is good, but Eslint doesn't know how to resolve alias path.\n\nI want to use aliases for paths — example:\n`import TableComponent from '@/components/table/TableComponent.vue'˙`\n\nEnvironment is in plain JavaScript.\n\nI managed to set up my `vite.config.js` so that the app can resolve paths like this:\n\n```\nimport path from 'path';\nimport { defineConfig } from 'vite';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [vue()],\n resolve: {\n alias: [{\n find: \"@\", replacement: path.resolve(__dirname, 'src')\n },],\n },\n});\n```\n\nVue app works like that and resolves the import path correctly, but Eslint keeps reporting the error: `Unable to resolve path to module eslint(import/no-unresolved)`\n\nHow and where can I tell Eslint how to resolve aliases?\n\nI have tried:\n`install eslint-plugin-import eslint-import-resolver-alias --save-dev`\n\n```\n// .eslintrc.js\n\n// ...\nextends: [\n 'eslint:recommended',\n 'plugin:import/recommended',\n 'airbnb-base',\n 'plugin:vue/vue3-strongly-recommended',\n],\n\nsettings: {\n 'import/resolver': {\n alias: {\n map: [\n ['@', 'src'],\n ],\n },\n },\n },\n```\n\nBut that doesn't work.\n\nEDIT:\n\nSolved the issue, see the accepted answer if you're using plain JavaScript like I do.\n\nIf you're using TypeScript, see if Seyd's answer can help you.\n\n========================================\n\nTop Answer:\nthis solves the issue in my `TypeScript` project.\n\n```\nnpm install eslint-import-resolver-typescript\n```\n\nAfter `eslint-import-resolver-typescript` installation\n\n```\n{\n // other configuration are omitted for brevity\n settings: {\n \"import/resolver\": {\n typescript: {} // this loads /tsconfig.json to eslint\n },\n },\n}\n```\n\nshould be added to `.eslintrc.js.`\n\nmy tsconfig.json (remove unwanted settings)\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"esnext\",\n \"module\": \"esnext\",\n \"moduleResolution\": \"node\",\n \"strict\": false,\n \"jsx\": \"preserve\",\n \"sourceMap\": true,\n \"resolveJsonModule\": true,\n \"esModuleInterop\": true,\n \"lib\": [\"esnext\", \"dom\"],\n \"types\": [\"vite/client\", \"node\"],\n \"baseUrl\": \".\",\n \"paths\": {\n \"@/*\": [\"src/*\"]\n },\n \"allowJs\": true\n },\n \"include\": [\"src/**/*.ts\", \"src/**/*.d.ts\", \"src/**/*.tsx\", \"src/**/*.vue\"],\n \"exclude\": [\"node_modules\"]\n}\n```\n\nCheck the discussion here:\n\n========================================\n\nCode:\n```text\nimport path from 'path';\nimport { defineConfig } from 'vite';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue()],\n  resolve: {\n    alias: [{\n        find: \"@\", replacement: path.resolve(__dirname, 'src')\n      },],\n  },\n});\n```\n\n```text\n// .eslintrc.js\n\n// ...\nextends: [\n    'eslint:recommended',\n    'plugin:import/recommended',\n    'airbnb-base',\n    'plugin:vue/vue3-strongly-recommended',\n],\n\nsettings: {\n    'import/resolver': {\n      alias: {\n        map: [\n          ['@', 'src'],\n        ],\n      },\n    },\n  },\n```\n\n```text\neslint(import/no-unresolved)\n```\n\n```text\nimport TableComponent from '@/components/table/TableComponent.vue'˙\n```\n\n```text\nvite.config.js\n```\n\n```text\nUnable to resolve path to module eslint(import/no-unresolved)\n```\n\n```text\ninstall eslint-plugin-import eslint-import-resolver-alias --save-dev\n```\n\n```text\nsettings: {\n    'import/resolver': {\n      alias: {\n        map: [\n          ['@', './src'],\n        ],\n      },\n    },\n  },\n```\n\n```text\n\"settings\": {\n    \"import/resolver\": {\n      \"alias\": {\n        \"map\": [\n          [\"@\", \"./src\"]\n        ],\n\n        \"extensions\": [\".js\",\".jsx\"] <--- HERE\n      }\n    }\n  },\n```\n\n```js\n// vite.config.js\n\nimport { resolve } from 'path';\n\nimport { defineConfig } from 'vite';\n\nexport const aliases = {\n    '@': resolve(__dirname, './src'),\n    '@u': resolve(__dirname, './src/utils'),\n};\n\nexport default () => defineConfig({\n  // ...\n  resolve: {\n      alias: aliases,\n  },\n})\n```\n\n```js\n// .eslintrc.esm.js\n\nexport default {\n  root: true,\n  extends: ['@vue/airbnb', 'plugin:vue/recommended'],\n  // ...\n}\n```\n\n```js\nconst _require = require('esm')(module)\nmodule.exports = _require('./.eslintrc.esm.js').default\n```\n\n```js\n// .eslintrc.esm.js\n\nimport { aliases } from './vite.config';\n\nconst mappedAliases = Object.entries(aliases).map((entry) => entry); // [[alias, path], [alias, path], ...]\n\nexport default {\n  // ...\n  settings: {\n      'import/resolver': {\n          alias: {\n              map: mappedAliases,\n          },\n      },\n  },\n}\n```\n\n```text\nnpm i esm -D\n```\n\n```text\n.eslintrc.js\n```\n\n```text\n.eslintrc.esm.js\n```\n\n```text\n.eslintrc.esm.js\n```\n\n```text\n.eslintrc.js\n```\n\n```text\nvite.config.js\n```\n\n```text\n.eslintrc.esm.js\n```\n\n```text\nnpm i eslint-import-resolver-alias -D\n```\n\n```text\n.eslintrc.esm.js\n```\n\n```text\nsettings: {\n'import/resolver': {\n  alias: {\n    map: [['@', './src/']],\n    extensions: ['.js', '.vue'],\n  },\n},\n```\n\n```text\nnpm install eslint-import-resolver-typescript\n```\n\n```text\n{\n  // other configuration are omitted for brevity\n  settings: {\n    \"import/resolver\": {\n      typescript: {} // this loads <rootdir>/tsconfig.json to eslint\n    },\n  },\n}\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"target\": \"esnext\",\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"strict\": false,\n    \"jsx\": \"preserve\",\n    \"sourceMap\": true,\n    \"resolveJsonModule\": true,\n    \"esModuleInterop\": true,\n    \"lib\": [\"esnext\", \"dom\"],\n    \"types\": [\"vite/client\", \"node\"],\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@/*\": [\"src/*\"]\n    },\n    \"allowJs\": true\n  },\n  \"include\": [\"src/**/*.ts\", \"src/**/*.d.ts\", \"src/**/*.tsx\", \"src/**/*.vue\"],\n  \"exclude\": [\"node_modules\"]\n}\n```\n\n```text\nTypeScript\n```\n\n```text\neslint-import-resolver-typescript\n```\n\n```text\n.eslintrc.js.\n```\n\n```js\n// .eslintrc.cjs\n/* eslint-env node */\nrequire(\"@rushstack/eslint-patch/modern-module-resolution\");\n\nmodule.exports = {\n  root: true,\n  extends: [\n    \"airbnb\",\n    \"plugin:vue/vue3-essential\",\n    \"eslint:recommended\",\n    \"@vue/eslint-config-prettier\",\n  ],\n  parserOptions: {\n    ecmaVersion: \"latest\",\n  },\n\n  // Using the accepted answer\n  settings: {\n    \"import/resolver\": {\n      alias: {\n        map: [[\"@\", \"./src\"]],\n      },\n    },\n  },\n};\n```\n\n```js\n/* eslint-env node */\nrequire(\"@rushstack/eslint-patch/modern-module-resolution\");\n\nconst path = require(\"node:path\");\nconst createAliasSetting = require(\"@vue/eslint-config-airbnb/createAliasSetting\");\n\nmodule.exports = {\n  root: true,\n  extends: [\n    \"plugin:vue/vue3-essential\",\n    \"@vue/eslint-config-airbnb\", // <-- added\n    \"eslint:recommended\",\n    \"@vue/eslint-config-prettier\",\n  ],\n  parserOptions: {\n    ecmaVersion: \"latest\",\n  },\n\n  rules: {\n    \"import/no-unresolved\": \"error\",\n  },\n  settings: {\n    ...createAliasSetting({\n      \"@\": `${path.resolve(__dirname, \"./src\")}`,\n    }),\n  },\n};\n```\n\n```text\neslint-config-airbnb\n```\n\n```text\nnpm add --dev @vue/eslint-config-airbnb @rushstack/eslint-patch\n```\n\n```yaml\nsettings:\n  import/resolver:\n    eslint-import-resolver-custom-alias:\n      alias:\n        '@': './app/javascript'\n      extensions:\n        - '.js'\n        - '.vue'\n```\n\n```text\nREADME.md\n```\n\n```text\n@\n```\n\n```text\napp/javascript\n```\n\n```text\nvite.config.ts\n```\n\n========================================\n\nComments:\n- This didn't work for me, I have no idea what I'm doing wrong\n- @JCraine check your project's folder structure. I've put a note (asterisk, *) on that issue. It could also be your OS reading path differently, but it's beyond my knowledge if that could affect it. If you're looking for TypeScript solution, check Syed's answer.\n- I don't use TS, and I've resolved it with different `path` ('./src' instead of 'src') as I've shown in the answer.\n- @DeliciousBacon this answer was for the users who come in search of `TS` fix :)\n- You should update your answer and state it \"solves the issue when using TypeScript\" because \"this solves the issue.\" is vague. I'll mention it in the OP.\n- @DeliciousBacon yes, just did that. thanks for the feedback.","metadata":{"transformedAt":"2026-08-18T18:33:46.405Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":38,"totalLines":457,"estimatedTokens":2038}}181{"id":"stack-75998425","source":"stackoverflow","questionId":75998425,"title":"Vite build.sourcemap hidden not loading in Chrome or Firefox","tags":["javascript","reactjs","vite","source-maps","javascript-debugger"],"text":"Title: Vite build.sourcemap hidden not loading in Chrome or Firefox\nTags: javascript, reactjs, vite, source-maps, javascript-debugger\nSource: Stack Overflow\n\nQuestion:\nMigrating my react app from create-react-app to Vite and seeing some unexpected behavior with source maps. Vite docs regarding source maps are here. I was leaning toward using `sourcemap: true` until I saw that `sourcemap: 'hidden'` is the same thing except it is supposed to hide my comments ... sounds like exactly what I want.\n\nIf I create a build with `sourcemap: true`, each JS file gets its own map file, and the JS file gets a comment like `//# sourceMappingURL=mylibrary-033b4774.js.map` appended at the end of it. The source maps get loaded into Chrome and Firefox as expected.\n\nIf I create a build with `sourcemap: 'hidden'`, the only difference in output is that the `//# sourceMappingURL=mylibrary-033b4774.js.map` comment is NOT appended at the end of the JS file. A map file is still produced for each JS file, and it is accessible if I try to access it manually in the browser by typing its full path. However, the browsers don't seem to like this ... they don't show the map at all.\n\nIs this a bug in Vite or am I doing something wrong here?\n\n========================================\n\nTop Answer:\n```\nexport default defineConfig({\nbuild: {\n sourcemap: true,\n}\n})\n```\n\n========================================\n\nCode:\n```text\nsourcemap: true\n```\n\n```text\nsourcemap: 'hidden'\n```\n\n```text\nsourcemap: true\n```\n\n```text\n//# sourceMappingURL=mylibrary-033b4774.js.map\n```\n\n```text\nsourcemap: 'hidden'\n```\n\n```text\n//# sourceMappingURL=mylibrary-033b4774.js.map\n```\n\n```text\nsourcemap: process.ENV === 'production' ? 'hidden' : true;\n```\n\n```js\nbuild: {\n      rollupOptions: {\n        output: {\n          sourcemap: true,\n          sourcemapBaseUrl: 'YOUR SOURCEMAP BASE URL', // https://www.my-source-maps.com\n        }\n      }\n    }\n```\n\n```text\n//# sourceMappingURL=\n```\n\n```text\n//# sourceMappingURL=build.js.map\n```\n\n```text\nhttp://localhost:3000\n```\n\n```text\nhttp://localhost:3000/build.js.map\n```\n\n```text\n//# sourceMappingURL=http://localhost:8080/build.js.map\n```\n\n```text\nhttp://localhost:3000/build.js.map\n```\n\n```text\nsourcemap\n```\n\n```text\nCORS\n```\n\n```text\nexport default defineConfig({\nbuild: {\n    sourcemap: true,\n}\n})\n```\n\n========================================\n\nComments:\n- Although this code might answer the question, I recommend that you also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.\n- Seems clear to me: `hidden` is an additional layer of security by obscurity. The publishers of the production source maps know the hosted domain and/or have to know where to look to load it manually. Albeit, the answer seems to be chatGPT generated.\n- This is clearly security through obscurity","metadata":{"transformedAt":"2026-08-18T18:33:46.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":112,"estimatedTokens":737}}182{"id":"stack-68570519","source":"stackoverflow","questionId":68570519,"title":"Why can't reflect-metadata be used in vite","tags":["typescript","vite","reflect-metadata"],"text":"Title: Why can't reflect-metadata be used in vite\nTags: typescript, vite, reflect-metadata\nSource: Stack Overflow\n\nQuestion:\n```\nimport \"reflect-metadata\"\n\nfunction validate(target: any) {\n let paramtypes = Reflect.getMetadata(\"design:paramtypes\", target);\n console.log(paramtypes); // undefined\n}\n\n@validate\nclass Log {\n constructor(public readonly xx: string) {}\n}\n```\n\nHit me to start the server, and when I opened the webpage, I found that paramtypes was undefined\n\ntsconfig.json\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"ESNext\",\n \"lib\": [\"DOM\", \"DOM.Iterable\", \"ESNext\"],\n \"allowJs\": false,\n \"skipLibCheck\": false,\n \"esModuleInterop\": false,\n \"allowSyntheticDefaultImports\": true,\n \"strict\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Node\",\n \"resolveJsonModule\": true,\n \"isolatedModules\": true,\n \"noEmit\": true,\n \"jsx\": \"react\",\n \"experimentalDecorators\": true,\n \"emitDecoratorMetadata\": true\n },\n \"include\": [\"./src\"]\n}\n```\n\n========================================\n\nTop Answer:\nUsing SWC is feasible solution, but if you want to stay closer to the original setup I've found the right configuration.\n\nIt's true that esbuild does not support decorator metadata, but! there is a community plugin for that - @anatine/esbuild-decorators.\n\nI've added it to the optimizeBuild configuration and it Just Works™️.\n\nFrom my understanding it shouldn't have worked after build (because from the docs vite does not use esbuild when building for prod), but it does work!\n\nHere is an example repo with vite 4 & tsyringe that uses reflect-metadata\nhttps://stackblitz.com/edit/vitejs-vite-hzkjj3?file=vite.config.ts\n\n========================================\n\nCode:\n```json\nimport \"reflect-metadata\"\n\nfunction validate(target: any) {\n  let paramtypes = Reflect.getMetadata(\"design:paramtypes\", target);\n  console.log(paramtypes);  // undefined\n}\n\n@validate\nclass Log {\n  constructor(public readonly xx: string) {}\n}\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"lib\": [\"DOM\", \"DOM.Iterable\", \"ESNext\"],\n    \"allowJs\": false,\n    \"skipLibCheck\": false,\n    \"esModuleInterop\": false,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react\",\n    \"experimentalDecorators\": true,\n    \"emitDecoratorMetadata\": true\n  },\n  \"include\": [\"./src\"]\n}\n```\n\n```js\nimport typescript from \"@rollup/plugin-typescript\";\nimport swc from \"rollup-plugin-swc\";\n\n// import typescript from \"rollup-plugin-typescript2\";\n\nexport default defineConfig({\n    plugins: [\n        swc({\n            jsc: {\n                parser: {\n                    syntax: \"typescript\",\n                    // tsx: true, // If you use react\n                    dynamicImport: true,\n                    decorators: true,\n                },\n                target: \"es2021\",\n                transform: {\n                    decoratorMetadata: true,\n                },\n            },\n        }),\n    ],\n    esbuild: false,\n});\n```\n\n```text\n\"emitDecoratorMetadata\"\n```\n\n```text\n/// <reference types=\"vitest\" />\nimport { defineConfig } from 'vite' \n\nexport default defineConfig({\n test: {\n  setupFiles: [\"./setupFile.ts\"],\n },\n...rest of your config\n})\n```\n\n```text\nimport 'reflect-metadata'\n\n...rest of your setup\n```\n\n```text\nimport 'reflect-metadata'\n```\n\n```text\nimport { reactRouter } from '@react-router/dev/vite';\nimport { defineConfig } from 'vite';\nimport { copyFileSync, mkdirSync } from 'fs';\nimport { resolve } from 'path';\n\nexport default defineConfig({\n  plugins: [\n    reactRouter(),\n    {\n      name: 'copy-reflect-metadata',\n      generateBundle() {\n        const srcPath = resolve('node_modules/reflect-metadata/Reflect.js');\n        const destDir = resolve('build/client/assets');\n        const destPath = resolve(destDir, 'reflect-metadata.js');\n\n        try {\n          mkdirSync(destDir, { recursive: true });\n          copyFileSync(srcPath, destPath);\n          console.log('✓ Copied reflect-metadata to assets');\n        } catch (error) {\n          console.warn('Failed to copy reflect-metadata:', error);\n        }\n      },\n    },\n  ],\n});\n```\n\n```text\nexport const Layout = ({ children }: { children: React.ReactNode }) => {\n  return (\n    <html lang=\"en\">\n      <head>\n        <meta charSet=\"utf-8\" />\n        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n        {/* Fallback script for reflect-metadata in production */}\n        {import.meta.env.PROD && (\n          <script\n            src=\"/assets/reflect-metadata.js\"\n            defer\n            onError={() => {\n              console.error('Failed to load reflect-metadata script');\n            }}\n          ></script>\n        )}\n        <Meta />\n        <Links />\n      </head>\n      <body>\n        {children}\n        <ScrollRestoration />\n        <Scripts />\n      </body>\n    </html>\n  );\n};\n```\n\n```text\nreflect-metadata\n```\n\n```text\nemitDecoratorMetadata\n```\n\n```text\nimport \"reflect-metadata\"\n```\n\n```text\nroot.tsx\n```\n\n```text\nreflect-metadata\n```\n\n```text\nvite.config.ts)\n```\n\n```text\nreflect-metadata\n```\n\n```text\napp/root.tsx\n```\n\n========================================\n\nComments:\n- Solution to similar problem (enabling reflect-metadata with Vite for Tsyringe): stackoverflow.com/a/79841152/11041249 uses options for '@vitejs/plugin-react-swc'; which is used in ne\n- This solution is feasible\n- It doesn't seem to resolve css/less files correctly.\n- @红了樱桃绿了吧唧 I dont see how this relates to css/less files, please elaborate.\n- Doesn't work on my end, tested using vite 2.9.9.\n- this does not work anymore/has never worked\n- @SebastianG This worked last time I checked my demo repo with vite version 2.4.0. I have no interest in updating my answer for newer vite versions since I don't use or recommend the usage of decorators anymore, so you might need to figure out your own solutions.\n- This doesn't work: `error when starting dev server: TypeError: swc is not a function`\n- @KiddoV Like I said, I have no interest in updating my answer for newer vite/ts versions. Additionally, with Typescript 5.0, and its implementation for Decorator, `reflect-metadata` will only work with the legacy decorator implementation `--experimentalDecorators`. As for the swc plugin, refer to this for its usage.\n- Thank you for providing this StackBlitz example. Do you know why error TS2322 is thrown in its vite.config.ts file?\n- unfortunately `@anatine&#47;esbuild-decorators` seems to be quite dead now\n- This does not address the issue reported by OP. OP refers to the lack of support of `emitDecoratorMetadata` in `esbuild`. What you're talking about is how to avoid importing `reflect-metadata` in every the test file, which comes originally from github.com/inversify/InversifyJS/issues/1189\n- for me it solved the problem I googled and that the title more or less says.","metadata":{"transformedAt":"2026-08-18T18:33:46.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":262,"estimatedTokens":1750}}183{"id":"stack-69487625","source":"stackoverflow","questionId":69487625,"title":"Socket.IO in React app bundled with Vite doesnt work (When bundled with Webpack it does)","tags":["javascript","reactjs","webpack","socket.io","vite"],"text":"Title: Socket.IO in React app bundled with Vite doesnt work (When bundled with Webpack it does)\nTags: javascript, reactjs, webpack, socket.io, vite\nSource: Stack Overflow\n\nQuestion:\nI have a Create React App that I migrated to Vite.\n\nI use `socket.io-client`.\n\nBoth versions of the app are exactly the same (simply copy/paste) except the bundlers.\n\nThis is my websocket connection\n\n```\nimport { io } from 'socket.io-client'\n\nexport function App() {\n useEffect(() => {\n io('http://my-server')\n })\n}\n```\n\nIn the webpack version I can see in the network tab that socket.io is attempting to connect.\n\nBut in the vite version it doesn't, it doesn't even throw an error.\n\nHow can I fix this? is this have anything to do with Vite only supporting ESM packages and not CommonJS?\n\n========================================\n\nCode:\n```text\nimport { io } from 'socket.io-client'\n\nexport function App() {\n  useEffect(() => {\n    io('http://my-server')\n  })\n}\n```\n\n```text\nsocket.io-client\n```\n\n```text\nio('http://my-server', {\n    transports: ['websocket'], // Required when using Vite      \n})\n```\n\n```text\ntransports\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.406Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":55,"estimatedTokens":277}}184{"id":"stack-64502855","source":"stackoverflow","questionId":64502855,"title":"Vite import CSS with alias in main.ts","tags":["typescript","vue.js","vuejs3","vite"],"text":"Title: Vite import CSS with alias in main.ts\nTags: typescript, vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to replace vue-cli with vite. I have a vite.config.js so I can use alias for imports:\n\n```\nexport default {\n alias: {\n '@': require('path').resolve(__dirname, 'src'),\n },\n};\n```\n\nThen in my main.ts I try to import my css file (I tried it with or without the `.module`:\n\n```\nimport { createApp } from 'vue';\nimport App from './App.vue';\nimport router from './router';\n\nimport '@/assets/app.module.css';\n\ncreateApp(App).use(router).mount('#app');\n```\n\nBut I get this error:\n\n[vite] Failed to resolve module import \"@/assets/app.module.css\". (imported by /src/main.ts)\n\nWhat am I doing wrong?\n\n========================================\n\nTop Answer:\n**Tested**\n\njust wanted to add:\nFor anyone still looking at this answer you need to add resolve so it work, as documented in the website.\nI didn't added the slashes '/@/'\nThis works for me:\n\nexample:\n\n```\nresolve: {\n alias: {\n '@': require('path').resolve(__dirname, 'src')\n }\n },\n```\n\nhttps://vitejs.dev/config/#resolve-alias\n\n========================================\n\nCode:\n```text\nexport default {\n    alias: {\n        '@': require('path').resolve(__dirname, 'src'),\n    },\n};\n```\n\n```text\nimport { createApp } from 'vue';\nimport App from './App.vue';\nimport router from './router';\n\nimport '@/assets/app.module.css';\n\ncreateApp(App).use(router).mount('#app');\n```\n\n```text\n.module\n```\n\n```text\n'/@/': require('path').resolve(__dirname, 'src'),\n```\n\n```text\n'/@foo/': path.resolve(__dirname, 'some-special-dir')\n```\n\n```text\n{\n    \"compilerOptions\": {\n        \"baseUrl\": \".\",\n        \"esModuleInterop\": true,\n        \"moduleResolution\": \"node\",\n        \"paths\": {\n            \"@/*\": [\n                \"src/*\"\n            ]\n        },\n        \"target\": \"esnext\"\n    },\n    \"include\": [\n        \"src/**/*.ts\",\n    ]\n}\n```\n\n```text\nimport seedrandom from 'seedrandom';\n```\n\n```text\nvue\n```\n\n```text\n/@/\n```\n\n```text\n@/\n```\n\n```text\nget x\n```\n\n```text\nset x\n```\n\n```text\nresolve: {\n    alias: {\n      '@': require('path').resolve(__dirname, 'src')\n    }\n  },\n```\n\n```text\naliases.push({ find: '~bootstrap', replacement: 'bootstrap' })\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport { getAliases } from 'vite-aliases'\n\nconst aliases = getAliases();\n\n// add aliases to import scss from node_modules here\n\naliases.push({ find: '~bootstrap', replacement: 'bootstrap' })\n\n// https://vitejs.dev/config/\n\nexport default defineConfig({\n  plugins: [vue()],\n  resolve: {\n    alias: aliases\n  },\n  css: {\n    preprocessorOptions: {\n      scss: {\n        additionalData: '@import \"@scss/shared.scss\";'\n      }\n    }\n  }\n})\n```\n\n```text\nimport '@scss/main.scss'\n```\n\n```text\n@import \"~bootstrap/scss/bootstrap\";\n```\n\n```text\nvite@2.1.5\n```\n\n```text\n@\n```\n\n```text\n~\n```\n\n```text\nvite.config.js\n```\n\n```text\nreadme.md\n```\n\n```text\n~\n```\n\n```text\nvite.config.js\n```\n\n```text\nsrc/main.ts\n```\n\n```text\nsrc/scss/main.scss\n```\n\n```text\nnode_modules\n```\n\n```text\naliases\n```\n\n```text\nbootstrap.scss\n```\n\n```text\ncss.preprocessorOptions.scss.additionalData\n```\n\n```text\nshared.scss\n```\n\n========================================\n\nComments:\n- Yes this seems to be the case. I can now import the css with @/assets/app.css, but it seems I now need to import my TS and .vue files with /@/components/ or VSCode complains.\n- do you mean that you have to change every relative path to `@&#47;` absolute one?\n- I think this is not a vite issue, but a VSCode one. I need to add a minimal tsconfig.json after all so it is happy again\n- I think this is now true for Vite 2\n- Yes this worked. This should be the accepted answer now.\n- Simply using `resolve: { alias: { '~bootstrap': path.resolve(__dirname, 'node_modules&#47;bootstrap') }}` works, no need for `vite-aliases` plugin. Pointed me in the right direction, though, thanks. Not sure why, but `'~': path.resolve(__dirname, 'node_modules&#47;')` doesn't work, for some reason, so you have to add an entry for every plugin referenced into an scss `@import`.\n- thanks a lot the answer and @tao comment saved the day","metadata":{"transformedAt":"2026-08-18T18:33:46.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":245,"estimatedTokens":1039}}185{"id":"stack-72414162","source":"stackoverflow","questionId":72414162,"title":"vue3+vite+vuei18n build \"Uncaught TypeError: _ctx.$t is not a function\"","tags":["vue.js","vite","vue-i18n"],"text":"Title: vue3+vite+vuei18n build \"Uncaught TypeError: _ctx.$t is not a function\"\nTags: vue.js, vite, vue-i18n\nSource: Stack Overflow\n\nQuestion:\nI want to publish my vue3+vite package to npm but after publishing, I encountered \"Uncaught TypeError: _ctx.$t is not a function\" in a test project and my package is not working, any suggestions... ?\n\nPS: I'm using vue options api\n\nvite.configs.js:\n\n```\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport vueI18n from '@intlify/vite-plugin-vue-i18n'\n\n// https://vitejs.dev/config/\nconst path = require(\"path\")\nexport default defineConfig({\n build: {\n lib: {\n entry: path.resolve(__dirname, 'src/install.ts'),\n name: 'vcp',\n fileName: (format) => `vcp.${format}.ts`\n },\n rollupOptions: {\n external: ['vue'],\n output: {\n exports: 'named',\n globals: {\n vue: 'Vue',\n vcp: 'Vcp'\n }\n }\n },\n },\n plugins: [\n vue(),\n vueI18n({\n include: path.resolve(__dirname, 'src/assets/translations.json'),\n compositionOnly: false,\n })\n ],\n server: {\n port: 8080\n },\n resolve: {\n dedupe: ['vue'],\n alias: {\n \"~\": path.resolve(__dirname, \"./src\"),\n \"@\": path.resolve(__dirname, \"./src\"),\n },\n },\n})\n```\n\n========================================\n\nTop Answer:\nCheck the path in `nuxt.config.ts -> i18n -> vueI18n`. In my case I had wrong path.\n\n(I’m not answering the question from the problem, but the first link from Google for the query “_ctx.$t is not a function”)\n\n========================================\n\nCode:\n```js\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport vueI18n from '@intlify/vite-plugin-vue-i18n'\n\n// https://vitejs.dev/config/\nconst path = require(\"path\")\nexport default defineConfig({\n  build: {\n    lib: {\n      entry: path.resolve(__dirname, 'src/install.ts'),\n      name: 'vcp',\n      fileName: (format) => `vcp.${format}.ts`\n    },\n    rollupOptions: {\n      external: ['vue'],\n      output: {\n        exports: 'named',\n        globals: {\n          vue: 'Vue',\n          vcp: 'Vcp'\n        }\n      }\n    },\n  },\n  plugins: [\n    vue(),\n    vueI18n({\n      include: path.resolve(__dirname, 'src/assets/translations.json'),\n      compositionOnly: false,\n    })\n  ],\n  server: {\n    port: 8080\n  },\n  resolve: {\n    dedupe: ['vue'],\n    alias: {\n      \"~\": path.resolve(__dirname, \"./src\"),\n      \"@\": path.resolve(__dirname, \"./src\"),\n    },\n  },\n})\n```\n\n```text\nnuxt.config.ts -> i18n -> vueI18n\n```\n\n========================================\n\nComments:\n- Take a look at this link, It's because you are `$t` in your project.\n- My problem is with vuei18n bundling tools for vite not the vuei18n itself, and globalInjection flag is for vuei18n","metadata":{"transformedAt":"2026-08-18T18:33:46.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":120,"estimatedTokens":661}}186{"id":"stack-73036803","source":"stackoverflow","questionId":73036803,"title":"Uncaught TypeError: https.Agent is not a constructor","tags":["javascript","reactjs","web3js","vite"],"text":"Title: Uncaught TypeError: https.Agent is not a constructor\nTags: javascript, reactjs, web3js, vite\nSource: Stack Overflow\n\nQuestion:\nI am developing a dapp with react, the error when I try to instantiate web3 with an RPC of HTTPS or HTTP.\n\nThe error is as follows:\n\nUncaught TypeError: https.Agent is not a constructor\n\nAfter doing some research, I have been able to verify that the error comes from the web3-providers-http module.\n\nExpected Behavior\nWhen I configure the Metamask provider (window.ethereum) everything works fine. Since I can do write and read transactions, without problem on the blockchain. What I hope is that it works correctly without the error and can make transactions.\n\nSteps to Reproduce\n\n```\nvar Web3 = require('web3');\nvar provider = 'https://mainnet.infura.io/v3/';\nvar web3Provider = new Web3.providers.HttpProvider(provider);\nvar web3 = new Web3(web3Provider);\nweb3.eth.getBlockNumber().then((result) => {\n console.log(\"Latest Ethereum Block is \",result);\n});\n```\n\nWeb3.js Version\n1.7.4\n\nVite Version\n3.0.0\n\nEnvironment\nOperating System: macOs 11.5.2\nBrowser: Chrome, Firefox\nNode.js Version: v12.22.0\nNPM Version: 7.7.6\n\n========================================\n\nCode:\n```text\nvar Web3 = require('web3');\nvar provider = 'https://mainnet.infura.io/v3/<PROJECT-ID>';\nvar web3Provider = new Web3.providers.HttpProvider(provider);\nvar web3 = new Web3(web3Provider);\nweb3.eth.getBlockNumber().then((result) => {\n  console.log(\"Latest Ethereum Block is \",result);\n});\n```\n\n```text\nimport GlobalsPolyfills from '@esbuild-plugins/node-globals-polyfill'\n\nexport default defineConfig({\n...\n  optimizeDeps: {\n    esbuildOptions: {\n      define: {\n        global: 'globalThis',\n      },\n      plugins: [\n        GlobalsPolyfills({\n          process: true,\n          buffer: true,\n        }),\n      ],\n    },\n  },\n  resolve: {\n    alias: {\n      stream: 'stream-browserify',\n      https: 'agent-base', \n      // comment above line and uncomment below line if it doesnot work\n      //     http:'agent-base',\n    },\n  },\n...\n)}\n```\n\n```text\nimport { ethers, Contract, Wallet, getDefaultProvider } from 'ethers';\nimport ZntLockerLens from './ZntLockerLens';\n\n    const provider = new ethers.providers.JsonRpcProvider(\n      'https://http-testnet.xx.com',\n    );\n    const contract = new Contract(\n      '0x492B7bCD1732FBB8297a24694dxx6B3FEDCA9D0A',\n      ZntLockerLens.abi,\n      provider,\n    );\n    (async () => {\n      const result = await contract.getLockInfo(\n        '0xC02a0c4634B4f2aF73Bb29bxx1153E791AdB7D1e',\n      );\n      console.log(result);\n    })();\n```\n\n```text\nyarn add stream-browserify agent-base\n```\n\n```text\nnpm -i stream-browserify agent-base\n```\n\n```text\nethers\n```\n\n========================================\n\nComments:\n- How would I do this in Quasar? I don't have direct access to Vite config, only the quasar.config.js file.","metadata":{"transformedAt":"2026-08-18T18:33:46.406Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":119,"estimatedTokens":717}}187{"id":"stack-77498366","source":"stackoverflow","questionId":77498366,"title":"How do I setup a multi page app using vite?","tags":["javascript","html","config","vite","multi-page-application"],"text":"Title: How do I setup a multi page app using vite?\nTags: javascript, html, config, vite, multi-page-application\nSource: Stack Overflow\n\nQuestion:\nI am trying to setup a vite project that has multiple entry points.\n\nhttps://stackblitz.com/edit/vitejs-vite-swtkdv\n\nIt is a pretty basic setup taken straight from the vite website that uses vanilla flavour. Only things which I have updated are the following:\n\n- add vite.config.js file with configuration for multiple entry points (check the attached stackblitz link)\n\n- add new files: login/index.html; login/login.js (check the attached stackblitz link)\n\nWhat I expect to happen is everytime I enter `url`/login, it should load the page `./login/index.html`. However in reality it keeps on loading the `./index.html`.\n\n========================================\n\nTop Answer:\nThis relates to the answer by DVN-Anakin.\n\nI was using this as an example and noticed that my dist folder after a build did not include the login folder with index.html. I took a look at the vite site as recommended but got errors relating to 'path' and '__dirname'. I changed it to:\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n build: {\n rollupOptions: {\n input: {\n main: 'index.html',\n login: 'login/index.html',\n },\n },\n },\n})\n```\n\nAnd now I have those files in dist. I am hosting this on an Azure SWA and can confirm that GitHub built and pushed this across and appending /login/ to the url of the site works as expected (although this is configurable in SWAs too).\n\n========================================\n\nCode:\n```text\nurl\n```\n\n```text\n./login/index.html\n```\n\n```text\n./index.html\n```\n\n```text\nhttp://localhost:5173/login\n```\n\n```text\n./login/index.html\n```\n\n```text\n./login/index.html\n```\n\n```text\nhttp://localhost:5173/login/\n```\n\n```text\n/\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  build: {\n    rollupOptions: {\n      input: {\n        main: 'index.html',\n        login: 'login/index.html',\n      },\n    },\n  },\n})\n```\n\n========================================\n\nComments:\n- this works at the local host, but after deploying to netilify it cant find the page.","metadata":{"transformedAt":"2026-08-18T18:33:46.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":101,"estimatedTokens":586}}188{"id":"stack-71415014","source":"stackoverflow","questionId":71415014,"title":"How to use autoprefixer with ViteJS and React?","tags":["reactjs","sass","vite","autoprefixer"],"text":"Title: How to use autoprefixer with ViteJS and React?\nTags: reactjs, sass, vite, autoprefixer\nSource: Stack Overflow\n\nQuestion:\nI'm using React with ViteJS and SASS, but i have a problem. It seems there is not autoprefixer for CSS/SCSS when i will build the project.\n\nHow to add an auto-prefixer with ViteJS and SASS?\n\n========================================\n\nTop Answer:\nFirst, you have to install autoprefixer:\n\n```\nnpm i autoprefixer -D\n```\n\nafter that, you have to go to your `vite.config.ts` and add it there:\n\n```\nimport autoprefixer from 'autoprefixer';\n\nexport default defineConfig({\n plugins: [react()],\n css: {\n ...\n postcss: {\n plugins: [\n autoprefixer\n ],\n }\n },\n ...\n});\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n  plugins: {\n    autoprefixer: {}\n  }\n}\n```\n\n```text\nimport { defineConfig } from \"vite\"\nimport react from '@vitejs/plugin-react'\nimport autoprefixer from 'autoprefixer'\n\nexport default defineConfig({\n  plugins: [\n    react()\n  ],\n  css: {\n    postcss: {\n      plugins: [\n        autoprefixer({}) // add options if needed\n      ],\n    }\n  }\n})\n```\n\n```text\nyarn add -D postcss@latest autoprefixer@latest\n```\n\n```text\npostcss.config.js\n```\n\n```text\nvite.config.ts\n```\n\n```text\nnpm i autoprefixer -D\n```\n\n```text\nimport autoprefixer from 'autoprefixer';\n\nexport default defineConfig({\n  plugins: [react()],\n  css: {\n    ...\n    postcss: {\n      plugins: [\n          autoprefixer\n      ],\n    }\n  },\n  ...\n});\n```\n\n```text\nvite.config.ts\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport cssInjectedByJsPlugin from \"vite-plugin-css-injected-by-js\";\nimport react from '@vitejs/plugin-react'\nimport autoprefixer from \"autoprefixer\";\n\nexport default defineConfig({\n  plugins: [react(), cssInjectedByJsPlugin()],\n  css: {\n    postcss: {\n      plugins: [autoprefixer],\n    },\n  },\n  build: {\n    rollupOptions: {\n      output: {\n        manualChunks: undefined,\n      },\n    },\n  },\n});\n```\n\n========================================\n\nComments:\n- I created the react project using `npm create vite` but the solution is not working.\n- Still it's not working. I've created a new question. stackoverflow.com/questions/73647725/&hellip; would be great if you can have a look..\n- Hey! I think this is not a solution, Vite is an alternative to create-react-app so there should be a way to use autoprefixer with it instead of changing the project generator.\n- the question explicitly says they want to use autoprefixer with Vite and React. So suggesting changing the project generator to CRA is the same as explaining how to add autoprefixer to Vue CLI and telling them to use Vue instead.\n- This answer is confusing, the question is specifically about Vite except you keep pointing to create react app. \"If it doesn't work, you should check which version of create-react-app you are using\". OP isn't using CRA, OP is using vite\n- Thats the correct answer","metadata":{"transformedAt":"2026-08-18T18:33:46.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":136,"estimatedTokens":728}}189{"id":"stack-71219585","source":"stackoverflow","questionId":71219585,"title":"How to keep tests outside from source directory in Vite projects?","tags":["vue.js","vite","vitest"],"text":"Title: How to keep tests outside from source directory in Vite projects?\nTags: vue.js, vite, vitest\nSource: Stack Overflow\n\nQuestion:\nRunning `npm init vue@latest` with the following setup\n\nhttps://i.sstatic.net/2c7XX.png\n\ngenerates a Vitest spec file inside the `src` directory. I'm wondering why Cypress e2e tests have a seperate directory and Vitest unit tests are right next to the source code. Are there any reasons?\n\nI want to move those tests to the root directory (equal to `cypress`), created a `vitest` directory and moved to spec into it.\n\nThe test itself passes but I think I have to change sopme configuration to exclude the tests from the build etc.\n\nInside the file `tsconfig.app.json` I changed the line `\"exclude\": [\"src/**/__tests__/*\"],` to `\"exclude\": [\"vitest\"],`.\n\nIs there something else I should do? Or are there any reasons to keep Vitest tests inside the source directory?\n\n========================================\n\nTop Answer:\non the latest release of vue 3, @flydev instruction and update your package.json file\n\nfrom\n`\"test:unit\": \"vitest --environment jsdom --root src/\",`\n\nto\n\n`\"test:unit\": \"vitest --environment jsdom --root .\",`\n\n========================================\n\nCode:\n```text\nnpm init vue@latest\n```\n\n```text\nsrc\n```\n\n```text\ncypress\n```\n\n```text\nvitest\n```\n\n```text\ntsconfig.app.json\n```\n\n```text\n\"exclude\": [\"src/**/__tests__/*\"],\n```\n\n```text\n\"exclude\": [\"vitest\"],\n```\n\n```text\ntest: {\n    include: ['./vitest/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}']\n  }\n```\n\n```text\n./src/components/__tests__\n```\n\n```text\n./vitest/__tests__\n```\n\n```text\n@\n```\n\n```text\nimport HelloWorld from '@/components/HelloWorld.vue'\n```\n\n```text\n\"exclude\": [\"src/**/__tests__/*\"],\n```\n\n```text\n\"exclude\": [\"vitest/**/__tests__/*\"],\n```\n\n```text\nnpm run build && npm run test:unit\n```\n\n```text\nvite.config.ts\n```\n\n```text\n\"exclude\": [\"vitest/**/*\"],\n```\n\n```text\nyarn run test:unit\n```\n\n```text\n\"test:unit\": \"vitest --environment jsdom --root src/\",\n```\n\n```text\n\"test:unit\": \"vitest --environment jsdom --root .\",\n```\n\n========================================\n\nComments:\n- @medsmh you don't necessarily need the `__tests__` folder now. That convention is mainly useful when unit tests are close to the src files (but adjust `exclude` if you remove it).\n- I'm not sure if I should stick to a `vitest` directory and move all those tests into it or if I should create a `tests` directory, move the generated cypress folder into it and create a `__tests__` directory for the Vitest stuff\n- I want to perform the same thing. I applied this solution. But it seems the `@` in imports is not resolved. Import cannot be found.\n- @Eria you need to define an alias. Check ‘resolve.alias’ in the vite doc and there: stackoverflow.com/a/66559769/774432\n- I have it already : stackoverflow.com/questions/72468249/&hellip;\n- I found vscode didn't like this (when the vue project is in a subfolder anyway) and would mark the import as \"not found\" even though it worked when building/running tests. To fix, I also had to add `\"vitest&#47;**&#47;__tests__&#47;*\"` to the `includes` section in **tsconfig.app.json**. It looks a bit odd, but works since **tsconfig.vitest.json** contains `\"exclude\": []\"`, which clears the list of excludes. (the other option would be to duplicate the includes from **tsconfig.app.json** while adding `\"vitest&#47;**&#47;__tests__&#47;*\"` there.","metadata":{"transformedAt":"2026-08-18T18:33:46.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":125,"estimatedTokens":848}}190{"id":"stack-71355290","source":"stackoverflow","questionId":71355290,"title":"Prevent service-worker.js from being bundled with vite / rollup","tags":["typescript","vuejs3","service-worker","rollup","vite"],"text":"Title: Prevent service-worker.js from being bundled with vite / rollup\nTags: typescript, vuejs3, service-worker, rollup, vite\nSource: Stack Overflow\n\nQuestion:\nI have a TypeScript-based Vuejs project compiled and bundled using Vite.\n\nI am trying to configure the build system to compile my custom service worker (src/service-worker.ts) and place the output in dist/service-worker.js. In particular, I don't want it included as part of the application's JS bundle, because it needs to be served at that well-known URL as part of a static website.\n\nThe existing structure is like:\n\n```\nindex.html\npublic/\n favicon.ico\nsrc/\n service-worker.ts\n main.ts\n /* etc */\n```\n\nAnd I would like the output to be something like:\n\n```\ndist/\n index.html\n assets/index.[hash].js\n assets/vendor.[hash].js\n /* ... */\n service-worker.js # If the service worker didn't need to be transpiled/compiled, I know I could simply include it in `public/` and it would be copied to the `dist/` folder unchanged.\n\nI've looked at vite-plugin-pwa but that is rather opaque and tied to workbox.\n\nOther related questions relate to situations where people want to exclude files altogether from their build output, which is not quite what I'm after.\n\nHow can I compile a TypeScript file but leave its output unbundled in my dist folder?\n\n========================================\n\nCode:\n```text\nindex.html\npublic/\n favicon.ico\nsrc/\n service-worker.ts\n main.ts\n /* etc */\n```\n\n```text\ndist/\n index.html\n assets/index.[hash].js\n assets/vendor.[hash].js\n /* ... */\n service-worker.js  # <-- I would like the file emitted here\n```\n\n```text\npublic/\n```\n\n```text\ndist/\n```\n\n```js\n// vite.config.ts\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\nexport default defineConfig({\n  plugins: [vue()],\n  build: {\n    rollupOptions: {\n      input: {\n        // the default entry point\n        app: './index.html',\n\n        // 1️⃣\n        'service-worker': './src/service-worker.ts',\n      },\n      output: {\n        // 2️⃣\n        entryFileNames: assetInfo => {\n          return assetInfo.name === 'service-worker'\n             ? '[name].js'                  // put service worker in root\n             : 'assets/js/[name]-[hash].js' // others in `assets/js/`\n        }\n      },\n    },\n  },\n})\n```\n\n```text\nbuild.rollupOptions\n```\n\n```text\nservice-worker.ts\n```\n\n```text\nbuild.rollupOptions.input\n```\n\n```text\nbuild.rollupOptions.output.entryFilenames\n```\n\n========================================\n\nComments:\n- Does the info at github.com/vitejs/vite/discussions/1736 help? It sounds like it's a question of dropping down and configuring Rollup directly. Either an IIFE (preferred) or UMD bundle of your `service-worker.ts` should work.","metadata":{"transformedAt":"2026-08-18T18:33:46.406Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":116,"estimatedTokens":678}}191{"id":"stack-71571129","source":"stackoverflow","questionId":71571129,"title":"How to use embedded Webassembly in Vite?","tags":["webassembly","vite","hpcc"],"text":"Title: How to use embedded Webassembly in Vite?\nTags: webassembly, vite, hpcc\nSource: Stack Overflow\n\nQuestion:\nI would like to use this great package: https://github.com/hpcc-systems/hpcc-js-wasm\nIt bundles a Webassembly (graphizlib.wasm) with the Javascript functions to use. I added it as a dependency in package.json.\n\n```\n\"dependencies\": {\n \"@hpcc-js/wasm\": \"^1.13.0\"\n },\n```\n\nWhen I now run the Vite dev server then the Javascript code is found easily enough. But the wasm isn't available. In particular, I get this error message:\n\n`Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3000/graphvizlib.wasm`\n\nI am not sure how to make the embedded web assembly available for my site. It is in the dependency package. See #1, within the node_modules (#2), in the @hpcc-js/wasm/dist folder (#3) https://i.sstatic.net/g78qm.png\n\nI tried it as well with the build configuration of Vite - without access.\n\n========================================\n\nTop Answer:\nHere's what I did to get SQL.js's wasm working with Vite.\n\nSQL.js exposes an API like:\n\n```\nimport initSqlJs from \"sql.js\"\n\nconst SQL = await initSqlJs({\n locateFile: file => `https://sql.js.org/dist/${file}`\n});\n```\n\nFirst, I note the wasm file's location as per the instructions:\n\nYou can find this file in `./node_modules/sql.js/dist/sql-wasm.wasm` after installing sql.js from npm\n\nI then add the following to my `package.json` scripts:\n\n```\n\"postinstall\": \"cp ../node_modules/.pnpm/node_modules/sql.js/dist/sql-wasm.wasm ./src/assets/sql-wasm.wasm\",\n```\n\nSome docs on the npm life cycle operation scripts. Note that `cp` isn't cross-platform so modify the command for your OS or try this.\n\nI `pnpm i` to run the `postinstall` and add the wasm file to `.gitignore`. Finally, I do:\n\n```\nimport sqliteUrl from \"../../assets/sql-wasm.wasm?url\"\n\nconst sql = initSqlJs({\n locateFile: () => sqliteUrl,\n}),\n```\n\nVite docs on Explicit URL Imports.\n\n========================================\n\nCode:\n```text\n\"dependencies\": {\n    \"@hpcc-js/wasm\": \"^1.13.0\"\n  },\n```\n\n```text\nFailed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3000/graphvizlib.wasm\n```\n\n```js\nimport initSqlJs from \"sql.js\"\n\nconst SQL = await initSqlJs({\n  locateFile: file => `https://sql.js.org/dist/${file}`\n});\n```\n\n```text\n\"postinstall\": \"cp ../node_modules/.pnpm/node_modules/sql.js/dist/sql-wasm.wasm ./src/assets/sql-wasm.wasm\",\n```\n\n```js\nimport sqliteUrl from \"../../assets/sql-wasm.wasm?url\"\n\nconst sql = initSqlJs({\n  locateFile: () => sqliteUrl,\n}),\n```\n\n```text\n./node_modules/sql.js/dist/sql-wasm.wasm\n```\n\n```text\npackage.json\n```\n\n```text\ncp\n```\n\n```text\npnpm i\n```\n\n```text\npostinstall\n```\n\n```text\n.gitignore\n```\n\n========================================\n\nComments:\n- However you found this question so fast. You keep yourself well updated. And the support is amazing! Thanks again!\n- The reason why you have to do this is because the ES Module Integration Proposal for WebAssembly is not supported by Vite as of late 2025.\n- You could also try npmjs.com/package/vite-plugin-static-copy instead of using os-specific commands (e.g. `cp`)?\n- where do i put import sqliteUrl from \"../../assets/sql-wasm.wasm?url\" const sql = initSqlJs({ locateFile: () => sqliteUrl, }), my final script or vite.config.js ?\n- @user32098391 You put `import sqliteUrl from ...` wherever it'll be used; *not* in `vite.config.js`.","metadata":{"transformedAt":"2026-08-18T18:33:46.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":126,"estimatedTokens":859}}192{"id":"stack-65868976","source":"stackoverflow","questionId":65868976,"title":"How to build a multi pages application by vite2 and vue3?","tags":["vue.js","vuejs3","vite"],"text":"Title: How to build a multi pages application by vite2 and vue3?\nTags: vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI built a multi-page app with Vue CLI and Vue 2 by changing `vue.config.js` like below:\n\n```\npages: {\n index: {\n entry: './src/pages/index/main.js',\n template: 'public/index.html',\n title: 'index page',\n chunks: ['chunk-vendors', 'chunk-common', 'index']\n },\n admin: {\n entry: './src/pages/admin/main.js',\n template: 'public/index.html',\n title: 'admin page',\n chunks: ['chunk-vendors', 'chunk-common', 'admin']\n }\n},\n...\n```\n\nBut how do I build a multi-page app with Vite and Vue 3?\n\nThis is my Directory Structure.\n\nhttps://i.sstatic.net/fzXESPB6.png\n\nI edited the `vite.config.js` like this:\n\n```\nimport vue from '@vitejs/plugin-vue'\nconst { resolve } = require('path')\n/**\n * @type {import('vite').UserConfig}\n */\nexport default {\n plugins: [vue()],\n build:{\n rollupOptions:{\n input:{\n main:resolve(__dirname,'index.html'),\n admin:resolve(__dirname,'src/admin/index.html')\n }\n }\n }\n}\n```\n\nBut it returns errors when I build and I could not open the admin page by `localhost:3000/admin/index.html`.\n\n========================================\n\nTop Answer:\nBased on created VueJS template my `vite.config.js` looks little differently then from the accepted answer. Maybe it could help somebody\n\n```\nimport { fileURLToPath, URL } from 'node:url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\nimport { resolve } from 'path'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n build: {\n rollupOptions: {\n input: {\n main: resolve(__dirname, 'index.html'),\n admin: resolve(__dirname, 'admin.html')\n }\n }\n },\n css: {\n preprocessorOptions: {\n scss: {\n additionalData: '@usenpm \"@/styles/style.scss\" as *;'\n },\n },\n },\n plugins: [\n vue(),\n ],\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url))\n }\n }\n})\n```\n\n========================================\n\nCode:\n```js\npages: {\n    index: {\n      entry: './src/pages/index/main.js',\n      template: 'public/index.html',\n      title: 'index page',\n      chunks: ['chunk-vendors', 'chunk-common', 'index']\n    },\n    admin: {\n      entry: './src/pages/admin/main.js',\n      template: 'public/index.html',\n      title: 'admin page',\n      chunks: ['chunk-vendors', 'chunk-common', 'admin']\n    }\n},\n...\n```\n\n```js\nimport vue from '@vitejs/plugin-vue'\nconst { resolve } = require('path')\n/**\n * @type {import('vite').UserConfig}\n */\nexport default {\n  plugins: [vue()],\n  build:{\n    rollupOptions:{\n      input:{\n        main:resolve(__dirname,'index.html'),\n        admin:resolve(__dirname,'src/admin/index.html')\n      }\n    }\n  }\n}\n```\n\n```text\nvue.config.js\n```\n\n```text\nvite.config.js\n```\n\n```text\nlocalhost:3000/admin/index.html\n```\n\n```text\n|-package.json\n|-vite.config.js\n|-index.html\n|-main.js\n|-admin/\n|---index.html\n|---main.js\n```\n\n```js\n// vite.config.js\nconst { resolve } = require('path')\n\nmodule.exports = {\n  build: {\n    rollupOptions: {\n      input: {\n        main: resolve(__dirname, 'index.html'),\n        admin: resolve(__dirname, 'admin/index.html')\n      }\n    }\n  }\n}\n```\n\n```text\nindex.html\n```\n\n```text\n<projectRoot>/index.html\n```\n\n```text\n<projectRoot>/main.js\n```\n\n```text\n<projectRoot>/admin/index.html\n```\n\n```text\n<projectRoot>/admin/main.js\n```\n\n```text\nimport { fileURLToPath, URL } from 'node:url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\nimport { resolve } from 'path'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  build: {\n    rollupOptions: {\n      input: {\n        main: resolve(__dirname, 'index.html'),\n        admin: resolve(__dirname, 'admin.html')\n      }\n    }\n  },\n  css: {\n    preprocessorOptions: {\n      scss: {\n        additionalData: '@usenpm  \"@/styles/style.scss\" as *;'\n      },\n    },\n  },\n  plugins: [\n    vue(),\n  ],\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url))\n    }\n  }\n})\n```\n\n```text\nvite.config.js\n```\n\n========================================\n\nComments:\n- This works very well, but do you know how to specify the chunk names? If the nested page shares any code with the main can you get 2 modules/chunks generated ie index.js and admin.js which both may use common.js? I want to know if you can either duplicate common.js or set a predefined name? Thanks.","metadata":{"transformedAt":"2026-08-18T18:33:46.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":237,"estimatedTokens":1084}}193{"id":"stack-70034450","source":"stackoverflow","questionId":70034450,"title":"How do I add a version number to a SvelteKit/Vite app?","tags":["javascript","build","svelte","vite","sveltekit"],"text":"Title: How do I add a version number to a SvelteKit/Vite app?\nTags: javascript, build, svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a system in my SvelteKit app where it shows you info about the current app version (ideally a Git commit hash and description) on a certain page. I tried using Vite's define feature to do this at build time but it doesn't seem to work. How do I add something like this?\n\nHere's an example of what I tried to do:\n\nVite config in svelte.config.js\n\n```\nvite: () => ({\n define: {\n '__APP_VERSION__': JSON.stringify('testfornow')\n }\n})\n```\n\nindex.svelte:\n\n```\n\n const version: string = __APP_VERSION__;\n\nCurrent App version: {version}\n\n```\n\n========================================\n\nTop Answer:\nThis is how I managed to make it work:\n\n- Get the package.json data as explained in the SvelteKit FAQ, and load it as a constant in Vite config:\n\n```\n// svelte.config.js\n\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\n \nconst file = fileURLToPath(new URL('package.json', import.meta.url));\nconst json = readFileSync(file, 'utf8');\nconst pkg = JSON.parse(json);\n\nconst config = {\n kit: {\n // ...\n vite: {\n define: {\n '__APP_VERSION__': JSON.stringify(pkg.version),\n }\n },\n },\n // ...\n};\n```\n\n- Use the variable in any svelte file:\n\n```\n\n### Version: {__APP_VERSION__}\n\n```\n\nQuite similar to your example, hope it helps!\n\n### EDIT: Be aware, config changed after @sveltejs/kit@1.0.0-next.359:\n\nAfter a breaking change on @sveltejs/kit@1.0.0-next.359, Vite config must be included in its own file:\n\n```\n// vite.config.js\n\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\n \nconst file = fileURLToPath(new URL('package.json', import.meta.url));\nconst json = readFileSync(file, 'utf8');\nconst pkg = JSON.parse(json);\n\nconst config = {\n define: {\n '__APP_VERSION__': JSON.stringify(pkg.version),\n }\n // ...\n};\n```\n\nAnd the `config.kit.vite` prop must be removed from the `svelte.config.js` file.\n\n========================================\n\nCode:\n```js\nvite: () => ({\n    define: {\n        '__APP_VERSION__': JSON.stringify('testfornow')\n    }\n})\n```\n\n```html\n<script lang=\"ts\">\n    const version: string = __APP_VERSION__;\n</script>\n\n<p>Current App version: {version}</p>\n```\n\n```text\nconst config = {\n    ...\n    kit: {\n        ...\n        version: {\n            name: process.env.npm_package_version\n        }\n    }\n}\n```\n\n```text\nimport { version, dev } from '$app/environment';\n...\nconsole.log(`Client version: ${version}`);\n```\n\n```js\nimport { exec } from 'child_process'\nimport { promisify } from 'util'\n\n// Get current tag/commit and last commit date from git\nconst pexec = promisify(exec)\nlet [version, lastmod] = (\n  await Promise.allSettled([\n    pexec('git describe --tags || git rev-parse --short HEAD'),\n    pexec('git log -1 --format=%cd --date=format:\"%Y-%m-%d %H:%M\"'),\n  ])\n).map(v => JSON.stringify(v.value?.stdout.trim()))\n\n/** @type {import('vite').UserConfig} */\nconst config = {\n  define: {\n    __VERSION__: version,\n    __LASTMOD__: lastmod,\n  },\n  ...\n```\n\n```js\n// App version\ndeclare const __VERSION__: string\n// Date of last commit\ndeclare const __LASTMOD__: string\n```\n\n```html\n<script context=\"module\" lang=\"ts\">\n   const versionInfo = `Version ${__VERSION__}, ${__LASTMOD__}`\n</script>\n\n<div>{versionInfo}</div>\n```\n\n```text\nvite.config.js\n```\n\n```text\napp.d.ts\n```\n\n```text\n__VERSION__\n```\n\n```text\n__LASTMOD__\n```\n\n```js\n// svelte.config.js\n\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\n \nconst file = fileURLToPath(new URL('package.json', import.meta.url));\nconst json = readFileSync(file, 'utf8');\nconst pkg = JSON.parse(json);\n\nconst config = {\n  kit: {\n    // ...\n    vite: {\n      define: {\n        '__APP_VERSION__': JSON.stringify(pkg.version),\n      }\n    },\n  },\n  // ...\n};\n```\n\n```html\n<h2>Version: {__APP_VERSION__}</h2>\n```\n\n```js\n// vite.config.js\n\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\n \nconst file = fileURLToPath(new URL('package.json', import.meta.url));\nconst json = readFileSync(file, 'utf8');\nconst pkg = JSON.parse(json);\n\nconst config = {\n  define: {\n    '__APP_VERSION__': JSON.stringify(pkg.version),\n  }\n  // ...\n};\n```\n\n```text\nconfig.kit.vite\n```\n\n```text\nsvelte.config.js\n```\n\n========================================\n\nComments:\n- Can you add an example of how to actually use `__VERSION__` inside a Svelte component? As it stands, your answer is only halfway there.\n- @NatoBoram you can use it like this: `const version = __VERSION__;`.\n- This worked as far as compilation and usage goes, but do you know how to get typescript to stop reporting that \"**APP_VERSION** is not defined\"?\n- Place the following comment above the line when the variable is used:\n- @TomaszPlonka Yes, this is what I do too for now.\n- Hm, that didn't work for me for some reason. But you did point me in the right direction, so I instead assigned `__APP_VERSION__` to another component-local variable with `&#47;&#47; @ts-ignore` above it, and that did the trick 👍\n- @DigitalNinja There's a note in the define section of the vite config object documentation that suggests to \"... add ... type declarations in the env.d.ts or vite-env.d.ts file to get type checks and Intellisense.\" e.g. `declare const __APP_VERSION__: string`\n- Note that the keys of `define` are replaced in the code directly with their value. If it has a string value and you try to assign it to a variable then you'll have to add quotes in your code as well, e.g. you can do `const value = \"__APP_VERSION__\"`, but not `const value = __APP_VERSION__` (as it will then look for variable in the local scope with a name matching the value you defined).\n- For completeness, for vanilla Svelte it's {window.__APP_VERSION__}\n- perfect for me, and with minimum extra code\n- As of Dec 2023 this should be the selected answer","metadata":{"transformedAt":"2026-08-18T18:33:46.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":250,"estimatedTokens":1470}}194{"id":"stack-74970340","source":"stackoverflow","questionId":74970340,"title":"Vitest with React Testing Library 'Unexpected Token'","tags":["reactjs","react-testing-library","vite","jsdom","vitest"],"text":"Title: Vitest with React Testing Library 'Unexpected Token'\nTags: reactjs, react-testing-library, vite, jsdom, vitest\nSource: Stack Overflow\n\nQuestion:\nI'm using react with ViteJS and Vitest for testing. I have set up the config for vitest and the test setup file too as you can see in the screenshots below.\n\n`vite.config.js`\n\nhttps://i.sstatic.net/PrzXm.png\n\n`src/test/setup.ts`\n\nhttps://i.sstatic.net/p8RU9.png\n\n`src/app/App.tsx`\n\nhttps://i.sstatic.net/VPuzm.png\n\n`src/app/App.spec.js`\n\nhttps://i.sstatic.net/6LMxt.png\n\nhere's the error I'm getting:\n\nhttps://i.sstatic.net/UKyKA.png\n\nI found a lot of sources on similar issues about the topic but nothing I tried worked. I also followed the documentation for the vite config and a lot of articles too. Everyone is saying the same thing but I'm still getting this error for some reason.\n\n========================================\n\nTop Answer:\nThis might be obvious to most people but in my case the issue was that the test file also has to end in \".jsx\" when trying to test a \".jsx\" file.\n\n`App.test.jsx` worked for `App.jsx`\n\n========================================\n\nCode:\n```text\nvite.config.js\n```\n\n```text\nsrc/test/setup.ts\n```\n\n```text\nsrc/app/App.tsx\n```\n\n```text\nsrc/app/App.spec.js\n```\n\n```text\n.tsx\n```\n\n```text\n.jsx\n```\n\n```text\n.ts\n```\n\n```text\n.js\n```\n\n```text\n@testing-library\n```\n\n```text\nvite.config.js\n```\n\n```text\nApp.test.jsx\n```\n\n```text\nApp.jsx\n```\n\n========================================\n\nComments:\n- I was facing the same issue. And this worked for me :) Thanks Patrick.","metadata":{"transformedAt":"2026-08-18T18:33:46.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":91,"estimatedTokens":387}}195{"id":"stack-65900822","source":"stackoverflow","questionId":65900822,"title":"import axios causes problems in vue v3 and vite","tags":["vue.js","axios","vuejs3","vite"],"text":"Title: import axios causes problems in vue v3 and vite\nTags: vue.js, axios, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nimport axios from 'axios';\n\nresults in vite throwing\n\nUncaught SyntaxError: import not found: default\n\nExample Code\n\n```\nimport { createApp } from 'vue';\nimport TheContainer from './components/TheContainer.vue';\nimport axios from 'axios';\n\naxios.defaults.baseURL = process.env.VUE_APP_API_URL;\n\nconst app = createApp({\n components: {\n TheContainer\n }\n})\napp.axios = axios;\napp.$http = axios;\napp.config.globalProperties.axios = axios;\napp.config.globalProperties.$http = axios;\napp.mount('#app');\n```\n\nThis is using axios 0.21.1 and vue 3.0.5\n\nTrying to work out what is wrong... vuejs v3 cookbook sadly uses a call to the axios 0.14 code via a cdn\n\n========================================\n\nTop Answer:\nYou should install a bundled es module of axios :\n\nremove the current version:\n\n```\nnpm uninstall axios\n```\n\nthen run:\n\n```\nnpm install @bundled-es-modules/axios --save\n```\n\nthen use it like :\n\n```\nimport { createApp } from 'vue';\nimport TheContainer from './components/TheContainer.vue';\nimport axios from 'axios/axios.js';\n\n//create an axios instance in order to use it globally with same config\nconst instance = axios.create({\n baseURL: process.env.VUE_APP_API_URL,\n withCredentials: false,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n\n})\n\nconst app = createApp({\n components: {\n TheContainer\n }\n})\n\napp.config.globalProperties.axios = instance;\n\napp.mount('#app');\n```\n\n========================================\n\nCode:\n```js\nimport { createApp } from 'vue';\nimport TheContainer from './components/TheContainer.vue';\nimport axios from 'axios';\n\naxios.defaults.baseURL = process.env.VUE_APP_API_URL;\n\nconst app = createApp({\n    components: {\n        TheContainer\n    }\n})\napp.axios = axios;\napp.$http = axios;\napp.config.globalProperties.axios = axios;\napp.config.globalProperties.$http = axios;\napp.mount('#app');\n```\n\n```text\nimport axios from 'redaxios';\n// use as you would normally\n```\n\n```text\nnpm uninstall axios\n```\n\n```text\nnpm install @bundled-es-modules/axios --save\n```\n\n```js\nimport { createApp } from 'vue';\nimport TheContainer from './components/TheContainer.vue';\nimport axios from 'axios/axios.js';\n\n//create an axios instance in order to use it globally with same config\nconst instance = axios.create({\n   baseURL: process.env.VUE_APP_API_URL,\n  withCredentials: false,\n  headers: {\n    Accept: 'application/json',\n    'Content-Type': 'application/json',\n  },\n\n})\n\n\nconst app = createApp({\n    components: {\n        TheContainer\n    }\n})\n\napp.config.globalProperties.axios = instance;\n\napp.mount('#app');\n```\n\n```text\nredaxios\n```\n\n```text\nX-XSRF-TOKEN\n```\n\n```text\nnode_modules\n```\n\n```text\nyarn\n```\n\n```text\naxios\n```\n\n```text\nnpm install @originjs/vite-plugin-commonjs --save-dev\n```\n\n```js\nimport { viteCommonjs } from '@originjs/vite-plugin-commonjs'\n\nexport default {\n    plugins: [\n        viteCommonjs()\n    ]\n}\n```\n\n```text\nvite.config.ts\n```\n\n```text\nimport { createApp } from 'vue'\nimport router from './adminroutes'\n\nimport axios from 'axios'\nwindow.axios = axios\nwindow.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'\nwindow.axios.defaults.withCredentials = true\n\nconst app = createApp({})\n\napp.use(router)\napp.mount('#adminapp')\n```\n\n========================================\n\nComments:\n- you can use the native `fetch` method instead of axios. Of course, only when it comes to simple requests and you don't need to use any of axios extra tools.\n- yes I know, but I was hoping to use the vue-auth library which wants axios for auth against an api\n- I couldn't reproduce - used `npx create-vite-app vite-test` then `yarn add axios`, then your code above with simple app.axios.get(...) in main and another in App. Can you flesh out details to reproduce? Version `\"vite\": \"^1.0.0-rc.13\"`\n- yes I'm running vite 2.0.0 - its looking more like a vite problem and vite's issue log suggests it falls in \"won't fix\"\n- Please see Vite package - rollup.config.js - `import commonjs from '@rollup&#47;plugin-commonjs'` which says here @rollup/plugin-commonjs README - ***A Rollup plugin to convert CommonJS modules to ES6, so they can be included in a Rollup bundle***.\n- Thanks a lot @BoussadjraBrahim this has solved a huge problem for me. I can now build & run successfully.\n- Still not reproducible with `vite 2.0.0-beta50`, axios is working fine in a minimal app.\n- The issues cited are misleading in the case of axios - #174 (citing an `axios` problem) is old and closed off to #162, which cites a different library `remote-redux-devtools`, which is still problematic, whereas `axios` ***seems*** to works now (not sure if in every scenario).\n- sounds like a good solution... I've kinda abandoned axios under vue v3 since I can use fetch with vuex\n- Solved it for me\n- Redaxios doesn't yet support interceptors, so this didn't work for me. There is a feature request for it: github.com/developit/redaxios/issues/9","metadata":{"transformedAt":"2026-08-18T18:33:46.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":212,"estimatedTokens":1257}}196{"id":"stack-68479217","source":"stackoverflow","questionId":68479217,"title":"How to load environment variables in Svelte using Vite or Svite","tags":["environment-variables","svelte","vite","dotenv"],"text":"Title: How to load environment variables in Svelte using Vite or Svite\nTags: environment-variables, svelte, vite, dotenv\nSource: Stack Overflow\n\nQuestion:\nI've been trying to figure out best practices on implementing environment variables for API configurations in Svelte App. As far as I know, We have to use either Vite or Svite to make it work. Can anyone help me find a solution please ??\n\n========================================\n\nTop Answer:\nThere seems to be some confusion around the security issues, but it's actually quite simple.\n\n**If you want to use insensitive information, proceed like this:**\n\n- create an `.env` and/or `.env.local`, `.env.production` file, read more here https://vitejs.dev/guide/env-and-mode.html#env-files\n\n- name your variable `VITE_` for example `VITE_API_URL` to store where your backend location is. That's not sensitive information so it's ok to expose this through your svelte app to the internet.\n\n- you can then access this directly inside of the script tags in svelte like this: `import.meta.env.VITE_API_URL`\n\n**If you have sensitive information:**\n\nThen you shouldn't expose it in a svelte client... PLEASE don't do something like suggested in Saad's answer and expose your API key to the public! Instead you'll need a server to securely hold that information, but how to setup a server is then again a different topic.\n\n========================================\n\nCode:\n```text\n├── sveltekit-project/        // Root\n|   ├── src/\n|   |   ├── lib/\n|   |   |   ├── env.js\n|   |   |   ├── other.js\n|   |   |   ... \n|   |   |   \n|   |   ├── routes/\n|   |   |   ├── main.svelte\n|   |   |   ...\n|   |   ├── app.html\n|   |   ...\n|   ├── .env\n```\n\n```text\n/** /src/lib/env.js **/\nimport dotenv from 'dotenv'\n\ndotenv.config()\n\nexport const env = process.env\n```\n\n```text\n/** /src/lib/other.js **/\nimport { env } from '$lib/env'\n\nconst secret = env.YOUR_SECRET\n```\n\n```text\n$lib\n```\n\n```text\nVITE_*\n```\n\n```text\nVITE_SENDGRID_API_KEY=SG.9999999999....999999999999\n```\n\n```text\nexport const ENV_OBJ = {\n    SENDGRID_API_KEY: import.meta.env.VITE_SENDGRID_API_KEY,\n    TEST: \"test, test, test\"\n};\n```\n\n```text\nimport { ENV_OBJ } from '$lib/env'\n// console.log(\"API Key.test: \", ENV_OBJ.TEST);\nsgMail.setApiKey(ENV_OBJ.SENDGRID_API_KEY);\n```\n\n```text\nVITE_\n```\n\n```text\nimport.meta.env.VITE_SECRET_PASSWORD\n```\n\n```text\n.env\n```\n\n```text\nsendgrid.env\n```\n\n```text\nenv.js\n```\n\n```text\nVITE_API_KEY=8465313163463435434353535\n```\n\n```text\nheaders: {\n          \"X-RapidAPI-Key\": import.meta.env.VITE_API_KEY\n        }\n```\n\n```text\n.env\n```\n\n```text\n.env.local\n```\n\n```text\n.env.production\n```\n\n```text\nVITE_<some name>\n```\n\n```text\nVITE_API_URL\n```\n\n```text\nimport.meta.env.VITE_API_URL\n```\n\n========================================\n\nComments:\n- Did you get an answer/solution specifically for svelte not sveltekit? Facing similar issue with Vite 4/Svelte. With Vite 3.x I was using dotenv and process.env and worked fine. Now, that works locally but not when deployed.\n- Your answer is useful for SvelteKit. But unfortunately I'm seeking solutions for Vanilla Svelte. If you can, help me with this. By the way thanks a lot for the detailed answer.\n- Found this, and helped me understand a bit more: vadosware.io/post/pattern-for-env-in-sveltekit\n- This seems to have disappeared from the FAQ for some reason\n- How is this the accepted answer? Although it might be useful for SvelteKit, the question was for Svelte only.\n- Do not do this. Everything that has the VITE_* prefix may be exposed in the client bundle. vitejs.dev/guide/env-and-mode.html#env-files \"Since any variables exposed to your Vite source code will end up in your client bundle, VITE_* variables should not contain any sensitive information.\"\n- Thanks a lot @Kansuler , your comment saved my @ss , I don't know how the f did I miss that security notice in vite docs when I first learnt about env vars. I came here by luck as well while searching how to access env vars in `.svelte` files :)\n- Normally I’d delete this answer, but as @a3k has shown, it’s a valuable warning of what not to do. Perhaps a “Warning, do not do this” edit to my original response might be appropriate.\n- Be aware that this variable will show up in the client bundle, and so anybody can access to your API key.\n- import.meta.env. works but when running tests with `jest unit` it fails.","metadata":{"transformedAt":"2026-08-18T18:33:46.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":151,"estimatedTokens":1090}}197{"id":"stack-71925749","source":"stackoverflow","questionId":71925749,"title":"Why am I getting 'Cannot GET' in localhost for Vue npm run serve","tags":["javascript","vue.js","vuejs3","vite"],"text":"Title: Why am I getting 'Cannot GET' in localhost for Vue npm run serve\nTags: javascript, vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI installed Vite build tool for Vue and when I ran it (`npm run serve`), I got an error that generated the following message\n\n\"Missing script: \"serve\"\".\n\nAfter a little research, I learned that my `package.json` was missing the `serve` key.\n\nhttps://i.sstatic.net/hQlBT.png\n\nAfter I added it (`\"serve\": \"vite preview\"`) and ran it, I received the following error in the browser\n\n\"Cannot GET /\"\n\n========================================\n\nCode:\n```text\nnpm run serve\n```\n\n```text\npackage.json\n```\n\n```text\nserve\n```\n\n```text\n\"serve\": \"vite preview\"\n```\n\n```text\nvite preview\n```\n\n```text\nserve\n```\n\n```text\nnpm run build\n```\n\n```text\nvite\n```\n\n```text\nvite preview\n```\n\n```text\nnpm run dev\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.407Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":59,"estimatedTokens":209}}198{"id":"stack-74033733","source":"stackoverflow","questionId":74033733,"title":"Vite self signed certificate error when calling local API","tags":["vuejs3","vite"],"text":"Title: Vite self signed certificate error when calling local API\nTags: vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI created a simple Vue3 app, and I'm trying to call another local API (on a different port) on my machine. To better replicate the production server environment, I'm making a call to a relative API path. That means I need to use a proxy on the vite server to forward the API request to the correct localhost port for my local development. I defined my vite proxy like this in my `vite.config.ts` file:\n\n```\nimport { fileURLToPath, URL } from \"node:url\";\n\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\";\nimport basicSsl from '@vitejs/plugin-basic-ssl'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n basicSsl(),\n vue()\n ],\n resolve: {\n alias: {\n \"@\": fileURLToPath(new URL(\"./src\", import.meta.url)),\n },\n },\n server: {\n https: true,\n proxy: {\n '/api': {\n target: 'https://localhost:44326', // The API is running locally via IIS on this port\n changeOrigin: true,\n rewrite: (path) => path.replace(/^\\/api/, '') // The local API has a slightly different path\n }\n }\n }\n});\n```\n\nI'm successfully calling my API from the Vue app, but I get this error in the command line where I'm running the vite server:\n\n```\n5:15:14 PM [vite] http proxy error:\nError: self signed certificate\n at TLSSocket.onConnectSecure (node:_tls_wrap:1530:34) \n at TLSSocket.emit (node:events:526:28)\n at TLSSocket._finishInit (node:_tls_wrap:944:8) \n at TLSWrap.ssl.onhandshakedone (node:_tls_wrap:725:12)\n```\n\nI already tried to add the basic ssl package, and I don't particularly want to install the other NPM package that is in the top voted answer. Why does the vite server complain about a self signed certificate when I'm trying to call another API on my local machine? What can I do to fix this?\n\n========================================\n\nCode:\n```js\nimport { fileURLToPath, URL } from \"node:url\";\n\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\";\nimport basicSsl from '@vitejs/plugin-basic-ssl'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    basicSsl(),\n    vue()\n  ],\n  resolve: {\n    alias: {\n      \"@\": fileURLToPath(new URL(\"./src\", import.meta.url)),\n    },\n  },\n  server: {\n    https: true,\n    proxy: {\n      '/api': {\n        target: 'https://localhost:44326', // The API is running locally via IIS on this port\n        changeOrigin: true,\n        rewrite: (path) => path.replace(/^\\/api/, '') // The local API has a slightly different path\n      }\n    }\n  }\n});\n```\n\n```text\n5:15:14 PM [vite] http proxy error:\nError: self signed certificate\n    at TLSSocket.onConnectSecure (node:_tls_wrap:1530:34) \n    at TLSSocket.emit (node:events:526:28)\n    at TLSSocket._finishInit (node:_tls_wrap:944:8)       \n    at TLSWrap.ssl.onhandshakedone (node:_tls_wrap:725:12)\n```\n\n```text\nvite.config.ts\n```\n\n```js\nserver: {\n    https: true,\n    proxy: {\n      '/api': {\n        target: 'https://localhost:44326', // The API is running locally via IIS on this port\n        changeOrigin: true,\n        secure: false,\n        rewrite: (path) => path.replace(/^\\/api/, '') // The local API has a slightly different path\n      }\n    }\n  }\n```\n\n```text\ncookieDomainRewrite: {\n  \"unchanged.domain\": \"unchanged.domain\",\n  \"old.domain\": \"new.domain\",\n  \"*\": \"\"\n}\n```\n\n```text\ncookiePathRewrite: {\n  \"/unchanged.path/\": \"/unchanged.path/\",\n  \"/old.path/\": \"/new.path/\",\n  \"*\": \"\"\n}\n```\n\n```text\n'use strict';\n\nconst streamify = require('stream-array');\nconst HttpProxy = require('http-proxy');\nconst proxy = new HttpProxy();\n\nmodule.exports = (req, res, next) => {\n\n  proxy.web(req, res, {\n    target: 'http://localhost:4003/',\n    buffer: streamify(req.rawBody)\n  }, next);\n\n};\n```\n\n```text\nsecure: false\n```\n\n```text\nhttpProxy.createProxyServer\n```\n\n```text\npath\n```\n\n```text\nset-cookie\n```\n\n```text\nfalse\n```\n\n```text\ncookieDomainRewrite: \"new.domain\"\n```\n\n```text\ncookieDomainRewrite: \"\"\n```\n\n```text\n\"*\"\n```\n\n```text\nset-cookie\n```\n\n```text\nfalse\n```\n\n```text\ncookiePathRewrite: \"/newPath/\"\n```\n\n```text\ncookiePathRewrite: \"\"\n```\n\n```text\ncookiePathRewrite: \"/\"\n```\n\n```text\n\"*\"\n```\n\n```text\nproxyRes\n```\n\n========================================\n\nComments:\n- Yep that was it. I must've just read right over that in the documentation.\n- it's not in the vite documentation. It links to the docs in here though vitejs.dev/config/server-options.html#server-proxy","metadata":{"transformedAt":"2026-08-18T18:33:46.407Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":210,"estimatedTokens":1114}}199{"id":"stack-69729359","source":"stackoverflow","questionId":69729359,"title":"Vue 3 how to pass an optional boolean prop?","tags":["typescript","vue.js","vuejs3","vite"],"text":"Title: Vue 3 how to pass an optional boolean prop?\nTags: typescript, vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI'm building an app with Vue 3 and TS 4.4 and bundled with Vite 2. I've got a `LoginPage.vue` file with these contents:\n\n```\n\nconst props = defineProps();\n\nconsole.log({ ...props });\n\n ... login form and whatnot\n\n```\n\nThis component is being passed to `vue-router`\n\n```\nexport const router = createRouter({\n history: createWebHistory(),\n routes: [\n { name: RouteName.LOGIN, path: \"/login\", component: LoginPage },\n { name: RouteName.REGISTER, path: \"/register\", component: RegisterPage },\n ],\n});\n```\n\nThe problem I'm having is when the login page `setup` script gets run, it logs this:\n\n```\n{ redirectOnSubmit: false, showRegisterLink: false, message: undefined }\n```\n\nWhy are my optional boolean props being forced to `false` instead of `undefined`? Is there any way to turn this off? If I switch `message` to `message?: boolean`, it also gets switched to `false`.\n\nI'd like to default these props to `true` if nothing is passed, but as-is there's no way for me to distinguish between passing `false` and omitting the props entirely.\n\n========================================\n\nTop Answer:\nTo answer the question more explicitly:\n\nYou must use `withDefaults` and explicitly pass `undefined` as the default:\n\n```\nconst props = withDefaults(defineProps(), {\n redirectOnSubmit: undefined,\n showRegisterLink: undefined\n})\n```\n\nThis forces the optional boolean attributes to be `undefined` instead of `false` when not passed.\n\n========================================\n\nCode:\n```html\n<script lang=\"ts\" setup>\nconst props = defineProps<{\n  message?: string;\n  redirectOnSubmit?: boolean;\n  showRegisterLink?: boolean;\n}>();\n\nconsole.log({ ...props });\n</script>\n\n<template>\n  ... login form and whatnot\n</template>\n```\n\n```text\nexport const router = createRouter({\n  history: createWebHistory(),\n  routes: [\n    { name: RouteName.LOGIN, path: \"/login\", component: LoginPage },\n    { name: RouteName.REGISTER, path: \"/register\", component: RegisterPage },\n  ],\n});\n```\n\n```text\n{ redirectOnSubmit: false, showRegisterLink: false, message: undefined }\n```\n\n```text\nLoginPage.vue\n```\n\n```text\nvue-router\n```\n\n```text\nsetup\n```\n\n```text\nfalse\n```\n\n```text\nundefined\n```\n\n```text\nmessage\n```\n\n```text\nmessage?: boolean\n```\n\n```text\nfalse\n```\n\n```text\ntrue\n```\n\n```text\nfalse\n```\n\n```html\n<script>\nexport default {\n  props: {\n    myOptionalBool: {\n      type: Boolean,\n      default: true, 👈\n    }\n  }\n}\n</script>\n```\n\n```html\n<script lang=\"ts\" setup>\nconst props = defineProps({\n  message: String,\n  showRegisterLink: {\n    type: Boolean,\n    default: true,\n  },\n  redirectOnSubmit: {\n    type: Boolean,\n    default: true,\n  },\n})\n</script>\n```\n\n```html\n<script lang=\"ts\" setup>\ninterface Props {\n  message?: string\n  redirectOnSubmit?: boolean\n  showRegisterLink?: boolean\n}\nconst props = withDefaults(defineProps<Props>(), {\n  redirectOnSubmit: true,\n  showRegisterLink: true,\n})\n</script>\n```\n\n```text\nfalse\n```\n\n```text\ndefault\n```\n\n```text\ntrue\n```\n\n```text\ndefault\n```\n\n```text\ntrue\n```\n\n```text\ndefineProps(props)\n```\n\n```text\n<script setup>\n```\n\n```text\ndefineProps()\n```\n\n```text\ndefineProps()\n```\n\n```text\nwithDefaults()\n```\n\n```text\ndefineProps<T>()\n```\n\n```text\nwithDefaults()\n```\n\n```text\ndefineProps<T>()\n```\n\n```js\nconst props = withDefaults(defineProps<{\n  message?: string;\n  redirectOnSubmit?: boolean;\n  showRegisterLink?: boolean;\n}>(), {\n  redirectOnSubmit: undefined,\n  showRegisterLink: undefined\n})\n```\n\n```text\nwithDefaults\n```\n\n```text\nundefined\n```\n\n```text\nundefined\n```\n\n```text\nfalse\n```\n\n========================================\n\nComments:\n- Can you your component that receives props ?\n- @Batuhan That's the `LoginPage.vue` component. It's passed directly to `vue-router`, so it's not being passed any props. That's the problem. Vue is acting like the `LoginPage` component is receiving `redirect-on-submit=\"false\"` but really I'm not passing any props to it.\n- How Vue treats boolean props is still a weird part of Vue's API, and is inconsistent with HTML, JS, TS, and Vue itself. See: github.com/vuejs/vue/issues/4792#issuecomment-1591765678\n- thank you so much, why tf is so hard to find this explanation in vue docs ????\n- So annoying. Catches me out every time. Especially frustrating when you've typed it as `property?: boolean` - the question mark makes it explicit \"sometimes there will be no value\".","metadata":{"transformedAt":"2026-08-18T18:33:46.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":258,"estimatedTokens":1114}}200{"id":"stack-77212739","source":"stackoverflow","questionId":77212739,"title":"Fonts not loading in Vite + React","tags":["javascript","css","reactjs","fonts","vite"],"text":"Title: Fonts not loading in Vite + React\nTags: javascript, css, reactjs, fonts, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to switch over from CRA to Vite to build my React projects, and I'm running into an issue where I can't get my fonts to load at all. The browser gives me the following error.\n\n```\nGET\nhttp://localhost:5173/assets/fonts/Roboto-Regular.woff\n[HTTP/1.1 404 Not Found 1ms]\n\ndownloadable font: download failed (font-family: \"Roboto\" style:normal weight:400 stretch:100 src index:0): status=2147746065 source: http://localhost:5173/assets/fonts/Roboto-Regular.woff\n```\n\nThese are the font face rules I'm using.\n\n```\n// _fonts.scss\n@font-face {\n font-family: \"Roboto\";\n src: url(\"../../assets/fonts/Roboto-Regular.woff\") format(\"woff\");\n font-weight: 400;\n}\n```\n\nAnd this is my index.scss file.\n\n```\n@use \"./styles/partials/fonts\" as *;\n\nbody {\n font-family: \"Roboto\", Arial, Helvetica, sans-serif;\n}\n```\n\nI thought it might be my folder structure, but that's not it either. I'm really confused as to why my fonts are loading when I do `npm run dev` and I've even tried to replicate the issue in a CRA project with no success at all.\n\nhttps://i.sstatic.net/rcAHW.png\n\n========================================\n\nTop Answer:\nI had the same issue (Vite + React) and leaving this here just in case it helps someone.\n\nMy CSS file was importing the font like this:\n\n```\n@font-face {\n font-family: \"Optimus Princeps\";\n src: url(\"./fonts/OptimusPrinceps.ttf\") format(\"ttf\") And it wouldn't work, visiting `localhost:5173/src/fonts/OptimusPrinceps.ttf` would download the file but the browser wouldn't display it.\n\nWhat fixed it was removing the explicit declaration, blind guess. However, this could be because of how this specific font works and has nothing to do with Vite.\n\nWorking CSS:\n\n```\n@font-face {\n font-family: \"Optimus Princeps\";\n src: url(\"./fonts/OptimusPrinceps.ttf\");\n}\n```\n\n========================================\n\nCode:\n```text\nGET\nhttp://localhost:5173/assets/fonts/Roboto-Regular.woff\n[HTTP/1.1 404 Not Found 1ms]\n\ndownloadable font: download failed (font-family: \"Roboto\" style:normal weight:400 stretch:100 src index:0): status=2147746065 source: http://localhost:5173/assets/fonts/Roboto-Regular.woff\n```\n\n```scss\n// _fonts.scss\n@font-face {\n  font-family: \"Roboto\";\n  src: url(\"../../assets/fonts/Roboto-Regular.woff\") format(\"woff\");\n  font-weight: 400;\n}\n```\n\n```scss\n@use \"./styles/partials/fonts\" as *;\n\nbody {\n  font-family: \"Roboto\", Arial, Helvetica, sans-serif;\n}\n```\n\n```text\nnpm run dev\n```\n\n```css\nsrc: url(\"../../assets/fonts/Roboto-Regular.woff\") format(\"woff\");\n```\n\n```css\nsrc: url(\"./assets/fonts/Roboto-Regular.woff\") format(\"woff\");\n```\n\n```text\ncreate-react-app\n```\n\n```css\n@font-face {\n  font-family: \"Optimus Princeps\";\n  src: url(\"./fonts/OptimusPrinceps.ttf\") format(\"ttf\") <- note the explicit format declaration\n}\n```\n\n```css\n@font-face {\n  font-family: \"Optimus Princeps\";\n  src: url(\"./fonts/OptimusPrinceps.ttf\");\n}\n```\n\n```text\nlocalhost:5173/src/fonts/OptimusPrinceps.ttf\n```\n\n```css\n@font-face {\n  font-family: \"Roboto\";\n  src:\n    local(\"Roboto\"),\n    url(\"../assets/fonts/RobotoFlex.woff2\") format(\"woff2\");\n  font-weight: 300 700; /* Range of weights supported by the variable font */\n  font-style: normal; /* Include if the font has italic styles */\n}\n```\n\n```text\nformat(...)\n```\n\n```text\nsrc\n```\n\n```text\nnetwork\n```\n\n```text\n@font-face {\n    src: url('~@/assets/fonts/Regular.ttf') format('truetype'),\n```\n\n```text\n@font-face {\n    src: url('@/assets/fonts/Regular.ttf') format('truetype'),\n```\n\n```text\n~\n```\n\n```text\nindex.html\n```\n\n```text\n<link href=\"https://fonts.googleapis.com/css?family=Montserrat:wght@400;700\" rel=\"stylesheet\">\n```\n\n```text\nimport '@fontsource-variable/lora/index';\n```\n\n========================================\n\nComments:\n- I lost an hour because of that, simply removing the format fixed the issue. Thanks!\n- Seems to be the case with ttf. woff2 works fine with the declaration.\n- I think you need to use `format(\"truetype\")` rather than \"ttf\"\n- same here use `format(\"truetype\")`\n- removing the `format(\"otf\")` worked for me.","metadata":{"transformedAt":"2026-08-18T18:33:46.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":182,"estimatedTokens":1033}}201{"id":"stack-75060072","source":"stackoverflow","questionId":75060072,"title":"Overriding antd variables with less on V5","tags":["reactjs","less","antd","vite","css-in-js"],"text":"Title: Overriding antd variables with less on V5\nTags: reactjs, less, antd, vite, css-in-js\nSource: Stack Overflow\n\nQuestion:\nI'm upgrading to antd v5 and i had some issues with keeping the variables overrides made from less files with v4\n\ni have multiple less files inside `src/theme` one of them is with the following\n\n```\n@import 'antd/lib/style/themes/variable.less';\n\n/* font */\n@font: ~'var(--font)';\n\n/* auxiliary colors */\n@secondary-color: ~'var(--secondary-color)';\n@secondary-color-light: ~'var(--secondary-color-light)';\n@primary-color-dark: @primary-7;\n@primary-color-light: @primary-5;\n@background-color: #f8f8f8;\n@shadow-color: rgba(0, 0, 0, 0.09);\n@text-color: #656565;\n@secondary-text-color: #9d9d9d;\n@light-text-color: #bababa;\n\n@secondary-color-bg: @green-1;\n@warning-color-bg: @orange-1;\n@error-color-bg: @red-1;\n@info-color-bg: @blue-1;\n\n/* sizes */\n@design-scale: 60 / 70;\n@app-bar-height: 60px;\n\n@page-padding: 40px 4vw;\n@page-padding-mobile: 30px 15px;\n\n@border-radius-base: 4px;\n@border-width-base: 2px;\n```\n\nAlso tried to inject `primaryColor` from `ConfigProvider` as follows\n`ConfigProvider.config({ theme: {primaryColor: '#fa259e'} });`\n\nin `vite.config` i added the following\n\n```\n...\nimport { theme } from 'antd/lib';\n...\n\nconst { defaultAlgorithm, defaultSeed } = theme;\n\nconst mapToken = defaultAlgorithm(defaultSeed);\nconst v4Token = convertLegacyToken(mapToken);\n\nexport default () => {\n return defineConfig({\n ...\n css: {\n preprocessorOptions: {\n less: {\n javascriptEnabled: true,\n modifyVars: v4Token,\n },\n },\n },\n ...\n```\n\nMy stylings has multiple issues with spacing paddings ... also primary-color not applying\n\n**EDIT**\nI have imported `antd/dist/reset.css` and also added `v4Token` in vite config just like the documentation suggested as follows\n\n```\n...\nimport { convertLegacyToken } from '@ant-design/compatible/lib';\nimport { theme } from 'antd/lib';\n...\n\nconst { defaultAlgorithm, defaultSeed } = theme;\n\nconst mapToken = defaultAlgorithm(defaultSeed);\nconst v4Token = convertLegacyToken(mapToken);\n\nexport default () => {\n return defineConfig({\n ...\n css: {\n preprocessorOptions: {\n less: { javascriptEnabled: true, modifyVars: v4Token },\n modifyVars: v4Token,\n },\n },\n ...\n });\n};\n```\n\nthe problem i have a dynamic `@primary-color` and used to use `ConfigProvider.config({ theme: defaultTheme });`\n\nso i tried to override as bellow\n\n```\n...\n\n {children}\n \n...\n```\n\nIt changes the color successfully, but the components or elements using less files `@primary-color` is still set by the default blue color of antd\n\n========================================\n\nTop Answer:\nI rewrited defaultSeed tokens and it works good for me.\n\n```\nconst withLess = require('next-with-less');\nconst { theme } = require('antd/lib');\nconst { convertLegacyToken } = require('@ant-design/compatible/lib');\n\nconst { defaultAlgorithm, defaultSeed } = theme;\n\nconst mapToken = defaultAlgorithm({\n ...defaultSeed,\n colorPrimary: '#115dee',\n});\n\nconst v4Token = convertLegacyToken(mapToken);\n\nmodule.exports = withLess({\n lessLoaderOptions: {\n lessOptions: {\n modifyVars: v4Token,\n javascriptEnabled: true,\n },\n },\n});\n```\n\n========================================\n\nCode:\n```text\n@import 'antd/lib/style/themes/variable.less';\n\n/* font */\n@font: ~'var(--font)';\n\n/* auxiliary colors */\n@secondary-color: ~'var(--secondary-color)';\n@secondary-color-light: ~'var(--secondary-color-light)';\n@primary-color-dark: @primary-7;\n@primary-color-light: @primary-5;\n@background-color: #f8f8f8;\n@shadow-color: rgba(0, 0, 0, 0.09);\n@text-color: #656565;\n@secondary-text-color: #9d9d9d;\n@light-text-color: #bababa;\n\n@secondary-color-bg: @green-1;\n@warning-color-bg: @orange-1;\n@error-color-bg: @red-1;\n@info-color-bg: @blue-1;\n\n/* sizes */\n@design-scale: 60 / 70;\n@app-bar-height: 60px;\n\n@page-padding: 40px 4vw;\n@page-padding-mobile: 30px 15px;\n\n@border-radius-base: 4px;\n@border-width-base: 2px;\n```\n\n```text\n...\nimport { theme } from 'antd/lib';\n...\n\nconst { defaultAlgorithm, defaultSeed } = theme;\n\nconst mapToken = defaultAlgorithm(defaultSeed);\nconst v4Token = convertLegacyToken(mapToken);\n\nexport default () => {\n    return defineConfig({\n       ...\n       css: {\n            preprocessorOptions: {\n                less: {\n                    javascriptEnabled: true,\n                    modifyVars: v4Token,\n                },\n            },\n        },\n       ...\n```\n\n```text\n...\nimport { convertLegacyToken } from '@ant-design/compatible/lib';\nimport { theme } from 'antd/lib';\n...\n\nconst { defaultAlgorithm, defaultSeed } = theme;\n\nconst mapToken = defaultAlgorithm(defaultSeed);\nconst v4Token = convertLegacyToken(mapToken);\n\nexport default () => {\n    return defineConfig({\n        ...\n        css: {\n            preprocessorOptions: {\n                less: { javascriptEnabled: true, modifyVars: v4Token },\n                modifyVars: v4Token,\n            },\n        },\n        ...\n    });\n};\n```\n\n```text\n...\n<ConfigProvider\n            theme={{\n                token: {\n                    colorPrimary: defaultTheme.primaryColor,\n                },\n            }}\n            locale={antDesignLocal}\n            direction={dir}\n        >\n            {children}\n        </ConfigProvider>\n...\n```\n\n```text\nsrc/theme\n```\n\n```text\nprimaryColor\n```\n\n```text\nConfigProvider\n```\n\n```text\nConfigProvider.config({ theme: {primaryColor: '#fa259e'} });\n```\n\n```text\nvite.config\n```\n\n```text\nantd/dist/reset.css\n```\n\n```text\nv4Token\n```\n\n```text\n@primary-color\n```\n\n```text\nConfigProvider.config({ theme: defaultTheme });\n```\n\n```text\n@primary-color\n```\n\n```js\nconst withLess = require('next-with-less');\nconst { theme } = require('antd/lib');\nconst { convertLegacyToken } = require('@ant-design/compatible/lib');\n\nconst { defaultAlgorithm, defaultSeed } = theme;\n\nconst mapToken = defaultAlgorithm({\n    ...defaultSeed,\n    colorPrimary: '#115dee',\n});\n\nconst v4Token = convertLegacyToken(mapToken);\n\nmodule.exports = withLess({\n    lessLoaderOptions: {\n        lessOptions: {\n            modifyVars: v4Token,\n            javascriptEnabled: true,\n        },\n    },\n});\n```\n\n========================================\n\nComments:\n- How did you tackle this problem in the end?\n- Did you find any solution to your problem ?\n- I know about them dropping LESS, but i'm thinking of a migration shortcut. rather then re-typing everything in CSS-in-JS\n- Not sure if it would work, but what if you simply build your styles outside of antd, e.g. directly with the LESS compiler and then include that compiled stylesheet in your app?\n- I'm not seeing a migration shortcut as the two approaches (e.g. LESS vs cssinjs) are very different in nature. There is a v5 codemod tool, but I have my doubts that it would be solving your problem, if you haven't yet check it out regardless github.com/ant-design/codemod-v5\n- tried the codemod but it skipp all the less files\n- Can you check the changes ?\n- Can you explain what happens here? Where do we load the less variables and how does it get converted to a v5 compatible theme?\n- Tried this one but it is not working. Can you please help me with mine?\n- it's in next.js configuration file, you need to use 'next-with-less'","metadata":{"transformedAt":"2026-08-18T18:33:46.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":322,"estimatedTokens":1791}}202{"id":"stack-75394277","source":"stackoverflow","questionId":75394277,"title":"Run react app locally in production mode using vite?","tags":["reactjs","vite","production-environment"],"text":"Title: Run react app locally in production mode using vite?\nTags: reactjs, vite, production-environment\nSource: Stack Overflow\n\nQuestion:\nI would like to run a vite react app locally in production mode? What is the best way of doing it?\n\n========================================\n\nTop Answer:\n2024 here\nLook at your `package.json`\n\n```\n\"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"tsc && vite build\",\n \"lint\": \"eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0\",\n \"preview\": \"vite preview\"\n },\n```\n\nAs you can see just `npm run preview` will do the job\n\n========================================\n\nCode:\n```text\n{\n  \"scripts\": {\n    \"build\": \"vite build\",\n    \"serve\": \"vite preview\"\n  }\n}\n```\n\n```text\nnpm run build\n\nnpm run serve\n```\n\n```text\n\"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"tsc && vite build\",\n    \"lint\": \"eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0\",\n    \"preview\": \"vite preview\"\n  },\n```\n\n```text\npackage.json\n```\n\n```text\nnpm run preview\n```\n\n========================================\n\nComments:\n- yarn build? then move the out/build folder into your local server\n- You can create a prod build and run `npx serve` command from the dist/build directory.\n- Thanks @RahulSharma for you hints. Its working now, putting the solution the answer section.\n- Please note that viet preview isn't meant for production mode!\n- @Milgo could you please describe your statement bit more?\n- See Vite documentation: \"It is important to note that vite preview is intended for previewing the build locally and not meant as a production server.\"","metadata":{"transformedAt":"2026-08-18T18:33:46.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":68,"estimatedTokens":398}}203{"id":"stack-66395054","source":"stackoverflow","questionId":66395054,"title":"How do i enable \"@babel/plugin-proposal-decorators\" with vite","tags":["javascript","vite"],"text":"Title: How do i enable \"@babel/plugin-proposal-decorators\" with vite\nTags: javascript, vite\nSource: Stack Overflow\n\nQuestion:\n```\n> src/App.jsx:22:0: error: Unexpected \"@\"\n 22 │ @observer\n\nerror when starting dev server:\nError: Build failed with 1 error:\nsrc/App.jsx:22:0: error: Unexpected \"@\"\n```\n\nI use the observer as a decorator then i got the error. Can not find a place to enable this option in documentation.\n\n========================================\n\nTop Answer:\nVite's react plugin already supports this.\nCheck the docs here\nhttps://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react#proposed-syntax. You need not install any new packages. The following configuration should work,\n\n```\nimport { defineConfig } from 'vite';\nimport reactSupport from '@vitejs/plugin-react';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [reactSupport({\n babel: {\n parserOpts: {\n plugins: ['decorators-legacy', 'classProperties']\n }\n }\n })],\n server: {\n port: 3000\n }\n});\n```\n\n========================================\n\nCode:\n```text\n> src/App.jsx:22:0: error: Unexpected \"@\"\n    22 │ @observer\n\nerror when starting dev server:\nError: Build failed with 1 error:\nsrc/App.jsx:22:0: error: Unexpected \"@\"\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\n// https://www.npmjs.com/package/@vitejs/plugin-react\nexport default defineConfig({\n    plugins: [\n        react({\n            babel: {\n                plugins: [\n                    [\"@babel/plugin-proposal-decorators\", { legacy: true }],\n                    [\n                        \"@babel/plugin-proposal-class-properties\",\n                        { loose: true },\n                    ],\n                ],\n            },\n        }),\n    ],\n});\n```\n\n```text\n.ts / .tsx\n```\n\n```text\n.js / .jsx\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport reactSupport from '@vitejs/plugin-react';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [reactSupport({\n    babel: {\n      parserOpts: {\n        plugins: ['decorators-legacy', 'classProperties']\n      }\n    }\n  })],\n  server: {\n    port: 3000\n  }\n});\n```\n\n```js\nimport { defineConfig } from 'vite';\nimport babelDev from 'vite-plugin-babel-dev';\n\nexport default defineConfig({\n    plugins: [\n        babelDev({\n            babelConfig: {\n                plugin: ['@babel/plugin-proposal-decorators']\n            }\n        }),\n        // ...\n    ],\n\n    // ...\n})\n```\n\n```text\nreact\n```\n\n```text\n@babel/plugin-proposal-decorators\n```\n\n```text\nimport {defineConfig} from \"vite\"\nimport vue from '@vitejs/plugin-vue'\nimport { createHtmlPlugin } from 'vite-plugin-html';\nimport vueJsx from '@vitejs/plugin-vue-jsx';\n\nexport default defineConfig({\n  build: {\n    outDir: 'dist/'\n  },\n  plugins: [\n    vue(),\n    vueJsx(\n      {babelPlugins: [[\n        \"@babel/plugin-proposal-decorators\",\n        { legacy: true },\n      ]]}\n    )\n  ],\n})\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\nexport default defineConfig({\n  plugins: [react({ tsDecorators: true })],\n})\n```\n\n```text\ntsDecorators\n```\n\n```text\nvite.config.ts\n```\n\n```text\nplugins: [\n    preact({\n      babel: {\n        plugins: [\n          [\"@babel/plugin-proposal-decorators\", { version: \"2023-05\" }],\n        ],\n      },\n    }),\n  ],\n```\n\n```text\n@preact/preset-vite\n```\n\n```text\nnpm install --save-dev @babel/plugin-proposal-decorators\n```\n\n```text\nvite.config.ts\n```\n\n```js\nexport default defineConfig({\n  plugins: [\n    react({\n      parserConfig: () => ({\n        syntax: 'typescript',\n        decorators: true,\n      }),\n    }),\n  ],\n})\n```\n\n========================================\n\nComments:\n- Downvoted because a question that didn't ask about React should not include Vite build configs.\n- This is not enough for Dec 2023, after you set those options you will get in the browser `Uncaught SyntaxError: Invalid or unexpected token`\n- Downvoted because a question that didn't ask about React should not include Vite build configs.\n- This is the easiest solution I tried that works!\n- github.com/vitejs/vite-plugin-react/issues/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:46.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":214,"estimatedTokens":1044}}204{"id":"stack-76208402","source":"stackoverflow","questionId":76208402,"title":"[vite]: Rollup failed to resolve import \"/src/main.tsx\"","tags":["reactjs","typescript","vite"],"text":"Title: [vite]: Rollup failed to resolve import \"/src/main.tsx\"\nTags: reactjs, typescript, vite\nSource: Stack Overflow\n\nQuestion:\nI have a legacy typescript react app, now I want to migration it from webpack to vite, when I using this command to build the app, show error like this:\n\n```\n> tsc && vite build\n\nvite v4.3.5 building for production...\n✓ 2 modules transformed.\n✓ built in 32ms\n[vite]: Rollup failed to resolve import \"/src/main.tsx\" from \"/Users/John/source/reddwarf/frontend/snap-web/src/index.html\".\nThis is most likely unintended because it can break your application at runtime.\nIf you do want to externalize this module explicitly add it to\n`build.rollupOptions.external`\nerror during build:\nError: [vite]: Rollup failed to resolve import \"/src/main.tsx\" from \"/Users/John/source/reddwarf/frontend/snap-web/src/index.html\".\nThis is most likely unintended because it can break your application at runtime.\nIf you do want to externalize this module explicitly add it to\n`build.rollupOptions.external`\n at viteWarn (file:///Users/John/source/reddwarf/frontend/snap-web/node_modules/.pnpm/vite@4.3.5_@types+node@16.18.23/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:46561:23)\n at onwarn (file:///Users/John/source/reddwarf/frontend/snap-web/node_modules/@vitejs/plugin-react/dist/index.mjs:237:9)\n at onRollupWarning (file:///Users/John/source/reddwarf/frontend/snap-web/node_modules/.pnpm/vite@4.3.5_@types+node@16.18.23/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:46582:9)\n at onwarn (file:///Users/John/source/reddwarf/frontend/snap-web/node_modules/.pnpm/vite@4.3.5_@types+node@16.18.23/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:46332:13)\n at Object.onwarn (file:///Users/John/source/reddwarf/frontend/snap-web/node_modules/.pnpm/rollup@3.21.5/node_modules/rollup/dist/es/shared/node-entry.js:25305:13)\n at ModuleLoader.handleInvalidResolvedId (file:///Users/John/source/reddwarf/frontend/snap-web/node_modules/.pnpm/rollup@3.21.5/node_modules/rollup/dist/es/shared/node-entry.js:23940:26)\n at file:///Users/John/source/reddwarf/frontend/snap-web/node_modules/.pnpm/rollup@3.21.5/node_modules/rollup/dist/es/shared/node-entry.js:23900:26\n ELIFECYCLE  Command failed with exit code 1.\n```\n\nwhat should I do to fixed this problem? I have searching from internet seems no-one facing the similar issue. this is the `vite.config.ts`:\n\n```\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport path from 'path';\n\nexport default defineConfig({\n root: path.join(__dirname, 'src'),\n plugins: [react()],\n build:{\n outDir: \"build\"\n }\n})\n```\n\nthis is the main.tsx which I was pasted from the standard lib that create from command `npm create vite@latest my-vue-app -- --template react-ts`:\n\n```\nimport React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport './index.css'\n\nReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(\n \n ddddd\n ,\n)\n```\n\nthis is the `index.html`:\n\n```\n\n \n \n \n \n \n \n \n \n \n \n title\n \n \n You need to enable JavaScript to run this app.\n \n \n \n\n```\n\n========================================\n\nTop Answer:\nOne way to solve this issue, check your file extension under the component folder . In Vite your component file extension should be .tsx\n\n*\n\n========================================\n\nCode:\n```text\n> tsc && vite build\n\nvite v4.3.5 building for production...\n✓ 2 modules transformed.\n✓ built in 32ms\n[vite]: Rollup failed to resolve import \"/src/main.tsx\" from \"/Users/John/source/reddwarf/frontend/snap-web/src/index.html\".\nThis is most likely unintended because it can break your application at runtime.\nIf you do want to externalize this module explicitly add it to\n`build.rollupOptions.external`\nerror during build:\nError: [vite]: Rollup failed to resolve import \"/src/main.tsx\" from \"/Users/John/source/reddwarf/frontend/snap-web/src/index.html\".\nThis is most likely unintended because it can break your application at runtime.\nIf you do want to externalize this module explicitly add it to\n`build.rollupOptions.external`\n    at viteWarn (file:///Users/John/source/reddwarf/frontend/snap-web/node_modules/.pnpm/vite@4.3.5_@types+node@16.18.23/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:46561:23)\n    at onwarn (file:///Users/John/source/reddwarf/frontend/snap-web/node_modules/@vitejs/plugin-react/dist/index.mjs:237:9)\n    at onRollupWarning (file:///Users/John/source/reddwarf/frontend/snap-web/node_modules/.pnpm/vite@4.3.5_@types+node@16.18.23/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:46582:9)\n    at onwarn (file:///Users/John/source/reddwarf/frontend/snap-web/node_modules/.pnpm/vite@4.3.5_@types+node@16.18.23/node_modules/vite/dist/node/chunks/dep-934dbc7c.js:46332:13)\n    at Object.onwarn (file:///Users/John/source/reddwarf/frontend/snap-web/node_modules/.pnpm/rollup@3.21.5/node_modules/rollup/dist/es/shared/node-entry.js:25305:13)\n    at ModuleLoader.handleInvalidResolvedId (file:///Users/John/source/reddwarf/frontend/snap-web/node_modules/.pnpm/rollup@3.21.5/node_modules/rollup/dist/es/shared/node-entry.js:23940:26)\n    at file:///Users/John/source/reddwarf/frontend/snap-web/node_modules/.pnpm/rollup@3.21.5/node_modules/rollup/dist/es/shared/node-entry.js:23900:26\n ELIFECYCLE  Command failed with exit code 1.\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport path from 'path';\n\nexport default defineConfig({\n    root: path.join(__dirname, 'src'),\n    plugins: [react()],\n    build:{\n        outDir: \"build\"\n    }\n})\n```\n\n```text\nimport React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport './index.css'\n\nReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(\n  <React.StrictMode>\n    <div>ddddd</div>\n  </React.StrictMode>,\n)\n```\n\n```text\n<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"icon\" href=\"/favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <meta\n      name=\"description\"\n      content=\"Web site created using create-react-app\"\n    />\n    <link rel=\"apple-touch-icon\" href=\"/logo192.png\" />\n    <!--\n      manifest.json provides metadata used when your web app is installed on a\n      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"/manifest.json\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>title</title>\n  </head>\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <div id=\"root\"></div>\n    <script type=\"module\" src=\"/src/main.tsx\"></script>\n  </body>\n</html>\n```\n\n```text\nvite.config.ts\n```\n\n```text\nnpm create vite@latest my-vue-app -- --template react-ts\n```\n\n```text\nindex.html\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n})\n```\n\n```text\nrootDir/\n  |- src/\n      |- <src dir contents>\n  |- index.html\n  |- vite.config.ts\n```\n\n```html\n<script type=\"module\" src=\"/src/main.tsx\"></script>\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  build:{\n    outDir: \"build\"\n  }\n})\n```\n\n```text\nvite.config.ts\n```\n\n```text\nnpm run build\n```\n\n```text\nindex.html\n```\n\n```text\nroot\n```\n\n```text\nroot: path.join(__dirname, 'src')\n```\n\n```text\nindex.html\n```\n\n```text\nsrc\n```\n\n```text\nindex.html\n```\n\n```text\nsrc\n```\n\n```text\nroot\n```\n\n```text\nvite.config.ts\n```\n\n```text\nindex.html\n```\n\n```text\nmain.tsx\n```\n\n```text\nvite.config.ts\n```\n\n```text\nindex.html\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":290,"estimatedTokens":2038}}205{"id":"stack-74919230","source":"stackoverflow","questionId":74919230,"title":"How to customize markdown with Astro components?","tags":["markdown","vite","astrojs"],"text":"Title: How to customize markdown with Astro components?\nTags: markdown, vite, astrojs\nSource: Stack Overflow\n\nQuestion:\n### md vs mdx\n\nmd import pipeline renders to html, mdx import pipeline renders to .js/.ts/.jsx... which allows to customize html tags with Astro components.\n\n### goal\n\nI would like to take advantage of the mdx power in .md files with Astro\n\n### what I tried\n\ntried to configure mdx integration in Astro but it is excluding .md extension unfortunately to allow default md rehype pipeline\n\nMy workaround of renaming all .md files to .mdx is very intrusive (changes files meta data) I would like to find a different approach\n\nforking mdx integration is hard to maintain\n\nI started a vite plugin that changes .md ids to add an x as .mdx, then I had to write my own loader, then it got too complex\n\nastro-remote only takes some default components and does allow to replace any custom component\n\n### examples\n\nI would like to avoid\n\n- (-) embedding svg assets in config files to e.g. add link icons in headings elements (example https://github.com/withastro/docs/blob/52bf88ec74e3d01d212808d678320f190be64f76/astro.config.ts#L16)\n\nand rather\n\n- (+) allow advanced enhancements written in html like e.g. .astro and NOT in rehype js format. (example just for reference in mdx not md https://github.com/MicroWebStacks/astro-big-doc/blob/9d4215e86c020bf72f28ce83d8e494df23e0ff7d/src/components/headings/H1.astro#L15)\n\nAny ideas of the finest approach to achieve this, it feels like this last step is missing to unleash Astro's power over Markdow !!!\n\n### references\n\nastro remote : https://github.com/natemoo-re/astro-remote\n\nusing old or deprecated options such as the previous `` tag, might be an option to explore but should not result in separate feature branch where most of new features have to be manually maintained.\n\nprogrammatic component creation https://github.com/withastro/astro/blob/main/packages/astro/test/units/render/jsx.test.js#L33-L35\n\n========================================\n\nCode:\n```text\n<Markdown />\n```\n\n```js\nimport {fromMarkdown} from 'mdast-util-from-markdown'\n\nconst tree = fromMarkdown(content)\n```\n\n```js\n---\nimport Heading from '../nodes/Heading.astro';\nimport Image from '../nodes/image/Image.astro'\nimport Code from '../nodes/code/Code.astro'\nimport {toHast} from 'mdast-util-to-hast'\nimport {toHtml} from 'hast-util-to-html'\nexport interface Props {\n    node: object;\n    data: object;\n}\n\nconst {node, data} = Astro.props;\nconst handled_types = [\"root\",\"heading\",\"paragraph\",\"image\",\"code\"]\nconst other_type = !handled_types.includes(node.type)\n---\n{(node.type == \"root\") &&\n    node.children.map((node)=>(\n        <Astro.self node={node} data={data} />\n    ))\n}\n{(node.type == \"paragraph\") &&\n<p>\n    {node.children.map((node)=>(\n        <Astro.self node={node} data={data}/>\n    ))}\n</p>\n}\n{(node.type == \"heading\") &&\n    <Heading node={node} headings={data.headings}/>\n}\n{(node.type == \"image\") &&\n    <Image node={node}  filepath={data.path}/>\n}\n{(node.type == \"code\") &&\n    <Code node={node}  filepath={data.path}/>\n}\n{other_type &&\n    <Fragment set:html={toHtml(toHast(node))}></Fragment>\n}\n```\n\n```js\n---\nconst {sid} = Astro.params;\nimport AstroMarkdown from '@/components/renderers/AstroMarkdown.astro'\n\nconst data_content = await load_json(`gen/documents/${sid}/content.json`)\nconst tree = await load_json(`gen/documents/${sid}/tree.json`)\n---\n<AstroMarkdown node={tree} data={data_content} />\n```\n\n```text\ntoHtml(toHast(node))\n```\n\n```text\n[...sid].astro\n```\n\n```text\nmdast-util-from-markdown\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.407Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":122,"estimatedTokens":889}}206{"id":"stack-72962164","source":"stackoverflow","questionId":72962164,"title":"Use index.php instead of index.html in vitejs","tags":["php","reactjs","drupal","vite","html-webpack-plugin"],"text":"Title: Use index.php instead of index.html in vitejs\nTags: php, reactjs, drupal, vite, html-webpack-plugin\nSource: Stack Overflow\n\nQuestion:\nI have a react application, currently migrating the app from `CRA` to `vite`. i have configured index.php (which has some php configuration) as entry point using `HtmlWebpackPlugin`. So, while migrating to `vite`, it takes index.html as a entry point. Is there any way to change it to index.php? Reference Link\n\n========================================\n\nTop Answer:\nNow there is a way to have an `index.php` instead of the default `index.html`!\n\nUse the `vite-plugin-php` Vite plugin to use PHP-files as entry points for your application.\n\nNo major hack- and workarounds required.\n\nCheck out:\nhttps://www.npmjs.com/package/vite-plugin-php\n\n========================================\n\nCode:\n```text\nCRA\n```\n\n```text\nvite\n```\n\n```text\nHtmlWebpackPlugin\n```\n\n```text\nvite\n```\n\n```text\nindex.php\n```\n\n```text\nindex.html\n```\n\n```text\nvite-plugin-php\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":49,"estimatedTokens":247}}207{"id":"stack-75554837","source":"stackoverflow","questionId":75554837,"title":"Vite not found in vite.config.ts cannot run vite apps","tags":["node.js","reactjs","npm","vite"],"text":"Title: Vite not found in vite.config.ts cannot run vite apps\nTags: node.js, reactjs, npm, vite\nSource: Stack Overflow\n\nQuestion:\nnpm create vite@latest error: Cannot find package 'vite' imported from .../vite.config.ts.timestamp-....mjs\n\nAn update while writing my problem:\nI concluded that the error has to do with the vite.config.ts (vite.config.js)\n\n*But I left everything I gathered so far, don't know what might help.*\n\n### Thank you for opening my problem. I'll walk you through it:\n\nnpm create vite@latest vite-react\n[I select React, Typescript]\n\n- cd vite-react\n\n- npm install\n\n- npm run dev\n\n```\n> vite-react@0.0.0 dev\n > vite\n\nfailed to load config from [my-path]\\vite-project\\vite-react\\vite.config.ts\nerror when starting dev server:\nError [ERR_MODULE_NOT_FOUND]: Cannot find package 'vite' imported from [my-path]\\vite-project\\vite-react\\vite.config.ts.timestamp-1677228345613.mjs\n at new NodeError (node:internal/errors:399:5)\n at packageResolve (node:internal/modules/esm/resolve:889:9)\n at moduleResolve (node:internal/modules/esm/resolve:938:20)\n at defaultResolve (node:internal/modules/esm/resolve:1153:11)\n at nextResolve (node:internal/modules/esm/loader:163:28)\n at ESMLoader.resolve (node:internal/modules/esm/loader:838:30)\n at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)\n at ModuleWrap. (node:internal/modules/esm/module_job:77:40)\n at link (node:internal/modules/esm/module_job:76:36)\n```\n\n**Versions:**\n\n```\nnode -v\n v18.14.2\n```\n\n```\nnpm -v\n 9.5.0\n```\n\n```\nvite -v\n vite/4.1.1 win32-x64 node-v18.14.2\n```\n\nThe weird thing is that a simple typescript app works with the above process.\nso if I select Vanilla, Typescript, and run install and run dev it works just fine...\n\n**Vanilla TS package.json**\n\n```\n{\n \"name\": \"vite-project\",\n \"private\": true,\n \"version\": \"0.0.0\",\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"tsc && vite build\",\n \"preview\": \"vite preview\"\n },\n \"devDependencies\": {\n \"typescript\": \"^4.9.3\",\n \"vite\": \"^4.1.0\"\n }\n}\n```\n\n**React TS package.json**\n\n```\n{\n \"name\": \"vite-react\",\n \"private\": true,\n \"version\": \"0.0.0\",\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"tsc && vite build\",\n \"preview\": \"vite preview\"\n },\n \"dependencies\": {\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\"\n },\n \"devDependencies\": {\n \"@types/react\": \"^18.0.27\",\n \"@types/react-dom\": \"^18.0.10\",\n \"@vitejs/plugin-react\": \"^3.1.0\",\n \"typescript\": \"^4.9.3\",\n \"vite\": \"^4.1.0\"\n }\n}\n```\n\nI tried creating a svelte app with typescript. (a tsconfig warning and) the same error as with the react app.\n\nI didn't think typescript had anything to do wih it since a [Vanilla, TypeScript] project worked but just to be sure I tried [React, JavaScript] and still the same error.\n\nThe problem has something to do with vite-config.ts (or vite-config.js) since the Vanilla project (which I checked has no such file) works fine.\n\n**vite.config.ts / vite.config.js**\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n})\n```\n\nThis is a work notebook so I cannot just clean install my os. The npm create vite@latest works at every machine at home as it should.\n\nIt seems only I have this problem since I could not find anything similar.\n\nTy for the rather long read. Any help, direction pointing is appreciated.\n\n========================================\n\nTop Answer:\nTry to rename the project name and update the name in the package.json file.\n\npackage.json file\n\n```\n{\n\"name\": \"update name of project here\",\n}\n```\n\nnow start the server.\n\n========================================\n\nCode:\n```text\n> vite-react@0.0.0 dev\n    > vite\n\nfailed to load config from [my-path]\\vite-project\\vite-react\\vite.config.ts\nerror when starting dev server:\nError [ERR_MODULE_NOT_FOUND]: Cannot find package 'vite' imported from [my-path]\\vite-project\\vite-react\\vite.config.ts.timestamp-1677228345613.mjs\n    at new NodeError (node:internal/errors:399:5)\n    at packageResolve (node:internal/modules/esm/resolve:889:9)\n    at moduleResolve (node:internal/modules/esm/resolve:938:20)\n    at defaultResolve (node:internal/modules/esm/resolve:1153:11)\n    at nextResolve (node:internal/modules/esm/loader:163:28)\n    at ESMLoader.resolve (node:internal/modules/esm/loader:838:30)\n    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)\n    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:77:40)\n    at link (node:internal/modules/esm/module_job:76:36)\n```\n\n```text\nnode -v\n v18.14.2\n```\n\n```text\nnpm -v\n 9.5.0\n```\n\n```text\nvite -v\n vite/4.1.1 win32-x64 node-v18.14.2\n```\n\n```text\n{\n  \"name\": \"vite-project\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"tsc && vite build\",\n    \"preview\": \"vite preview\"\n  },\n  \"devDependencies\": {\n    \"typescript\": \"^4.9.3\",\n    \"vite\": \"^4.1.0\"\n  }\n}\n```\n\n```text\n{\n  \"name\": \"vite-react\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"tsc && vite build\",\n    \"preview\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^18.0.27\",\n    \"@types/react-dom\": \"^18.0.10\",\n    \"@vitejs/plugin-react\": \"^3.1.0\",\n    \"typescript\": \"^4.9.3\",\n    \"vite\": \"^4.1.0\"\n  }\n}\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n})\n```\n\n```text\nnpm install --include=dev\n```\n\n```text\nnpm install\n```\n\n```text\npackage.json\n```\n\n```text\n{\n\"name\": \"update name of project here\",\n}\n```\n\n========================================\n\nComments:\n- not working, same issue\n- they should not be under dependencies, vite is a compile time build tool, it is not published to the end user\n- This npm install --include=dev worked like a charm for me when running my app in heroku. Thanks alot!\n- I wish this worked for me. Btw theoretically they are meant to be under devDependencies","metadata":{"transformedAt":"2026-08-18T18:33:46.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":261,"estimatedTokens":1524}}208{"id":"stack-74416205","source":"stackoverflow","questionId":74416205,"title":"Vite build gives 404","tags":["http-status-code-404","vite"],"text":"Title: Vite build gives 404\nTags: http-status-code-404, vite\nSource: Stack Overflow\n\nQuestion:\nI am new to vite, I did install, wrote some code, did *npm run dev* and *npm run build*.\n\nEverything went fine until uploading to my server.\n\nindex.html:\n\n```\n\n```\n\nRunning from live server, I get these errors\n\n```\nFailed to load resource: net::ERR_FAILED index.4293b7ae.css:1\nFailed to load resource: net::ERR_FILE_NOT_FOUND index.a673cca3.js\n```\n\nThe filenames are correct and they are where are suposed to be.\n\nWhat gives?\n\n========================================\n\nCode:\n```text\n<script type=\"module\" crossorigin src=\"/assets/index.a673cca3.js\"></script>\n```\n\n```text\nFailed to load resource: net::ERR_FAILED index.4293b7ae.css:1\nFailed to load resource: net::ERR_FILE_NOT_FOUND index.a673cca3.js\n```\n\n```text\n// vite.config.js\nexport default {\n    base: '/someproject/'\n}\n \n// if uploading to a subdomain it is ok to no specify any dir:\nexport default {\n    base: '/'\n}\n\n// using a relative path will work on any dir:\nexport default {\n    base: './'\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.407Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":54,"estimatedTokens":264}}209{"id":"stack-71690883","source":"stackoverflow","questionId":71690883,"title":"Pinia: $reset alternative when using setup syntax","tags":["vue.js","vuejs3","vite","pinia"],"text":"Title: Pinia: $reset alternative when using setup syntax\nTags: vue.js, vuejs3, vite, pinia\nSource: Stack Overflow\n\nQuestion:\nI have a pinia store created with setup syntax like:\n\n```\ndefineStore('id', () => {\n const counter = ref(0)\n \n return { counter }\n})\n```\n\nEverything has been working great with setup syntax because I can re-use other pinia stores.\n\nNow, however, I see the need to re-use Pinia stores on other pages but their state needs to be reset.\n\nIn Vuex for example, I was using `registerModule` and `unregisterModule` to achieve having a fresh store.\n\n### So the question is: How to reset the pinia store with setup syntax?\n\n*Note: The `$reset()` method is only implemented for stores defined with the object syntax, so that is not an option.*\n\n*Note 2: I know that I can do it manually by creating a function where you set all the state values to their initial ones*\n\n*Note 3: I found $dispose but it doesn't work. If $dispose is the answer, then how it works resetting the store between 2 components?*\n\n========================================\n\nTop Answer:\nYou can do this as suggested in the documentation here\n\n```\nmyStore.$dispose()\n\nconst pinia = usePinia()\n\ndelete pinia.state.value[myStore.$id]\n```\n\n========================================\n\nCode:\n```js\ndefineStore('id', () => {\n  const counter = ref(0)\n  \n  return { counter }\n})\n```\n\n```text\nregisterModule\n```\n\n```text\nunregisterModule\n```\n\n```text\n$reset()\n```\n\n```js\n// store.js\nimport { createPinia } from 'pinia'\nimport cloneDeep from 'lodash.clonedeep'\n\nconst store = createPinia()\n1️⃣\nstore.use(({ store }) => {\n  2️⃣\n  const initialState = cloneDeep(store.$state)\n  3️⃣\n  store.$reset = () => {\n    store.$patch($state => {\n      4️⃣\n      Object.assign($state, initialState)\n    })\n  }\n})\n```\n\n```text\n$reset()\n```\n\n```text\nuse()\n```\n\n```text\nstore\n```\n\n```text\nstore.$state\n```\n\n```text\nlodash.clonedeep\n```\n\n```text\nSet\n```\n\n```text\nstore.$reset()\n```\n\n```text\nstore.$patch()\n```\n\n```text\nObject.assign\n```\n\n```text\n$reset\n```\n\n```text\nmyStore.$dispose()\n\nconst pinia = usePinia()\n\ndelete pinia.state.value[myStore.$id]\n```\n\n========================================\n\nComments:\n- Reset feature is supported by this library github.com/huybuidac/vuex-extensions. Just $store.reset()\n- @HuyBuiDac That library is for Vuex, but this question is about Pinia.\n- `store.$state` is an empty object if you use setup syntax? I am not sure why this is the accepted answer. Is it outdated?\n- @oemera Not sure what you mean. The solution works as seen in the linked StackBlitz (although it's possible that code is outdated, as I've not kept up with any recent releases of those libs). If you still need help, I recommend posting a new question with details to reproduce the problem so that someone familiar with the topic can help you. I'll chime in if I can.\n- This approach works, however for me it breaks options-api defined stores (I have a mix while we transition to setup func). Is there a reliable method to establish if the store is defined via options-api syntax and skip overwriting the `$reset` method? Checking if `store.$reset` isn't sufficient, as it's defined on both syntax stores.\n- @tivoni To clarify, at the time of the original writing, `$reset` was not a built-in function of the store, and this answer provided a way to define it.\n- I realize I did not point out that `$reset` is still not supported with setup syntax, however the property exists, perhaps as a stub only so it logs a \"$reset is not supported\" message. This makes the store syntax/type difficult to differentiate in an app which combines both setup syntax store and options-api syntax stores\n- I found a problem with this. It throws an error when we return a ref as readonly\n- I ended up, instead of `prop: readonly(myProp)` I used `prop: computed(() => myProp.value)`","metadata":{"transformedAt":"2026-08-18T18:33:46.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":145,"estimatedTokens":958}}210{"id":"stack-67822238","source":"stackoverflow","questionId":67822238,"title":"how to import a json file using vite dynamicly","tags":["nuxt.js","vue-i18n","vite"],"text":"Title: how to import a json file using vite dynamicly\nTags: nuxt.js, vue-i18n, vite\nSource: Stack Overflow\n\nQuestion:\nI am using vue-i18n in a Nuxtjs project, and I want to import my locale files with vite dynamicly.\n\nwhen I am using webpack, those code run well\n\n**plugins/i18n.js**\n\n```\nimport Vue from 'vue';\nimport VueI18n from 'vue-i18n';\nimport config from '@/config';\n\nVue.use(VueI18n);\n\nlet messages = Object;\n\nconfig.locale.available.forEach(locale => {\n messages[locale] = require(`~/locales/${locale}.json`);\n});\n\nexport default ({ app, store }) => {\n app.i18n = new VueI18n({\n locale: store.state.locale.locale,\n messages: messages\n });\n}\n```\n\nI got that there is no `require()` in vitejs, also the glob-import feature of vitejs\n\n- So I tried like this below first:\n\n```\nlet messages = Object,\n languages = import.meta.glob('../locales/*.json'); // => languages = {} (languages only get {} value)\n\nconfig.locale.available.forEach(locale => {\n messages[locale] = languages[`../locales/${locale}.json`];\n});\n```\n\nBut the `languages` only got `{}` value.\n\n- Then I tried to use `import()`\n\n```\nlet messages = Object,\n translate = lang => () => import(`@/locales/${lang}.json`).then(i => i.default || i);\n\nconfig.locale.available.forEach(locale => {\n messages[locale] = translate(locale);\n});\n```\n\nno errors in both terminal and console, but no locale file has been loaded correctly.\n\nonly if I `import()` one by one, the issue will disappear:\n\n```\nimport en from '@/locales/en.json';\nimport fr from '@/locales/fr.json';\nimport ja from '@/locales/ja.json';\n\nlet messages = Object;\n\nmessages['en'] = en;\nmessages['fr'] = fr;\nmessages['ja'] = ja;\n```\n\n### **CodeSandbox**\n\nBut, how to import it dynamicly?\n\nI googled it, but helped little. Greate thank for anyone help!\n\n========================================\n\nTop Answer:\nBased on @Lucas Dawson's answer\n\nfor those who have to run their code on both vite and webpack\n\n**plugins/i18n.js**\n\n```\nimport Vue from 'vue';\nimport VueI18n from 'vue-i18n';\n\nVue.use(VueI18n);\n\n/***\nmake sure your public config has `VITE_` prefix or it can't be seen in the client side\nhttps://vitejs.dev/guide/env-and-mode.html#env-files\n***/\nlet messages = Object,\n locales = process.env.VITE_AVAILABLE_LOCALES.split(',');\n\n// check is using vite or webpack\nif (typeof __webpack_require__ !== 'function') {\n // for vite\n\n /***\n glob and globEager are both work for this\n https://vitejs.dev/guide/features.html#glob-import\n\n the differences is\n `glob` will return a dynamic import function (lazy load)\n `globEager` will return the data of the file from the path directly\n\n if you use `glob`, don't forget `JSON.parse(JSON.stringify(**Your data**))`\n if you have trouble with this, use `globEager` may save your day\n ***/\n\n let modules = import.meta.globEager('/lang/*.json');\n locales.forEach(locale => {\n messages[locale] = modules[`/lang/${locale}.json`];\n });\n}\nelse {\n // for webpack (storybook)\n locales.forEach(locale => {\n messages[locale] = require(`~/lang/${locale}.json`);\n });\n}\n\nexport default ({ app, store }) => {\n app.i18n = new VueI18n({\n locale: store.getters['locale/locale'],\n messages\n });\n}\n```\n\nThanks again for @Lucas Dawson's answer!\n\n========================================\n\nCode:\n```js\nimport Vue from 'vue';\nimport VueI18n from 'vue-i18n';\nimport config from '@/config';\n\nVue.use(VueI18n);\n\nlet messages = Object;\n\nconfig.locale.available.forEach(locale => {\n    messages[locale] = require(`~/locales/${locale}.json`);\n});\n\nexport default ({ app, store }) => {\n    app.i18n = new VueI18n({\n        locale: store.state.locale.locale,\n        messages: messages\n    });\n}\n```\n\n```js\nlet messages = Object,\n    languages = import.meta.glob('../locales/*.json'); // => languages = {} (languages only get {} value)\n\nconfig.locale.available.forEach(locale => {\n    messages[locale] = languages[`../locales/${locale}.json`];\n});\n```\n\n```js\nlet messages = Object,\n    translate = lang => () => import(`@/locales/${lang}.json`).then(i => i.default || i);\n\nconfig.locale.available.forEach(locale => {\n    messages[locale] = translate(locale);\n});\n```\n\n```js\nimport en from '@/locales/en.json';\nimport fr from '@/locales/fr.json';\nimport ja from '@/locales/ja.json';\n\nlet messages = Object;\n\nmessages['en'] = en;\nmessages['fr'] = fr;\nmessages['ja'] = ja;\n```\n\n```text\nrequire()\n```\n\n```text\nlanguages\n```\n\n```text\n{}\n```\n\n```text\nimport()\n```\n\n```text\nimport()\n```\n\n```js\n//Importing your data \nconst data = import.meta.glob('../locales/*.json')\n\n//Ref helps with promises I think. I'm sure there are more elegant ways.\nconst imp = ref([{}])\n\n// From https://github.com/vitejs/vite/issues/77\n// by LiuQixuan commented on Jun 20\n\nfor (const path in data) {\n    data[path]().then((mod) => { \n        imp.value.push(mod)\n    })\n}\n```\n\n```js\nJSON.parse(JSON.stringify(**Your data**))\n```\n\n```html\n<div v-for=\"(module,i) in imp\" :key=\"i\">\n          <div v-for=\"(data,j) in module\" :key=\"j\">\n\n            //at this point you can read it fully with {{ data }}\n\n            <div v-for=\"(jsonText, k) in JSON.parse(JSON.stringify(data))\" :key=k\">\n              {{ jsonText.text }}\n              <div v-for=\"insideJson in jsonText\" :key=\"insideJson\">\n                {{ insideJson.yourtext }}\n              </div>\n            </div>\n          </div>\n     </div>\n```\n\n```js\nnew URL(*, import.meta.url)\n```\n\n```js\nfor (const path in modules) {\n      modules[path]().then(() => {\n        //*************\n        const imgURL = new URL(path, import.meta.url)\n        //*************\n        gallery.value.push(imgURL)\n      })\n    }\n    //Then reference that gallery.value in your :src\n```\n\n```text\nimp.values\n```\n\n```js\nimport Vue from 'vue';\nimport VueI18n from 'vue-i18n';\n\nVue.use(VueI18n);\n\n/***\nmake sure your public config has `VITE_` prefix or it can't be seen in the client side\nhttps://vitejs.dev/guide/env-and-mode.html#env-files\n***/\nlet messages = Object,\n    locales = process.env.VITE_AVAILABLE_LOCALES.split(',');\n\n// check is using vite or webpack\nif (typeof __webpack_require__ !== 'function') {\n    // for vite\n\n    /***\n    glob and globEager are both work for this\n    https://vitejs.dev/guide/features.html#glob-import\n\n    the differences is\n    `glob` will return a dynamic import function (lazy load)\n    `globEager` will return the data of the file from the path directly\n\n    if you use `glob`, don't forget `JSON.parse(JSON.stringify(**Your data**))`\n    if you have trouble with this, use `globEager` may save your day\n    ***/\n\n    let modules = import.meta.globEager('/lang/*.json');\n    locales.forEach(locale => {\n        messages[locale] = modules[`/lang/${locale}.json`];\n    });\n}\nelse {\n    // for webpack (storybook)\n    locales.forEach(locale => {\n        messages[locale] = require(`~/lang/${locale}.json`);\n    });\n}\n\nexport default ({ app, store }) => {\n    app.i18n = new VueI18n({\n        locale: store.getters['locale/locale'],\n        messages\n    });\n}\n```\n\n```js\nconst requireLocale = async fileName => {\n  try {\n    const files = import.meta.globEager(\"./i18n/*.json\")\n    const texts = files[`./i18n/${fileName}.json`]\n    return texts?.default || {}\n  }\n  catch (e) {\n    console.warn(`The file \"./i18n/${fileName}.json\" could not be loaded.`)\n    return {}\n  }\n}\n```\n\n```text\nimport.meta.glob\n```\n\n========================================\n\nComments:\n- One thing that bugged me, is that my IDE (vscode) didn't look \"healthy\" after importing the data with this syntax `const data = import.meta.glob('..&#47;locales&#47;*.json')`: it worked but the linting displayed it as if there was a closing parenthesis missing. I solved it by using a backslash such as `const data = import.meta.glob('..&#47;locales&#47;\\*.json')`","metadata":{"transformedAt":"2026-08-18T18:33:46.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":342,"estimatedTokens":1927}}211{"id":"stack-75864713","source":"stackoverflow","questionId":75864713,"title":"How do I display the version number from package.json in my vue3 app?","tags":["typescript","vuejs3","version","package.json","vite"],"text":"Title: How do I display the version number from package.json in my vue3 app?\nTags: typescript, vuejs3, version, package.json, vite\nSource: Stack Overflow\n\nQuestion:\nI want to display the version number of my app, defined in package.json. I am using Vite, Vue 3, Typescript, and script setup with composition API.\n\nI solved this exact problem I had, but I have too little reputation to answer this question:\n\nHow can I display the current app version from package.json to the user using Vite?\n\nSo here is how to do it in Vue 3.\n\nUse this answer as a basis: https://stackoverflow.com/a/74860417/12008976.\n\nSo, add\n\n```\nimport packageJson from \"./package.json\"\n```\n\nand\n\n```\ndefine: {\n 'import.meta.env.PACKAGE_VERSION': JSON.stringify(packageJson.version),\n},\n```\n\nto `vite.config.ts`\n\nAdd this\n\n```\n/// \n\ninterface ImportMetaEnv {\n readonly PACKAGE_VERSION: string\n}\n\ninterface ImportMeta {\n readonly env: ImportMetaEnv\n}\n```\n\nto `env.d.ts` in /src\n\nNow, this adds intellisense to `import.meta.env`. But you cannot use these import statements directly in a Vue component. I fixed it by using the globalProperties of the Vue app.\n\nAdd\n\n```\napp.config.globalProperties.versionNumber = import.meta.env.PACKAGE_VERSION\n```\n\nto `main.ts`\n\nNow, in a component, add\n\n```\n\nconst version = getCurrentInstance()?.appContext.config.globalProperties.versionNumber\n\n```\n\n```\n{{ version }}\n```\n\nMy question is: is this the best way to solve this in Vue 3?\n\n========================================\n\nCode:\n```text\nimport packageJson from \"./package.json\"\n```\n\n```text\ndefine: {\n  'import.meta.env.PACKAGE_VERSION': JSON.stringify(packageJson.version),\n},\n```\n\n```text\n/// <reference types=\"vite/client\" />\n\ninterface ImportMetaEnv {\n  readonly PACKAGE_VERSION: string\n}\n\ninterface ImportMeta {\n  readonly env: ImportMetaEnv\n}\n```\n\n```text\napp.config.globalProperties.versionNumber = import.meta.env.PACKAGE_VERSION\n```\n\n```text\n<script setup lang=\"ts\">\nconst version = getCurrentInstance()?.appContext.config.globalProperties.versionNumber\n</script>\n```\n\n```html\n<div>{{ version }}</div>\n```\n\n```text\nvite.config.ts\n```\n\n```text\nenv.d.ts\n```\n\n```text\nimport.meta.env\n```\n\n```text\nmain.ts\n```\n\n```text\nVITE_APP_VERSION=$npm_package_version\n```\n\n```text\nconst version = import.meta.env.VITE_APP_VERSION\n```\n\n```text\n.env\n```\n\n```text\n$npm_package_*\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- The variables are created by NPM when the \"scripts\" are run. See docs.npmjs.com/cli/v10/using-npm/scripts#packagejson-vars\n- Does this means `.env` must be exposed after `npm run build`?","metadata":{"transformedAt":"2026-08-18T18:33:46.408Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":151,"estimatedTokens":651}}212{"id":"stack-67744210","source":"stackoverflow","questionId":67744210,"title":"How to use asset URLs in style binding with Vite","tags":["css","vue.js","vuejs3","vite"],"text":"Title: How to use asset URLs in style binding with Vite\nTags: css, vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI want to show a background image from my assets folder. When I use an image tag, the image is shown properly, so the image is well placed, but throws a 404 when I use the `background-image` style. Any idea about what is happening?. I am using Vue 3 with TypeScript and Vite 2.\n\nThis does not resolve the URL:\n\n```\n\n```\n\nBut this does:\n\n```\n\n```\n\n========================================\n\nTop Answer:\nThis is due to vite can't handle alias by default, so we need to set up an alias in vite config file.\n\nthere is no need to setup the import image in script tag.\n\njust put the below code in vite.config.js file\n\n```\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\";\nimport path from \"path\";\n\nexport default defineConfig({\n plugins: [vue()],\n resolve: {\n alias: {\n \"@\": path.resolve(__dirname, \"/src\"),\n \"~@\": path.resolve(__dirname, \"/src\"),\n },\n },\n});\n```\n\n========================================\n\nCode:\n```html\n<div style=\"background-image: url(./assets/img/header.png)\"\n></div>\n```\n\n```html\n<img src=\"./assets/img/header.png\" alt=\"Header\" />\n```\n\n```text\nbackground-image\n```\n\n```html\n<script setup>\nimport imagePath from '@/assets/logo.svg'\n</script>\n\n<template>\n  <div class=\"logo\" :style=\"{ backgroundImage: `url(${imagePath})` }\"></div>\n</template>\n\n<style>\n.logo {\n  height: 400px;\n  width: 400px;\n}\n</style>\n```\n\n```text\nimport\n```\n\n```text\n<script>\n```\n\n```text\n@vue/compiler-sfc\n```\n\n```text\n<div>.style\n```\n\n```text\n<img>.src\n```\n\n```text\nimport\n```\n\n```text\n<script>\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\";\nimport path from \"path\";\n\nexport default defineConfig({\n  plugins: [vue()],\n  resolve: {\n    alias: {\n      \"@\": path.resolve(__dirname, \"/src\"),\n      \"~@\": path.resolve(__dirname, \"/src\"),\n    },\n  },\n});\n```\n\n========================================\n\nComments:\n- What if I want to use backgroundImage on a pseudo-element? This wouldn't work with inline css, would it?\n- Well, that's annoying, Vite. Who thought that one up?\n- I have the same issue with a background image showing up on the entire site. How would this trick work for that?\n- If anyone is inside react functional component like me then `:style=\"{ backgroundImage: `url(${imagePath})` }\"` wont work, `style={{'backgroundImage': `url(${imagePath})`}}` would\n- After struggling for hours, this was the solution that worked for me. Thanks a lot!\n- The OP is not using an alias in the URL. Also, setting up the alias would not automatically resolve the path in the style binding for the `` (demo).","metadata":{"transformedAt":"2026-08-18T18:33:46.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":130,"estimatedTokens":669}}213{"id":"stack-67707813","source":"stackoverflow","questionId":67707813,"title":"defining global variables with vite development","tags":["vue.js","global-variables","vuejs3","vite"],"text":"Title: defining global variables with vite development\nTags: vue.js, global-variables, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nNow I am using **vite build tool** for my **vue SFC app**. I read the documentation of vite with the link below:\n\nvite config link\n\nIf I am not wrong, the **define** option in config could be used for defining **global constants**. What I want to do is to define for example the name of my App in a variable inside this option and then use it in my Vue components. But unfortunately there is no example of code in the documentation about this option.\n\nI tried this code in my **vite.config.js** file:\n\n\r\n\r\n\n```\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n define: {\n global: {\n appName: \"my-custom-name\"\n }\n },\n plugins: [vue()]\n})\n```\n\n\r\n\r\n\r\n\nI am not sure that the syntax and code is *correct*! And also if it is correct I don't know how to call (use) this constant in my vue app components (*.vue files*). For example I want to use it in **template** or **script** part of this component:\n\n\r\n\r\n\n```\n\n \n\n \n{{ use here }}\n \n\n export default {\n data() {\n return {\n name: use here\n };\n },\n \n methods: {\n nameMethod() {\n \n \n console.log(use here);\n \n }\n\n } // end of method\n\n } // end of export\n\n```\n\n\r\n\r\n\r\n\nI declared the places that want with **\"use here\"** in the code. And also if there is any other way that I could define some global constants and variables in my **vite** vue app, I very much appreciate your help to tell me about that.\n\n========================================\n\nCode:\n```js\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  define: {\n      global: {\n        appName: \"my-custom-name\"\n      }\n  },\n  plugins: [vue()]\n})\n```\n\n```html\n<template>\n    <div class=\"bgNow\">\n\n    <p class=\"color1\">\n{{ use here }}\n    </p>\n\n</template>\n\n<script>\n\n    export default {\n        data() {\n            return {\n              name: use here\n            };\n        },\n        \n        methods: {\n            nameMethod() {\n                \n                \n                console.log(use here);\n                \n            }\n\n        } // end of method\n\n    } // end of export\n</script>\n\n<style scoped></style>\n```\n\n```js\nexport default defineConfig({\n  define: {\n    appName: JSON.stringify('my-custom-name')\n  }\n})\n```\n\n```html\n<script setup>\nconsole.log('appName', appName)\n</script>\n```\n\n```html\n<script setup>\nconsole.log(\"appName\", \"my-custom-name\")\n</script>\n```\n\n```text\ndefine\n```\n\n```text\nappName\n```\n\n```text\n\"my-custom-name\"\n```\n\n```text\nJSON.stringify()\n```\n\n```text\nApp.vue\n```\n\n========================================\n\nComments:\n- The `define` section of the Vite docs has moved here:\n- I used this approach in my Vue.js app + Vite 4. But the defined variable can not found!.\n- Tested it for Next JS as well works perfectly fine. If you are using TypeScript make sure to declare a const as stated in the docs.\n- Looks like replacement doesn't happen in the `` section? stackoverflow.com/questions/77133977/&hellip;\n- Oh!. when i first read docs i though it would provide me a gloabal constant variable which i can access across my app. vite docs does not contain any example for this that is why it can be confusing.","metadata":{"transformedAt":"2026-08-18T18:33:46.408Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":176,"estimatedTokens":838}}214{"id":"stack-74987006","source":"stackoverflow","questionId":74987006,"title":"TailwindCSS not working with Vite + React","tags":["javascript","reactjs","tailwind-css","vite","tailwind-css-3"],"text":"Title: TailwindCSS not working with Vite + React\nTags: javascript, reactjs, tailwind-css, vite, tailwind-css-3\nSource: Stack Overflow\n\nQuestion:\nI am initializing TailwindCSS using Create React App (CRA); so my project built with Vite, React, but can't get it to work.\n\nIt seems like postcss and autoprefixer is not getting installed, when I try to install manually it gives the following error:\n\n```\nwarning Pattern [\"postcss@^8.4.20\"] is trying to unpack in the same destination \"C:\\\\Users\\\\NUR\\\\AppData\\\\Local\\\\Yarn\\\\Cache\\\\v6\\\\npm-postcss-8.4.20-64c52f509644cecad8567e949f4081d98349dc56-integrity\\\\node_modules\\\\postcss\" as pattern [\"postcss@^8.4.18\",\"postcss@^8.4.20\"]. This could result in non-deterministic behavior, skipping.\n[3/4] Linking dependencies...\nwarning \" > tailwindcss@3.2.4\" has unmet peer dependency \"postcss@^8.0.9\".\n```\n\n========================================\n\nTop Answer:\nI followed the documentation to install tailwind with Vite and React and it didn't work either. Then I added these changes in vite.config.js and it worked.\n\n```\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport tailwindcss from \"tailwindcss\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n css: {\n postcss: {\n plugins: [tailwindcss()],\n },\n },\n});\n```\n\n========================================\n\nCode:\n```none\nwarning Pattern [\"postcss@^8.4.20\"] is trying to unpack in the same destination \"C:\\\\Users\\\\NUR\\\\AppData\\\\Local\\\\Yarn\\\\Cache\\\\v6\\\\npm-postcss-8.4.20-64c52f509644cecad8567e949f4081d98349dc56-integrity\\\\node_modules\\\\postcss\" as pattern [\"postcss@^8.4.18\",\"postcss@^8.4.20\"]. This could result in non-deterministic behavior, skipping.\n[3/4] Linking dependencies...\nwarning \" > tailwindcss@3.2.4\" has unmet peer dependency \"postcss@^8.0.9\".\n```\n\n```text\nmodule.exports = {\n  plugins: {\n    tailwindcss: {},\n    autoprefixer: {}\n  }\n};\n```\n\n```text\nnpx tailwindcss init -p\n```\n\n```text\npostcss.config.cjs\n```\n\n```text\nnpx tailwindcss init -p\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport tailwindcss from \"tailwindcss\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  css: {\n    postcss: {\n      plugins: [tailwindcss()],\n    },\n  },\n});\n```\n\n```text\nimport tailwindcss from \"tailwindcss\";\n```\n\n```text\nvite.config.js\n```\n\n```text\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n```text\nexport default {\n  content: [\"./index.html\", \"./src/**/*.{html,js,ts,jsx,tsx}\"],\n  theme: {\n    extend: {},\n  },\n  plugins: [],\n};\n```\n\n```text\nnpm install -D tailwindcss@3 postcss autoprefixer\n```\n\n```text\nnpx tailwindcss init -p\n```\n\n```text\ntailwind.config.js\n```\n\n```js\ncontent: [\n    \"./index.html\",\n    \"./src/**/*.{js,ts,jsx,tsx}\",\n  ],\n```\n\n```text\nnpm install -D tailwindcss postcss autoprefixer\nnpx tailwindcss init -p\n```\n\n```text\nexport default {\n  plugins: {\n    tailwindcss: {},\n    autoprefixer: {},\n  },\n};\n```\n\n```text\nexport default {\n  content: [\"./src/**/*.{html,js,jsx}\"],\n  theme: {\n    extend: {},\n    },\n  },\n  plugins: [],\n};\n```\n\n```text\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n```text\npostcss.config.js\n```\n\n```text\ntailwind.config.js\n```\n\n```text\nmain.css or index.css\n```\n\n```text\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n```text\n./src/index.css\n```\n\n```text\nimport { defineConfig } from \"vite\"; \nimport react from \"@vitejs/plugin-react\"; \nimport tailwindcss from \"tailwindcss\";\n\n// https://vitejs.dev/config/ \nexport default defineConfig({   \n    plugins: [react()],   \n    css: {\n        postcss: {\n            plugins: [tailwindcss()],\n        },   \n    }, \n});\n```\n\n```text\n<script src=\"https://cdn.tailwindcss.com\"></script>\n```\n\n```text\nindex.html\n```\n\n```js\nexport default {\n    plugins: {\n      tailwindcss: {},\n      autoprefixer: {},\n    },\n  }\n```\n\n```text\nnpm i postcss\n```\n\n```text\nnpm i autoprefixer\n```\n\n========================================\n\nComments:\n- Perhaps try use https://tailwindcss.com/docs/guides/vite as a reference instead of the guide for CRA.\n- @JohnLi I have tried using the vite guide , it still doesn't work and gives the same issue\n- Can you show you package.json and tailwind.config.cjs ?\n- I have copied the TailWind config exactly from the guide\n- I just tried and only one thing went wrong, there was no postcss.config.cjs Did you have it when you tried npx tailwindcss init -p ?\n- No , same for me , postcss isn't getting installed, and the config is also not generated on npx init\n- The question is too old - if you've come across it now, you're probably using TailwindCSS v4 instead of v3. This other question relates to v4: Deprecated CRA; new plugins for TailwindCSS v4\n- This question is similar to: Error: PostCSS plugin tailwindcss requires PostCSS 8. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.\n- Related for v4 with PostCSS: Error: PostCSS plugin tailwindcss requires PostCSS 8\n- In a comment, wrongly posted as an answer here, mentions \"in changing the default export to a module export, at least in my case, breaks the entire app.\"\n- and if you want to keep your postcss.config.js, you can move `tailwindcss()` from the vite config file to your separate postcss config file - for me, I had to place it before the other plugins that I am using.\n- respectfully, the language used in your answer is impossible to decipher.\n- Please explain how this addresses the issue. What have you changed? Code-only answers are not good answers\n- This vite.config.js file does the following: It integrates React support via @vitejs/plugin-react. It configures PostCSS to use Tailwind CSS for processing styles, ensuring the proper Tailwind classes are applied. It optimizes your development environment for React with fast refresh and efficient style processing.","metadata":{"transformedAt":"2026-08-18T18:33:46.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":234,"estimatedTokens":1480}}215{"id":"stack-75469067","source":"stackoverflow","questionId":75469067,"title":"How to prevent reloading (due to optimized dependencies) causing the test to fail?","tags":["vue.js","cypress","vuetify.js","vite"],"text":"Title: How to prevent reloading (due to optimized dependencies) causing the test to fail?\nTags: vue.js, cypress, vuetify.js, vite\nSource: Stack Overflow\n\nQuestion:\nWhen I'm running Cypress component test, sometimes i'm facing this :\n\n```\n17:34:59 [vite] ✨ new dependencies optimized: vuetify/components, vuetify/lib/components/VAppBar/index.mjs, vuetify/lib/components/VDivider/index.mjs, vuetify/lib/components/VToolbar/index.mjs, @vueuse/core\n17:34:59 [vite] ✨ optimized dependencies changed. reloading\n\n1) An uncaught error was detected outside of a test\n```\n\nAnd the test fails... If I relaunch tests a second time, everything is ok : all tests pass.\nAnything I can do to prevent this ?\n\nMy `cypress.config.ts` is quite simple :\n\n```\nexport default defineConfig({\n video: false,\n env: {\n codeCoverage: {\n exclude: ['cypress/**/*.*', 'src/**/*.cy.ts'],\n },\n },\n component: {\n devServer: {\n framework: 'vue',\n bundler: 'vite',\n },\n setupNodeEvents(on, config) {\n registerCodeCoverageTasks(on, config)\n\n return config\n },\n },\n})\n```\n\nSo do my `vite.config.ts` :\n\n```\nexport default defineConfig({\n plugins: [\n vue(), // SFC\n vuetify({\n autoImport: true,\n }),\n istanbul({\n cypress: true,\n requireEnv: false,\n }),\n ],\n resolve: {\n alias: {\n '@': resolve(__dirname, 'src'),\n },\n extensions: ['.js', '.json', '.jsx', '.mjs', '.ts', '.tsx', '.vue'],\n },\n }\n})\n```\n\n========================================\n\nTop Answer:\nIn my case the library that was causing the dependencies to be optimized was `antd`.\n\nI tried several different `optimizeDeps` options for Vite but none of them worked for me.\n\nWhat I did instead was to find all imports of `antd` and change them to import from `antd/es` instead.\n\nIn your case I suspect that changing your `vuetify` imports to use `dist` instead of `lib` subfolder will fix the issue.\n\nSo instead of:\n\n```\nimport { whatever } from 'vuetify/**lib**/whatever'\n```\n\nYou could try:\n\n```\nimport { whatever } from 'vuetify/**dist**/whatever'\n```\n\n========================================\n\nCode:\n```text\n17:34:59 [vite] ✨ new dependencies optimized: vuetify/components, vuetify/lib/components/VAppBar/index.mjs, vuetify/lib/components/VDivider/index.mjs, vuetify/lib/components/VToolbar/index.mjs, @vueuse/core\n17:34:59 [vite] ✨ optimized dependencies changed. reloading\n\n1) An uncaught error was detected outside of a test\n```\n\n```text\nexport default defineConfig({\n  video: false,\n  env: {\n    codeCoverage: {\n      exclude: ['cypress/**/*.*', 'src/**/*.cy.ts'],\n    },\n  },\n  component: {\n    devServer: {\n      framework: 'vue',\n      bundler: 'vite',\n    },\n    setupNodeEvents(on, config) {\n      registerCodeCoverageTasks(on, config)\n\n      return config\n    },\n  },\n})\n```\n\n```text\nexport default defineConfig({\n  plugins: [\n    vue(), // SFC\n    vuetify({\n      autoImport: true,\n    }),\n    istanbul({\n      cypress: true,\n      requireEnv: false,\n    }),\n  ],\n resolve: {\n    alias: {\n      '@': resolve(__dirname, 'src'),\n    },\n    extensions: ['.js', '.json', '.jsx', '.mjs', '.ts', '.tsx', '.vue'],\n  },\n }\n})\n```\n\n```text\ncypress.config.ts\n```\n\n```text\nvite.config.ts\n```\n\n```js\n// vite.config.ts\nexport default defineConfig({\n  ...,\n  optimizeDeps: {\n    exclude: ['vuetify'],\n    // or include: ['vuetify'], ?\n  },\n```\n\n```js\noptimizeDeps: {\n    entries: ['./src/**/*.{vue,js,jsx,ts,tsx}'],\n```\n\n```text\nvite.config.ts\n```\n\n```text\nvite-plugin-vuetify\n```\n\n```text\noptimizeDeps.include\n```\n\n```text\noptimizeDeps.exclude\n```\n\n```text\ninclude\n```\n\n```text\nexclude\n```\n\n```text\n@vueuse/core\n```\n\n```text\n.vue\n```\n\n```text\noptimizeDeps.entries\n```\n\n```text\nimport { whatever } from 'vuetify/**lib**/whatever'\n```\n\n```text\nimport { whatever } from 'vuetify/**dist**/whatever'\n```\n\n```text\nantd\n```\n\n```text\noptimizeDeps\n```\n\n```text\nantd\n```\n\n```text\nantd/es\n```\n\n```text\nvuetify\n```\n\n```text\ndist\n```\n\n```text\nlib\n```\n\n```text\ndescribe(\n  'ensure xyz works',\n  {\n    retries: {\n      runMode: 2,\n      openMode: 1\n    }\n  },\n  () => {\n    it('Should ...', () => {\n      cy.visit('/...')\n\n      cy.contains('Continue').click()\n\n      // previously would consistently get stuck here\n\n      cy.url().should('include', '/next-page')\n   \n      ...\n    \n    })\n  }\n)\n```\n\n```text\nviteConfig: {\n...\noptimizeDeps: {\n   entries: [\n      'cypress/support/component.ts',\n      'cypress/tests/component/**/*', // or wherever your component spec files are. You could also just move the value you're passing to specPattern outside the config and pass it here as well\n   ],\n}\n```\n\n========================================\n\nComments:\n- `exclude: ['vuetify']` was the only thing that worked with `vuetify({ styles: 'none' })` as a plugin.\n- excluding the dependencies in this config, automatically fail my test. It seems Cypress couldn't import this module when we exclude in the config. > module is not defined at (localhost:3000/__cypress/src/node_modules/moment-timezone/&hellip;&zwnj;&#8203;)","metadata":{"transformedAt":"2026-08-18T18:33:46.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":279,"estimatedTokens":1230}}216{"id":"stack-68046410","source":"stackoverflow","questionId":68046410,"title":"how to force vite clearing cache in vue3","tags":["caching","bundle","vuejs3","rollup","vite"],"text":"Title: how to force vite clearing cache in vue3\nTags: caching, bundle, vuejs3, rollup, vite\nSource: Stack Overflow\n\nQuestion:\nI have a side project with `Vue.js 3` and `vite` as my bundler.\n\nAfter each build the bundled files got the same hash from the build before, like:\n\n```\nindex.432c7f2f.js so after each new build (with the same hash on the files) I had to reload the browser hard to clear the cache and see the changes I made.\n\nI tried forcing a clearing with a different version number in the `package.json`, but:\n\n- It does not work in the Vite/Rollup environment,\n\n- it doesn't make sense to enter a new number by hand every time after a change.\n\n### Question:\n\nIs there any way to configure vite to randomly create new hashes after a new build, or do you know another trick to clear the cache?\n\n========================================\n\nTop Answer:\nTo go off of @wittgenstein answer, you can also just use the version from `package.json` as well (when you need to make sure cache is busted when releasing to production):\n\n```\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport { version } from './package.json'\n\nexport default defineConfig({\n plugins: [vue()],\n build: {\n rollupOptions: {\n output: {\n entryFileNames: `[name].js?v=${version}`,\n chunkFileNames: `[name].js?v=${version}`,\n assetFileNames: `[name].[ext]?v=${version}`\n }\n }\n }\n})\n```\n\nAnd it doesn't have to be the filename itself, the browser will see any query arguments added to the file as a different file\n\nA PWA may give issues with doing this, for that just add version to the filename similar to solution above:\n\n```\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport { version } from './package.json'\n\nexport default defineConfig({\n plugins: [vue()],\n build: {\n rollupOptions: {\n output: {\n entryFileNames: `[name].${version}.js`,\n chunkFileNames: `[name].${version}.js`,\n assetFileNames: `[name].${version}.[ext]`\n }\n }\n }\n})\n```\n\n========================================\n\nCode:\n```text\nindex.432c7f2f.js   <-- the hash will be identical after each new build\nindex.877e2b8d.css\nvendor.67f46a28.js\n```\n\n```text\nVue.js 3\n```\n\n```text\nvite\n```\n\n```text\npackage.json\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport { hash } from './src/utils/functions.js'\n\nexport default defineConfig({\n  plugins: [vue()],\n  build: {\n    rollupOptions: {\n      output: {\n        entryFileNames: `[name]` + hash + `.js`,\n        chunkFileNames: `[name]` + hash + `.js`,\n        assetFileNames: `[name]` + hash + `.[ext]`\n      }\n    }\n  }\n})\n```\n\n```js\n// functions.js\nexport const hash = Math.floor(Math.random() * 90000) + 10000;\n```\n\n```text\ndist/index.html\ndist/index87047.css\ndist/index87047.js\ndist/vendor87047.js\n\nor\n\ndist/index.html\ndist/index61047.css\ndist/index61047.js\ndist/vendor61047.js\n\n...\n```\n\n```text\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport { version } from './package.json'\n\nexport default defineConfig({\n  plugins: [vue()],\n  build: {\n    rollupOptions: {\n      output: {\n          entryFileNames: `[name].js?v=${version}`,\n          chunkFileNames: `[name].js?v=${version}`,\n          assetFileNames: `[name].[ext]?v=${version}`\n      }\n    }\n  }\n})\n```\n\n```text\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport { version } from './package.json'\n\nexport default defineConfig({\n  plugins: [vue()],\n  build: {\n    rollupOptions: {\n      output: {\n          entryFileNames: `[name].${version}.js`,\n          chunkFileNames: `[name].${version}.js`,\n          assetFileNames: `[name].${version}.[ext]`\n      }\n    }\n  }\n})\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- That is great. It works for me. I could jsut refresh a page and get the the build content.but I do not get why. Vite seems to add already random numbers to its files? How is this different?\n- Yes, but it should be possible to see the new content without refreshing the page. The randomized hashing will do that for you. This way, every user (even those who have been on your site before) will see the latest content.\n- Yes, I noticed and that was the reason I tried that in the first place, which is doing excactly that super gerat :D I am only confused, since Vite gives the files already an alpha numeric hash. Why did it not work straight away, but needs a forced numeric hash?\n- Here is the problem. The hash is not changed. **The browser cache thinks it is the old file**. With the randomized hash, the browser automatically fetches the new file and displays the site with all the new changes. Remember that not every user will update your page. That's what this randomized hashing will do for you.\n- Thank you a lot for the explanation. That makes perfect sense. Just for clarification: That the hash var comes in from an import is just a preference or does it matters, if it is written direct in vite.config.js?\n- It does not matter. It's just javascript. I'm glad I could help.\n- I think there is a misunderstanding here. Vite already takes this approach by default. How is this different from what vite does?\n- @RoboKozo, thanks for mentioned it. Maybe there is a mismatch between 2021 and now.\n- @RoboKozo, Vite uses the content hash by default, not randomized hash. The problem is, content hash is not working for the topic starter for some reason. It works correctly for me in React app though.\n- how do you update the version number of your application? Because if you don't change them, the bundled files will have the same name and the client has to hard reload your page to see the changes.\n- You update it in the `package.json` file assuming you are versioning your code that you're releasing (really for production releases)\n- I also applied this solution, but I need to keep the name of entry files the same. Setting `entryFileNames` to `[name].js` will do it, but it doesn't work for CSS inside `index.html`. I want to keep every build generated with the same `index.html`. Any ideas?\n- ?v=${version} is JSON, you need to stringify. Try this instead: ?v=${JSON.stringify(version)}","metadata":{"transformedAt":"2026-08-18T18:33:46.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":193,"estimatedTokens":1562}}217{"id":"stack-72793590","source":"stackoverflow","questionId":72793590,"title":"I can't run 'npm run dev' since Laravel updated with Vite","tags":["laravel","compiler-errors","vite"],"text":"Title: I can't run 'npm run dev' since Laravel updated with Vite\nTags: laravel, compiler-errors, vite\nSource: Stack Overflow\n\nQuestion:\nTaylor Otwell announced that new Laravel projects now will run with Vite and that Vite is installed by default. I can't seem to be able to run dev environment `npm run dev`\n\nI installed new laravel project, installed Laravel JetStream with SSR and teams support hit the 'npm install command'.\n\nEvery time I run `npm run dev` it shows this:\n\nhttps://i.sstatic.net/42Ge0.png\n\nAnd if I open the local link, it shows this:\n\nhttps://i.sstatic.net/u7t4V.png\n\nWhy can't I user `npm run dev` and compile my files?\n\nThis is package.json for my brand new laravel app\n\n\r\n\r\n\n```\n{\n \"private\": true,\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build && vite build --ssr\"\n },\n \"devDependencies\": {\n \"@inertiajs/inertia\": \"^0.11.0\",\n \"@inertiajs/inertia-vue3\": \"^0.6.0\",\n \"@inertiajs/progress\": \"^0.2.7\",\n \"@inertiajs/server\": \"^0.1.0\",\n \"@tailwindcss/forms\": \"^0.5.2\",\n \"@tailwindcss/typography\": \"^0.5.2\",\n \"@vitejs/plugin-vue\": \"^2.3.3\",\n \"@vue/server-renderer\": \"^3.2.31\",\n \"autoprefixer\": \"^10.4.7\",\n \"axios\": \"^0.25\",\n \"laravel-vite-plugin\": \"^0.2.1\",\n \"lodash\": \"^4.17.19\",\n \"postcss\": \"^8.4.14\",\n \"tailwindcss\": \"^3.1.0\",\n \"vite\": \"^2.9.11\",\n \"vue\": \"^3.2.31\"\n }\n}\n```\n\n\r\n\r\n\r\n\nand if I try hitting 'vite' in the terminal I get this:\n\nhttps://i.sstatic.net/beOvo.png\n\n========================================\n\nTop Answer:\nIf you don't want to use `vite` but `mix` instead in your new laravel project, you can just get the usual behavior of `npm run dev` back with the following changes:\n\n- Install Laravel Mix (because by the new installation it is not there anymore):\n\n```\nnpm install --save-dev laravel-mix\n```\n\n- Create a `webpack.mix.js` file, if it is not there, and make sure it has the following content:\n\n```\nconst mix = require('laravel-mix');\n\n/*\n|--------------------------------------------------------------------------\n| Mix Asset Management\n|--------------------------------------------------------------------------\n|\n| Mix provides a clean, fluent API for defining some Webpack build steps\n| for your Laravel applications. By default, we are compiling the CSS\n| file for the application as well as bundling up all the JS files. \n|\n*/\n\nmix.js('resources/js/app.js', 'public/js')\n .postCss('resources/css/app.css', 'public/css', [\n //\n]);\n```\n\n- Update `package.json`:\n\n```\n\"scripts\": {\n- \"dev\": \"vite\",\n- \"build\": \"vite build\"\n+ \"dev\": \"npm run development\",\n+ \"development\": \"mix\",\n+ \"watch\": \"mix watch\",\n+ \"watch-poll\": \"mix watch -- --watch-options-poll=1000\",\n+ \"hot\": \"mix watch --hot\",\n+ \"prod\": \"npm run production\",\n+ \"production\": \"mix --production\"\n}\n```\n\n- Remove vite helper functions (if they are there):\n\n```\n- import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';\n\n createInertiaApp({\n title: (title) => `${title} - ${appName}`,\n- resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),\n+ resolve: (name) => require(`./Pages/${name}.vue`),\n setup({ el, app, props, plugin }) {\n return createApp({ render: () => h(app, props) })\n .use(plugin)\n .mixin({ methods: { route } })\n .mount(el);\n },\n});\n```\n\n- Update environment valiables (in .env, `VITE_` prefix to `MIX_`):\n\n```\n- VITE_PUSHER_APP_KEY=\"${PUSHER_APP_KEY}\"\n- VITE_PUSHER_APP_CLUSTER=\"${PUSHER_APP_CLUSTER}\"\n+ MIX_PUSHER_APP_KEY=\"${PUSHER_APP_KEY}\"\n+ MIX_PUSHER_APP_CLUSTER=\"${PUSHER_APP_CLUSTER}\"\n```\n\n- Remove Vite and the laravel Plugin\n\n```\nnpm remove vite laravel-vite-plugin\n```\n\n- Remove the Vite config file:\n\n```\nrm vite.config.js\n```\n\n- Remove these paths from .gitignore:\n\n```\n- /public/build\n- /storage/ssr\n```\n\nIf you created some code already with vite, you must have some more changes in your blade files, check out this article. But if it is a new project, you just good to go.\n\n========================================\n\nCode:\n```js\n{\n    \"private\": true,\n    \"scripts\": {\n        \"dev\": \"vite\",\n        \"build\": \"vite build && vite build --ssr\"\n    },\n    \"devDependencies\": {\n        \"@inertiajs/inertia\": \"^0.11.0\",\n        \"@inertiajs/inertia-vue3\": \"^0.6.0\",\n        \"@inertiajs/progress\": \"^0.2.7\",\n        \"@inertiajs/server\": \"^0.1.0\",\n        \"@tailwindcss/forms\": \"^0.5.2\",\n        \"@tailwindcss/typography\": \"^0.5.2\",\n        \"@vitejs/plugin-vue\": \"^2.3.3\",\n        \"@vue/server-renderer\": \"^3.2.31\",\n        \"autoprefixer\": \"^10.4.7\",\n        \"axios\": \"^0.25\",\n        \"laravel-vite-plugin\": \"^0.2.1\",\n        \"lodash\": \"^4.17.19\",\n        \"postcss\": \"^8.4.14\",\n        \"tailwindcss\": \"^3.1.0\",\n        \"vite\": \"^2.9.11\",\n        \"vue\": \"^3.2.31\"\n    }\n}\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run dev\n```\n\n```text\nLaravel Project\n```\n\n```text\nLatest (v9.19.0)\n```\n\n```text\nnode_modules\n```\n\n```text\nnpm install\n```\n\n```text\nphp artisan serve\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run dev\n```\n\n```text\nphp artisan serve\n```\n\n```text\nnpm install --save-dev laravel-mix\n```\n\n```text\nconst mix = require('laravel-mix');\n\n/*\n|--------------------------------------------------------------------------\n| Mix Asset Management\n|--------------------------------------------------------------------------\n|\n| Mix provides a clean, fluent API for defining some Webpack build steps\n| for your Laravel applications. By default, we are compiling the CSS\n| file for the application as well as bundling up all the JS files. \n|\n*/\n\nmix.js('resources/js/app.js', 'public/js')\n   .postCss('resources/css/app.css', 'public/css', [\n       //\n]);\n```\n\n```text\n\"scripts\": {\n-     \"dev\": \"vite\",\n-     \"build\": \"vite build\"\n+     \"dev\": \"npm run development\",\n+     \"development\": \"mix\",\n+     \"watch\": \"mix watch\",\n+     \"watch-poll\": \"mix watch -- --watch-options-poll=1000\",\n+     \"hot\": \"mix watch --hot\",\n+     \"prod\": \"npm run production\",\n+     \"production\": \"mix --production\"\n}\n```\n\n```text\n- import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';\n\n  createInertiaApp({\n      title: (title) => `${title} - ${appName}`,\n-     resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),\n+     resolve: (name) => require(`./Pages/${name}.vue`),\n      setup({ el, app, props, plugin }) {\n          return createApp({ render: () => h(app, props) })\n              .use(plugin)\n              .mixin({ methods: { route } })\n              .mount(el);\n      },\n});\n```\n\n```text\n- VITE_PUSHER_APP_KEY=\"${PUSHER_APP_KEY}\"\n- VITE_PUSHER_APP_CLUSTER=\"${PUSHER_APP_CLUSTER}\"\n+ MIX_PUSHER_APP_KEY=\"${PUSHER_APP_KEY}\"\n+ MIX_PUSHER_APP_CLUSTER=\"${PUSHER_APP_CLUSTER}\"\n```\n\n```text\nnpm remove vite laravel-vite-plugin\n```\n\n```text\nrm vite.config.js\n```\n\n```text\n- /public/build\n- /storage/ssr\n```\n\n```text\nvite\n```\n\n```text\nmix\n```\n\n```text\nnpm run dev\n```\n\n```text\nwebpack.mix.js\n```\n\n```text\npackage.json\n```\n\n```text\nVITE_\n```\n\n```text\nMIX_\n```\n\n```text\nserver: {\n    hmr: {\n        host: 'localhost',\n    },\n}\n```\n\n```text\nnpm install\n```\n\n```text\nnpm run dev\n```\n\n```text\nphp artisan serve\n```\n\n```text\n<head>\n\n<title>my project</title>\n\n@vite(['/resources/js/app.js', '/resources/css/app.css'])\n```\n\n```text\nAPP_URL=http://localhost:8000\n```\n\n```text\n.env\n```\n\n```text\nphp artisan serve\n```\n\n```text\nnpm run dev\n```\n\n========================================\n\nComments:\n- Op has created a brand new laravel install, so upgrade guides shouldn't be necessary.\n- Same problem for me. Fresh new installation of Laravel Sail. Everything fits the upgrade guide steps. I can see just a blank page, but source code shows it is working, just inertia component is not loaded or something like that.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- Excellent answer to rollback to mix, but Vite is actually great and made the default for a reason. I recommend you create a migration branch to make your project work with Vite.\n- Is there I could do the same if I am using Reactjs instead of Vue?\n- certainly yes, but I haven't tried it yet.\n- Ok, tried this after hours and hours trying to get my brand new Laravel project running. Now instead of getting \"sh: 1: vite: not found\" I instead get \"sh: 1: mix: not found\" when I try to run npm run dev. Why can't just Laravel work out of the box???\n- @DanielMalmgren Indeed, why can;t it work out of the box. It looks like every new version the syntax changed, the file locations changed and nearly none of the instructions works out of the box.\n- on vitejs.dev/guide/#scaffolding-your-first-vite-project page is writing : `Vite requires Node.js version 14.18+, 16+…`","metadata":{"transformedAt":"2026-08-18T18:33:46.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":36,"totalLines":390,"estimatedTokens":2204}}218{"id":"stack-71767581","source":"stackoverflow","questionId":71767581,"title":"How do I disable minification when running \"build\" command in sveltekit?","tags":["svelte","vite","sveltekit"],"text":"Title: How do I disable minification when running \"build\" command in sveltekit?\nTags: svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am deploying sveltekit to a dfinity container and I need to disable minification to debug.\n\nI have to build a static version to deploy it with `npm run build` -- is there a vite option to disable minification?\n\nI've tried this: `svelte.config.js` but it doesn't do anything:\n\n```\nvite: {\n resolve: {\n alias: {\n $components: path.resolve('./src/components'),\n $stores: path.resolve('./src/stores'),\n $api: path.resolve('./src/api')\n }\n },\n build: {\n minify: false\n }\n}\n```\n\n========================================\n\nCode:\n```js\nvite: {\n    resolve: {\n        alias: {\n            $components: path.resolve('./src/components'),\n            $stores: path.resolve('./src/stores'),\n            $api: path.resolve('./src/api')\n        }\n    },\n    build: {\n        minify: false\n    }\n}\n```\n\n```text\nnpm run build\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n    plugins: [sveltekit()],\n    build: {\n        minify: false\n    }\n});\n```\n\n```text\nvite.config.js/ts\n```\n\n========================================\n\nComments:\n- I cannot reproduce the issue. `vite.build.minify=false` does actually disable minification in a newly scaffolded SvelteKit project. Can you a link to a reproduction of the problem?\n- that works. it still compiled it but did not minify. so we're good.","metadata":{"transformedAt":"2026-08-18T18:33:46.408Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":73,"estimatedTokens":382}}219{"id":"stack-69540063","source":"stackoverflow","questionId":69540063,"title":"Vite - Static Files Are Not Copying","tags":["vue.js","vite"],"text":"Title: Vite - Static Files Are Not Copying\nTags: vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI have a Vue.js app that relies on Vite. In this app, I have two static files that I need to copy to my `dist` directory: `favicon.ico` and `manifest.json`. My `vite.config.js` file looks like this:\n\n```\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig(({command, mode }) => {\n return {\n assetsDir: 'res',\n plugins: [vue()],\n publicDir: 'dist',\n root: 'src',\n build: {\n emptyOutDir: true,\n outDir: '../dist'\n }\n }\n});\n```\n\nMy directory structure looks like this:\n\n```\n/\n /dist\n /src\n /assets\n favicon.ico\n manifest.json\n /res\n /css\n theme.css\n App.vue\n main.js\n index.html\n package.json\n README.md\n vite.config.js\n```\n\nWhen I compile my program using `npm run build`, I can see a file named `index.html` that gets created in the `dist` directory. However, I have been unsuccessful in getting the `favicon.ico` and `manifest.json` file copied to the `dist` directory, which is what I need. I tried adding `publicDir: 'assets'` to the `build` options. However, that didn't work. I also tried creating a `public` directory under the `src` directory in an effort to along with this documentation. However, that did not move the files to the directory. What am I doing wrong?\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig(({command, mode }) => {\n  return {\n    assetsDir: 'res',\n    plugins: [vue()],\n    publicDir: 'dist',\n    root: 'src',\n    build: {\n      emptyOutDir: true,\n      outDir: '../dist'\n    }\n  }\n});\n```\n\n```text\n/\n  /dist\n  /src\n    /assets\n      favicon.ico\n      manifest.json\n    /res\n      /css\n        theme.css\n    App.vue\n    main.js\n    index.html\n  package.json\n  README.md\n  vite.config.js\n```\n\n```text\ndist\n```\n\n```text\nfavicon.ico\n```\n\n```text\nmanifest.json\n```\n\n```text\nvite.config.js\n```\n\n```text\nnpm run build\n```\n\n```text\nindex.html\n```\n\n```text\ndist\n```\n\n```text\nfavicon.ico\n```\n\n```text\nmanifest.json\n```\n\n```text\ndist\n```\n\n```text\npublicDir: 'assets'\n```\n\n```text\nbuild\n```\n\n```text\npublic\n```\n\n```text\nsrc\n```\n\n```text\nroot: 'src'\n```\n\n```text\npublicDir: 'dist'\n```\n\n```text\npublic\n```\n\n```text\n./src/dist\n```\n\n```text\nvite.config.js\n```\n\n```text\npublic\n```\n\n```text\n/\n```\n\n```text\nfavicon.ico\n```\n\n```text\n/public\n```\n\n```text\ndist\n```\n\n```text\nvite\n```\n\n```text\npublicDir\n```\n\n```text\nvite\n```\n\n```text\nfavicon.ico\n```\n\n```text\ndist\n```\n\n```text\nvite build\n```\n\n```text\npublicDir\n```\n\n```text\npublic\n```\n\n```text\nroot\n```\n\n```text\nroot: './src'\n```\n\n```text\npublicDir: 'mypublic'\n```\n\n```text\n./src/mypublic\n```\n\n========================================\n\nComments:\n- I added a `public` directory under the `src` directory and at the same level as the `src` directory. Still, the contents of the `public` directory are *not* copied to the `dist` directory. I suspect it has something to do with either the `assetsDir` value or `root` value, but I haven't confirmed. Regardless, `favicon.ico` and `manifest.json` are not getting copied to the `dist` directory.\n- Thank you so much for this. I have been digging through Vite's documentation forever looking for this information and either its not there anymore or I'm just bad at reading","metadata":{"transformedAt":"2026-08-18T18:33:46.410Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":38,"totalLines":237,"estimatedTokens":848}}220{"id":"stack-74902697","source":"stackoverflow","questionId":74902697,"title":"Error: `The request url * is outside of Vite serving allow list` after git init of submodule inside pnpm monorepo workspace","tags":["nuxt.js","vite","pnpm-workspace"],"text":"Title: Error: `The request url * is outside of Vite serving allow list` after git init of submodule inside pnpm monorepo workspace\nTags: nuxt.js, vite, pnpm-workspace\nSource: Stack Overflow\n\nQuestion:\nI have setup a pnpm workspace with a number of projects that I am adding as git submodules.\n\nA previously working Nuxt project suddenly started giving the error `The request url * is outside of Vite serving allow list` for multiple files, including dependencies installed as pnpm modules inside the **workspace** `node_modules` folder.\n\nThe only change had been to initialise my project as a git repository.\n\nI was expecting the dev server to keep working, and that changes to git would not have any effect.\n\nThe project still builds ok.\n\n========================================\n\nTop Answer:\nThe recommended method is to add it to the `server.fs.allow` list:\n\n```\nimport { defineConfig, searchForWorkspaceRoot } from 'vite'\n \nexport default defineConfig({\n server: {\n fs: {\n allow: [\n // search up for workspace root\n searchForWorkspaceRoot(process.cwd()),\n // your custom rules\n '/path/to/custom/allow',\n ],\n },\n },\n})\n```\n\n========================================\n\nCode:\n```text\nThe request url * is outside of Vite serving allow list\n```\n\n```text\nnode_modules\n```\n\n```js\nexport default defineNuxtConfig({\n    vite: {\n        server: {\n            fs: {\n                allow: [\"/home/user/Monorepo\"]\n            }\n        }\n    }\n})\n```\n\n```text\nnode_modules\n```\n\n```js\nimport { defineConfig, searchForWorkspaceRoot } from 'vite'\n  \nexport default defineConfig({\n  server: {\n    fs: {\n      allow: [\n        // search up for workspace root\n        searchForWorkspaceRoot(process.cwd()),\n        // your custom rules\n        '/path/to/custom/allow',\n      ],\n    },\n  },\n})\n```\n\n```text\nserver.fs.allow\n```\n\n```text\nserver: {\n  fs: {\n    // Allow serving files from one level up to the project root\n    allow: ['..'],\n  },\n},\n```\n\n```text\nviteConf.server = {\n          ...viteConf.server,\n          fs: {\n            strict: false // Disable strict file serving restrictions\n          }\n        };\n```\n\n```text\nnpm run build\n```\n\n========================================\n\nComments:\n- Related (unanwsered) questions: stackoverflow.com/questions/74326498/&hellip;, stackoverflow.com/questions/74264304/&hellip;\n- Works nice with absolute paths, but couldn't figure out how to make it work with relative paths (better in teams).\n- I tried this: stackoverflow.com/a/72327029/5935615 but the only thing that worked (but it feels a little bit dirty) is, instead of setting vite.server.fs.allow as you did, setting vite.server.fs.strict to false.\n- stackoverflow.com/questions/71113423/&hellip;\n- I've tried this solution with my own user path to the project, but still getting \"Failed to load url\" and \"The request url...is outside of Vite serving allow list\" errors. I'm not using pnpm workspace. My Node version is v18.15.0. Nuxt 3.3.3. My Nuxt app also worked fine before initializing as git repository. Now the app is constantly trying to load (browser tab spinning) and does not hot-reload. Is there something I'm missing? Any help appreciated!\n- @Anelec It's hard to say without knowing what you *are* using, npm workspace? You might also be able to output the result of `searchForWorkspaceRoot` to help with debugging and compare this to where your node_modules are in your setup. If that's not enough to resolve the issue then I'd suggest asking your own question and linking it to this one, then you can explain properly what your setup is and how/why this solution isn't working for you. hth\n- @a2k42 thanks for your response! i'm new to nuxt and don't know how to do the `searchForWorkspaceRoot` function...but yes I'm using an npm workspace and here's a repo of the test project in which i'm getting the errors. i'm happy to create a new question too, if this is too much for comments\n- @anelec the path you've used in the allow array looks suspect to me\n- @a2k42 wow. i added a few more lines to the code. including a path to the local project and a path to the global \"node_modules\" folder on the system – with and without the asterisk to include all folders within....that seemed to do the trick. thanks so much for your help. you have no idea how long this took me and i don't know why it didn't work before.\n- I know it's recommended in the docs, but I wonder if `searchForWorkspaceRoot(process.cwd())` is really necessary. Maybe you can just use `'.'` if `vite.config.js` is run from your project root folder already.\n- While securing your back end is a common focus, there's two problems with this comment: (1) This is actually securing the \"back-end\" (file system) of your development machine — without this random users on your network may be able to read ANY file on your machine = not good! (2) Front end security *IS* actually a big deal, and if you ignore it, attackers may be able to steal cookies, session tokens, users' location data, localStorage data, gain admin rights to your app, and inject all sorts of nasty content that attacks you or your users.","metadata":{"transformedAt":"2026-08-18T18:33:46.410Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":121,"estimatedTokens":1270}}221{"id":"stack-74028448","source":"stackoverflow","questionId":74028448,"title":"vite Internal server error: Codegen node is missing for element/if/for node. Apply appropriate transforms first","tags":["vue.js","vite"],"text":"Title: vite Internal server error: Codegen node is missing for element/if/for node. Apply appropriate transforms first\nTags: vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nso yesterday i was working on a project and by the time i was about to quit because i was done with it i got this error and have been trying to fix it the entire day today. My code worked, then broke, undid everything to a point where i knew it worked, but it was still broken.\n\nThe error i get in my browserConsole is :\n`GET http://localhost:8080/src/js/component/App.vue net::ERR_ABORTED 500 (Internal Server Error) (main.js:5)`\n\nwhen i look at main.js line 5 there is only an import for App. i have not touched main.js, App.vue and AppTemplate.vue since the beginning of the project sinse i did not have to.\n\nTo run my code i use run vite in the terminal (or in my case a shortcut for the run window in phpstorm) there i get another error:\n\n```\nCannot read properties of undefined (reading 'type')\nCannot read properties of undefined (reading 'type') (x2)\nCannot read properties of undefined (reading 'type') (x3)\nCannot read properties of undefined (reading 'type') (x4)\nCannot read properties of undefined (reading 'type') (x5)\nCannot read properties of undefined (reading 'type') (x6)\nCannot read properties of undefined (reading 'type') (x7)\nCannot read properties of undefined (reading 'type') (x8)\nCannot read properties of undefined (reading 'type') (x9)\nCannot read properties of undefined (reading 'type') (x10)\n1:40:13 PM [vite] Internal server error: Codegen node is missing for element/if/for node. Apply appropriate transforms first.\n Plugin: vite:vue\n File: /Users/robdewilligen/Development/Wittig/jobse/app/src/js/component/App.vue\n at assert (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js:508:15)\n at genNode (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js:2628:13)\n at genNodeList (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js:2602:13)\n at genNodeListAsArray (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js:2587:5)\n at genNodeList (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js:2599:13)\n at genVNodeCall (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js:2770:5)\n at genNode (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js:2651:13)\n at generate (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js:2412:9)\n at Object.baseCompile (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js:5690:12)\n at Object.compile (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-dom/dist/compiler-dom.cjs.js:3100:25) ```\n\nthis bit repeats another 6 or 7 times or so:\n``` Cannot read properties of undefined (reading 'type')\nCannot read properties of undefined (reading 'type') (x2)\nCannot read properties of undefined (reading 'type') (x3)\nCannot read properties of undefined (reading 'type') (x4)\nCannot read properties of undefined (reading 'type') (x5)\nCodegen node is missing for element/if/for node. Apply appropriate transforms first.\nCodegen node is missing for element/if/for node. Apply appropriate transforms first. (x2)\n```\n\nSo far i have tried anything i could find or think of,\n\nbeginning with restarting vite,\nrestarting docker container,\nrestarting my laptop,\nlike i said before, revert to a working version but still broken.\nupdating terminal dev tools and a few things git was complaining about.\ncheck for wrong placed tags. (none were wrongplaced)\n\ni have no clue what to do anymore and any and all suggestions are very much welcome.\nAny info requested i will do my best to soon.\n\nI have a macbook pro 2020\nuse Vue 3 with Vite\na few library's i use are:\nvue-class-components\naxios\nvue-router\nvueX\n\n========================================\n\nTop Answer:\nVery late but just in case anyone else has the same issue.\n\nThis also happens when trying to use a named slot without using a default slot, or trying to use a single named slot instead of using the default one.\nApparently, that is not possible.\n\nIf you have a single slot in your component, it cannot be a named slot but just `` and also remove the `` tag from the parent, or nothing will show.\n\nIf you have more slots, you have to name them but make sure to declare the default one.\n\nVue CLI never complained, but after switching to Vite the error started to appear.\n\n========================================\n\nCode:\n```text\nCannot read properties of undefined (reading 'type')\nCannot read properties of undefined (reading 'type') (x2)\nCannot read properties of undefined (reading 'type') (x3)\nCannot read properties of undefined (reading 'type') (x4)\nCannot read properties of undefined (reading 'type') (x5)\nCannot read properties of undefined (reading 'type') (x6)\nCannot read properties of undefined (reading 'type') (x7)\nCannot read properties of undefined (reading 'type') (x8)\nCannot read properties of undefined (reading 'type') (x9)\nCannot read properties of undefined (reading 'type') (x10)\n1:40:13 PM [vite] Internal server error: Codegen node is missing for element/if/for node. Apply appropriate transforms first.\n  Plugin: vite:vue\n  File: /Users/robdewilligen/Development/Wittig/jobse/app/src/js/component/App.vue\n      at assert (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js:508:15)\n      at genNode (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js:2628:13)\n      at genNodeList (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js:2602:13)\n      at genNodeListAsArray (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js:2587:5)\n      at genNodeList (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js:2599:13)\n      at genVNodeCall (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js:2770:5)\n      at genNode (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js:2651:13)\n      at generate (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js:2412:9)\n      at Object.baseCompile (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js:5690:12)\n      at Object.compile (/Users/robdewilligen/Development/Wittig/jobse/app/node_modules/@vue/compiler-dom/dist/compiler-dom.cjs.js:3100:25) ```\n\nthis bit repeats another 6 or 7 times or so:\n``` Cannot read properties of undefined (reading 'type')\nCannot read properties of undefined (reading 'type') (x2)\nCannot read properties of undefined (reading 'type') (x3)\nCannot read properties of undefined (reading 'type') (x4)\nCannot read properties of undefined (reading 'type') (x5)\nCodegen node is missing for element/if/for node. Apply appropriate transforms first.\nCodegen node is missing for element/if/for node. Apply appropriate transforms first. (x2)\n```\n\n```text\nGET http://localhost:8080/src/js/component/App.vue net::ERR_ABORTED 500 (Internal Server Error) (main.js:5)\n```\n\n```html\n<template>\n    <AppShell>\n        <template v-slot:header>\n            <template v-slot:home>Home</template>\n            <RouterLink to=\"/media\">Media</RouterLink>\n        </template>\n    </AppShell>\n</template>\n```\n\n```html\n<template>\n    <AppShell>\n        <template v-slot:header>\n            <NavBar>\n                <template v-slot:home>Home</template>\n                <RouterLink to=\"/media\">Media</RouterLink>\n            </NavBar>\n        </template>\n    </AppShell>\n</template>\n```\n\n```text\nNavBar\n```\n\n```text\n<slot></slot>\n```\n\n```text\n<template #slot-name>\n```\n\n```text\nParentComponent.Vue\n\n\n<template #content>\n    <p>Some Content</p>\n    <SomeComponent></SomeComponent>\n</template>\n```\n\n```text\n<template slot=\"trigger\">\n<slot name=\"trigger\" v-bind=\"{ show }\"></slot>\n</template>\n```\n\n```text\n<template #trigger>\n<slot name=\"trigger\" v-bind=\"{ show }\"></slot>\n</template>\n```\n\n```text\n// Base Component\n<template>\n  <div>\n    Hello I am the BaseComponent\n    <slot :someMethod=\"...\"></slot>\n  </div>\n</template>\n\n// Using the Base Component - Correct Usage\n<BaseComponent v-slot=\"{someMethod}\">\n  <AnotherComponent></AnotherComponent>\n</BaseComponent>\n\n// But with even a single named slot, this will fail\n<BaseComponent v-slot=\"{someMethod}\">\n  <slot #myNamedSlot>\n    <AnotherComponent></AnotherComponent>\n  </slot>\n</BaseComponent>\n\n// This is Correct.\n<BaseComponent>\n  <slot #myNamedSlot v-slot=\"{someMethod}\">\n    <AnotherComponent></AnotherComponent>\n  </slot>\n</BaseComponent>\n```\n\n```text\n// Base Component with 2 named slots\n<template>\n  <div>\n    Hello I am the BaseComponent\n    <slot name='slot1' :someMethod=\"...\"></slot>\n    <slot name='slot2' :someMethod=\"...\"></slot>\n  </div>\n</template>\n\n// Incorrect Usage.\n<BaseComponent>\n  <slot #slot1 v-slot=\"{someMethod}\">\n    <AnotherComponent></AnotherComponent>\n    <slot #slot2 v-slot=\"{someMethod}\">\n      <AnotherComponent></AnotherComponent>\n    </slot>\n  </slot>\n</BaseComponent>\n\n// Correct Usage\n<BaseComponent>\n  <slot #slot1 v-slot=\"{someMethod}\">\n    <AnotherComponent></AnotherComponent>\n  </slot>\n  <slot #slot2 v-slot=\"{someMethod}\">\n    <AnotherComponent></AnotherComponent>\n  </slot>\n</BaseComponent>\n```\n\n```text\n<sl-dialog v-if=\"popup\">\n  <sl-button\n    slot=\"footer\"\n    variant=\"primary\"\n  >Close</sl-button>\n</sl-dialog>\n```\n\n```text\n<sl-dialog v-if=\"popup\">\n  <template #footer>\n    <sl-button\n\n      variant=\"primary\"\n    >Close</sl-button>\n  </template>\n</sl-dialog>\n```\n\n```text\n{\n    rules: {\n        \"vue/no-deprecated-slot-attribute\": [ \"error\", {\n            ignore: [\n                \"sl-button\",\n                \"sl-icon\",\n                ...\n            ]\n        } ]\n    }\n}\n```\n\n```text\nignore option\n```\n\n========================================\n\nComments:\n- this is not a \"question\", you should reword the title to increase the likelihood of getting a response.\n- This question isn't really answerable without a minimal reproducible example of the code or environment causing the problem.\n- I had this weird bug when i tried to wrap the `slot content` that is passed to `tippy-js` component inside a single `div` element using `vue`\n- This answer doesn't get to the root of the problem\n- \"Trying to put a template in a template\". Thanks. That part helped. Although I had actual elements in between, it still threw.\n- The same thing happened to me. I wasn't aware about it , thanks a million","metadata":{"transformedAt":"2026-08-18T18:33:46.410Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":290,"estimatedTokens":2769}}222{"id":"stack-74731469","source":"stackoverflow","questionId":74731469,"title":"Laravel VueJs Vite: Failed to parse source for import analysis because the content contains invalid JS syntax. Install @vitejs/plugin-vue to handle?","tags":["laravel","vue.js","vuejs3","vite"],"text":"Title: Laravel VueJs Vite: Failed to parse source for import analysis because the content contains invalid JS syntax. Install @vitejs/plugin-vue to handle?\nTags: laravel, vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI'm using `vite`in my `laravel` project but when I run `npm run build` shows me errors in the syntax and the syntax sounds correct.\n\n**- my component**\nhttps://i.sstatic.net/u0BuJ.png\n\n**- my vite.config.js**\nhttps://i.sstatic.net/8dJnX.png\n\n**- the error that I see**\nhttps://i.sstatic.net/7UYeL.png\n\n**larave ^9.19**\n\n**vue ^3.2.30**\n\n**vite ^3.0.0**\n\nhow I can fix that?\nand thanks in advance.\n\n========================================\n\nCode:\n```text\nvite\n```\n\n```text\nlaravel\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm i @vitejs/plugin-vue\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\"; //add this line\nimport laravel from \"laravel-vite-plugin\";\n\nexport default defineConfig({\n    plugins: [\n        vue(), // write this\n        laravel({\n            input: [\"resources/css/app.css\", \"resources/js/app.js\"],\n            refresh: true,\n        }),\n    ],\n});\n```\n\n```text\nnpm run dev\n```\n\n========================================\n\nComments:\n- Well you have a syntax error, but without code we can't say much\n- ok, I modified the content now\n- You don't call/use the vue plugin, so vue files do not work, you should add vue() in the plugins array\n- yes right, but when I add it I see the error in the production as I say in the first\n- try to import defineComponent from vue\n- It works. But... is this supposed to be done this way? inertiajs.com should do a better job in documentation. It is confusing for us.\n- I am glad it works for you. Hope inertia might update as well.\n- Thank you, def can be frustrating tracking this stuff down. Inertia should def try to include this in the docs.\n- While the error is self explanatory, (@ the time of writing) this small config is still not part of the Inertia docs in the client-side installation part\n- How many upvotes should these comment take, so that Inertia decide to fix their documentations??? It's been a long time this issue is not fixed!!!\n- In my case I also needed to run 'npm i vue' as well","metadata":{"transformedAt":"2026-08-18T18:33:46.410Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":78,"estimatedTokens":555}}223{"id":"stack-65858930","source":"stackoverflow","questionId":65858930,"title":"'does not provide an export named 'createRouter'' vue 3, vite and vue-router","tags":["vue.js","vue-router","vuejs3","vue-router4","vite"],"text":"Title: 'does not provide an export named 'createRouter'' vue 3, vite and vue-router\nTags: vue.js, vue-router, vuejs3, vue-router4, vite\nSource: Stack Overflow\n\nQuestion:\nI just started using vite with vue.\n\nWhen I'm trying to use vue-router I get the error:\n\nSyntaxError: The requested module '/node_modules/.vite/vue-router/dist/vue-router.esm.js?v=4830dca4' does not provide an export named 'createRouter\n\nMy router/index.js looks like this:\n\n```\nimport {\n createWebHistory,\n createRouter\n} from \"vue-router\";\n\nimport Services from \"../views/Services.vue\";\nimport Customers from \"../views/Customers.vue\";\n\nconst history = createWebHistory();\nconst routes = [\n {\n path: \"/\",\n component: Services\n },\n {\n path: \"/customers\",\n component: Customers\n },\n];\nconst router = createRouter({\n history,\n routes\n});\nexport default router;\n```\n\nMy main.js looks like this:\n\n```\nimport { createApp } from 'vue'\nimport App from './App.vue'\nimport './index.css'\nimport router from './router'\n\ncreateApp(App).use(router).mount('#app')\n```\n\nMy package.json looks like this:\n\n```\n{\n \"name\": \"frontend\",\n \"version\": \"0.0.0\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\"\n},\n \"dependencies\": {\n \"vue\": \"^3.0.5\",\n \"vue-router\": \"^3.4.9\"\n},\n \"devDependencies\": {\n \"@vitejs/plugin-vue\": \"^1.0.4\",\n \"@vue/compiler-sfc\": \"^3.0.5\",\n \"autoprefixer\": \"^10.2.3\",\n \"postcss\": \"^8.2.4\",\n \"tailwindcss\": \"^2.0.2\",\n \"vite\": \"^2.0.0-beta.12\"\n }\n}\n```\n\nAnyone knows how to export the route?\n\n========================================\n\nTop Answer:\nif you check inside the file `'/node_modules/.vite/vue-router/dist/vue-router.esm.js?v=4830dca4'`\n\nthere is no `export default` syntax. only named `export {}`\n\nso instead import default, use named import.\n\n```\n// don't\nimport VueRouter from 'vue-router'\n\n// do\nimport { createRouter, createWebHashHistory } from 'vue-router'\n```\n\n========================================\n\nCode:\n```text\nimport {\n createWebHistory,\n createRouter\n} from \"vue-router\";\n\nimport Services from \"../views/Services.vue\";\nimport Customers from \"../views/Customers.vue\";\n\nconst history = createWebHistory();\nconst routes = [\n  {\n    path: \"/\",\n    component: Services\n  },\n  {\n    path: \"/customers\",\n    component: Customers\n  },\n];\nconst router = createRouter({\n  history,\n  routes\n});\nexport default router;\n```\n\n```text\nimport { createApp } from 'vue'\nimport App from './App.vue'\nimport './index.css'\nimport router from './router'\n\ncreateApp(App).use(router).mount('#app')\n```\n\n```text\n{\n \"name\": \"frontend\",\n \"version\": \"0.0.0\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\"\n},\n \"dependencies\": {\n \"vue\": \"^3.0.5\",\n \"vue-router\": \"^3.4.9\"\n},\n \"devDependencies\": {\n \"@vitejs/plugin-vue\": \"^1.0.4\",\n \"@vue/compiler-sfc\": \"^3.0.5\",\n \"autoprefixer\": \"^10.2.3\",\n \"postcss\": \"^8.2.4\",\n \"tailwindcss\": \"^2.0.2\",\n \"vite\": \"^2.0.0-beta.12\"\n }\n}\n```\n\n```text\nnpm uninstall vue-router\n```\n\n```text\nnpm install vue-router@next -S\n```\n\n```text\nvue-router\n```\n\n```js\n// don't\nimport VueRouter from 'vue-router'\n\n// do\nimport { createRouter, createWebHashHistory } from 'vue-router'\n```\n\n```text\n'/node_modules/.vite/vue-router/dist/vue-router.esm.js?v=4830dca4'\n```\n\n```text\nexport default\n```\n\n```text\nexport {}\n```\n\n```text\n// if this does not work\nimport VueRouter from 'vue-router'\n\n// try this\nimport * as VueRouter from 'vue-router';\n```\n\n```text\nunderscore\n```\n\n```text\nlodash\n```\n\n```text\nimport VueRouter from 'vue-router';\n```\n\n```text\nimport * as VueRouter from 'vue-router';\n```\n\n```text\nimport { createRouter, createWebHashHistory } from 'vue-router'\n```\n\n========================================\n\nComments:\n- Use `import VueRouter from \"vue-router\"` and when defining use `const router = new VueRouter({ your code})`\n- @YashMaheshwari this syntax is for vue 2 with vue router 3\n- no worries, you could get that when you see that he's using vite which works only with vue 3\n- The new portal: next.router.vuejs.org/installation.html\n- `4.0.6` worked fine for me with `vue@^3.0.5`\n- NOTE: If you're running Vite you'll have to shut it down and restart it before this change takes effect. This did solve my problem.\n- @Roga do you mean quitting server and restarting again ?\n- Me too. I have `vue-router@4` and doing it with `yarn`. From your comment, I tried just deleting `node_modules` and reinstalling with `yarn` again and worked!\n- This is the answer if you're referencing: router.vuejs.org/guide/#javascript\n- I had this issue in `App.vue` and this answer solve my issue.\n- This solves the issue but now it says `VueRouter is not defined`","metadata":{"transformedAt":"2026-08-18T18:33:46.410Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":231,"estimatedTokens":1137}}224{"id":"stack-69286329","source":"stackoverflow","questionId":69286329,"title":"Polyfill node os module with vite/rollup.js","tags":["node.js","vue.js","rollupjs","vite"],"text":"Title: Polyfill node os module with vite/rollup.js\nTags: node.js, vue.js, rollupjs, vite\nSource: Stack Overflow\n\nQuestion:\nI'm working on a Vite project which uses the `opensea-js` package. This package depends on `xhr2-cookies`. which imports `os`, `http`, `https` and some other internal node modules.\n\nI'm getting this error when trying to call any of the opensea methods:\n\n```\nUncaught (in promise) TypeError: os.type is not a function\n XMLHttpRequest2 xml-http-request.ts:102\n prepareRequest httpprovider.js:61\n sendAsync httpprovider.js:116\n node_modules opensea-js.js:24209\n```\n\nTracing this error it comes from constructing the useragent string.\n\nI tried installing `rollup-plugin-polyfill-node` and adding it to `vite.config.js` but still getting the same error:\n\n```\nimport path from 'path'\nimport vue from '@vitejs/plugin-vue'\nimport nodePolyfills from 'rollup-plugin-polyfill-node'\nimport { defineConfig } from 'vite'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [vue()],\n resolve: {\n alias: {\n '@': path.resolve(__dirname, 'src'),\n },\n },\n server: {\n port: 8080,\n },\n define: {\n 'process.env': {},\n },\n build: {\n rollupOptions: {\n plugins: [\n nodePolyfills(),\n ],\n },\n },\n})\n```\n\nI've also tried patching the file manually with `patch-package`, which fixes the `os` error however then fails when trying to sending the request (which uses `http`/`https` modules which also need to be polyfilled).\n\n========================================\n\nTop Answer:\nI used `rollup-plugin-polyfill-node` to fix the issue.\n\n```\nimport nodePolyfills from 'rollup-plugin-polyfill-node';\nrollup({\n entry: 'main.js',\n plugins: [\n nodePolyfills( /* options */ )\n ]\n})\n```\n\nHere is a more complete answer based on Fabiano's answer:\n\n```\n// yarn add --dev @esbuild-plugins/node-globals-polyfill\nimport { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'\n// yarn add --dev @esbuild-plugins/node-modules-polyfill\nimport { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill'\nimport nodePolyfills from 'rollup-plugin-polyfill-node';\n\nexport default {\n optimizeDeps: {\n esbuildOptions: {\n // Node.js global to browser globalThis\n define: {\n global: 'globalThis'\n },\n // Enable esbuild polyfill plugins\n plugins: [\n NodeGlobalsPolyfillPlugin({\n process: true,\n buffer: true\n }),\n NodeModulesPolyfillPlugin()\n ]\n }\n },\n build: {\n rollupOptions: {\n plugins: [\n // Enable rollup polyfills plugin\n // used during production bundling\n nodePolyfills()\n ]\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nUncaught (in promise) TypeError: os.type is not a function\n    XMLHttpRequest2 xml-http-request.ts:102\n    prepareRequest httpprovider.js:61\n    sendAsync httpprovider.js:116\n    node_modules opensea-js.js:24209\n```\n\n```text\nimport path from 'path'\nimport vue from '@vitejs/plugin-vue'\nimport nodePolyfills from 'rollup-plugin-polyfill-node'\nimport { defineConfig } from 'vite'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue()],\n  resolve: {\n    alias: {\n      '@': path.resolve(__dirname, 'src'),\n    },\n  },\n  server: {\n    port: 8080,\n  },\n  define: {\n    'process.env': {},\n  },\n  build: {\n    rollupOptions: {\n      plugins: [\n        nodePolyfills(),\n      ],\n    },\n  },\n})\n```\n\n```text\nopensea-js\n```\n\n```text\nxhr2-cookies\n```\n\n```text\nos\n```\n\n```text\nhttp\n```\n\n```text\nhttps\n```\n\n```text\nrollup-plugin-polyfill-node\n```\n\n```text\nvite.config.js\n```\n\n```text\npatch-package\n```\n\n```text\nos\n```\n\n```text\nhttp\n```\n\n```text\nhttps\n```\n\n```text\n// yarn add --dev @esbuild-plugins/node-globals-polyfill\nimport { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'\n// yarn add --dev @esbuild-plugins/node-modules-polyfill\nimport { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill'\n// You don't need to add this to deps, it's included by @esbuild-plugins/node-modules-polyfill\nimport rollupNodePolyFill from 'rollup-plugin-node-polyfills'\n\nexport default {\n        resolve: {\n            alias: {\n                // This Rollup aliases are extracted from @esbuild-plugins/node-modules-polyfill, \n                // see https://github.com/remorses/esbuild-plugins/blob/master/node-modules-polyfill/src/polyfills.ts\n                // process and buffer are excluded because already managed\n                // by node-globals-polyfill\n                util: 'rollup-plugin-node-polyfills/polyfills/util',\n                sys: 'util',\n                events: 'rollup-plugin-node-polyfills/polyfills/events',\n                stream: 'rollup-plugin-node-polyfills/polyfills/stream',\n                path: 'rollup-plugin-node-polyfills/polyfills/path',\n                querystring: 'rollup-plugin-node-polyfills/polyfills/qs',\n                punycode: 'rollup-plugin-node-polyfills/polyfills/punycode',\n                url: 'rollup-plugin-node-polyfills/polyfills/url',\n                string_decoder:\n                    'rollup-plugin-node-polyfills/polyfills/string-decoder',\n                http: 'rollup-plugin-node-polyfills/polyfills/http',\n                https: 'rollup-plugin-node-polyfills/polyfills/http',\n                os: 'rollup-plugin-node-polyfills/polyfills/os',\n                assert: 'rollup-plugin-node-polyfills/polyfills/assert',\n                constants: 'rollup-plugin-node-polyfills/polyfills/constants',\n                _stream_duplex:\n                    'rollup-plugin-node-polyfills/polyfills/readable-stream/duplex',\n                _stream_passthrough:\n                    'rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough',\n                _stream_readable:\n                    'rollup-plugin-node-polyfills/polyfills/readable-stream/readable',\n                _stream_writable:\n                    'rollup-plugin-node-polyfills/polyfills/readable-stream/writable',\n                _stream_transform:\n                    'rollup-plugin-node-polyfills/polyfills/readable-stream/transform',\n                timers: 'rollup-plugin-node-polyfills/polyfills/timers',\n                console: 'rollup-plugin-node-polyfills/polyfills/console',\n                vm: 'rollup-plugin-node-polyfills/polyfills/vm',\n                zlib: 'rollup-plugin-node-polyfills/polyfills/zlib',\n                tty: 'rollup-plugin-node-polyfills/polyfills/tty',\n                domain: 'rollup-plugin-node-polyfills/polyfills/domain'\n            }\n        },\n        optimizeDeps: {\n            esbuildOptions: {\n                // Node.js global to browser globalThis\n                define: {\n                    global: 'globalThis'\n                },\n                // Enable esbuild polyfill plugins\n                plugins: [\n                    NodeGlobalsPolyfillPlugin({\n                        process: true,\n                        buffer: true\n                    }),\n                    NodeModulesPolyfillPlugin()\n                ]\n            }\n        },\n        build: {\n            rollupOptions: {\n                plugins: [\n                    // Enable rollup polyfills plugin\n                    // used during production bundling\n                    rollupNodePolyFill()\n                ]\n            }\n        }\n}\n```\n\n```text\nimport nodePolyfills from 'rollup-plugin-polyfill-node';\nrollup({\n  entry: 'main.js',\n  plugins: [\n    nodePolyfills( /* options */ )\n  ]\n})\n```\n\n```text\n// yarn add --dev @esbuild-plugins/node-globals-polyfill\nimport { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'\n// yarn add --dev @esbuild-plugins/node-modules-polyfill\nimport { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill'\nimport nodePolyfills from 'rollup-plugin-polyfill-node';\n\nexport default {\n        optimizeDeps: {\n            esbuildOptions: {\n                // Node.js global to browser globalThis\n                define: {\n                    global: 'globalThis'\n                },\n                // Enable esbuild polyfill plugins\n                plugins: [\n                    NodeGlobalsPolyfillPlugin({\n                        process: true,\n                        buffer: true\n                    }),\n                    NodeModulesPolyfillPlugin()\n                ]\n            }\n        },\n        build: {\n            rollupOptions: {\n                plugins: [\n                    // Enable rollup polyfills plugin\n                    // used during production bundling\n                    nodePolyfills()\n                ]\n            }\n        }\n}\n```\n\n```text\nrollup-plugin-polyfill-node\n```\n\n```js\n// https://vitejs.dev/config/\nimport { defineConfig } from \"vite\";\nimport { NodeGlobalsPolyfillPlugin } from \"@esbuild-plugins/node-globals-polyfill\";\nimport nodePolyfills from \"rollup-plugin-node-polyfills\";\nimport { svelte } from \"@sveltejs/vite-plugin-svelte\";\n\n// Config is based on metaplex + vite example from:\n// https://github.com/metaplex-foundation/js-examples/tree/main/getting-started-vite\n\n// es2020 Needed for BigNumbers\n// See https://github.com/sveltejs/kit/issues/859\n\nexport default defineConfig({\n  plugins: [svelte()],\n  resolve: {\n    alias: {\n      stream: \"rollup-plugin-node-polyfills/polyfills/stream\",\n      events: \"rollup-plugin-node-polyfills/polyfills/events\",\n      assert: \"assert\",\n      crypto: \"crypto-browserify\",\n      util: \"util\",\n    },\n  },\n  define: {\n    \"process.env\": process.env ?? {},\n  },\n  build: {\n    target: \"es2020\",\n    rollupOptions: {\n      plugins: [nodePolyfills({ crypto: true })],\n    },\n  },\n  optimizeDeps: {\n    esbuildOptions: {\n      plugins: [NodeGlobalsPolyfillPlugin({ buffer: true })],\n      target: \"es2020\",\n    },\n  },\n});\n```\n\n```js\nimport { defineConfig } from \"vite\";\nimport { NgmiPolyfill } from \"vite-plugin-ngmi-polyfill\";\n\nexport default defineConfig({\n  plugins: [NgmiPolyfill()],\n});\n```\n\n```js\nimport { builtinModules } from 'module';\n\nconst allExternal = [\n    ...builtinModules,\n    ...builtinModules.map((m) => `node:${m}`)\n]\n\n// add the following to your config object\n\nreturn {\n    build: {\n            rollupOptions: {\n                external: ...allExternal\n            }\n    }\n}\n```\n\n```text\n\"resolve\" is not exported by \"__vite-browser-external\", imported by \"../../node_modules/some_module/index.mjs\".\n\n...\n\nfile: /home/user/project/node_modules/some_module/index.mjs:1:18\n\n1: import { dirname, resolve } from 'path';\n```\n\n========================================\n\nComments:\n- maybe you should add the polyfills to your plugins like `plugins: [vue(), nodePolyfills()]`\n- Note - if these solutions end up importing `Buffer` twice, **there's currently an outstanding issue with Vite** github.com/vitejs/vite/issues/7384\n- I had to add `buffer: 'rollup-plugin-node-polyfills&#47;polyfills&#47;buffer-es6',` to the `alias` object in order to get my build to compile for production.\n- @JiFus in my project adding it breaks the build, need to investigate better.\n- @FabianoTaioli Did you find out why?\n- indeed, the `buffer` alias is needed for me too, and the `process` was also needed for me: `buffer: 'rollup-plugin-node-polyfills&#47;polyfills&#47;buffer-es6', process: 'rollup-plugin-node-polyfills&#47;polyfills&#47;process-es6'`\n- It looks like there's a dir missing in your `alias` setup. `Could not read from file: &#47;home&#47;mike&#47;Code&#47;myproject&#47;rollup-plugin-node-polyfills&#47;polyf&zwnj;&#8203;ills&#47;string-decoder`\n- Didn't work for me, I got: `No matching export in \"node-modules-polyfills:util\" for import \"types\"`\n- any idea why am I getting the following `@esbuild-plugins&#47;node-globals-polyfill&#47;_buffer.js\" cannot be marked as external`?\n- Looks like esbuild bug, see: github.com/remorses/esbuild-plugins/issues/&hellip;\n- This actually worked for me. I also had to add the buffer property as indicated by @jifus\n- This was probably the easier config, and it also worked for me!\n- This should be the best answer with the latest Vite version (5 and mjs configuration). Thanks\n- Worked perfectly for me in my Nuxt config, with 1 change: I removed the ... in front of allExternal. I'm working with a nuxt.config.ts file, so my config block looked like this: vite: { build: { rollupOptions: { external: allExternal } } }","metadata":{"transformedAt":"2026-08-18T18:33:46.410Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":414,"estimatedTokens":3052}}225{"id":"stack-70594844","source":"stackoverflow","questionId":70594844,"title":"NPM warning: 'unsupported engine'","tags":["node.js","npm","vite"],"text":"Title: NPM warning: 'unsupported engine'\nTags: node.js, npm, vite\nSource: Stack Overflow\n\nQuestion:\nI entered the command `npm install -D tailwind css postcss autoprefixer vite` in VS-Code.\n\nMy environment is:\n\n- NPM version: `8.1.2`\n\n- Node.js version: `16.13.1`\n\nWhich resulted in following warning:\n\n```\nnpm WARN idealTree Removing dependencies.vite in favor of devDependencies.vite\nnpm WARN EBADENGINE Unsupported engine { \nnpm WARN EBADENGINE package: 'amqplib@0.5.2', \nnpm WARN EBADENGINE required: { node: '>=0.8 My package.json is:\n\n```\n{\n \"name\": \"tailwind-css-part-7\",\n \"version\": \"1.0.0\",\n \"main\": \"index.js\",\n \"devDependencies\": {\n \"autoprefixer\": \"^10.4.2\",\n \"css\": \"^3.0.0\",\n \"postcss\": \"^8.4.5\",\n \"tailwind\": \"^4.0.0\",\n \"vite\": \"^2.7.10\"\n },\n \"scripts\": {\n \"start\": \"vite\"\n },\n \"keywords\": [],\n \"author\": \"\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"accepts\": \"^1.3.7\",\n \"ajv\": \"^6.10.0\",\n \"amqplib\": \"^0.5.2\",\n \"ansi-styles\": \"^3.2.1\",\n \"app-root-path\": \"^2.1.0\",\n \"array-flatten\": \"^1.1.1\",\n \"asn1\": \"^0.2.3\",\n \"async-limiter\": \"^1.0.1\",\n \"async-retry\": \"^1.2.3\",\n \"atob\": \"^2.1.2\",\n \"babel-runtime\": \"^6.26.0\",\n \"basic-auth\": \"^2.0.1\",\n \"bitsyntax\": \"^0.0.4\",\n \"bluebird\": \"^3.7.2\",\n \"body-parser\": \"^1.18.3\",\n \"browserslist\": \"^4.19.1\",\n \"buffer-equal-constant-time\": \"^1.0.1\",\n \"buffer-more-ints\": \"^0.0.2\",\n \"bytes\": \"^3.0.0\",\n \"call-bind\": \"^1.0.2\",\n \"caniuse-lite\": \"^1.0.30001296\",\n \"chalk\": \"^2.4.1\",\n \"color-convert\": \"^1.9.3\",\n \"color-name\": \"^1.1.3\",\n \"commands-events\": \"^1.0.4\",\n \"comparejs\": \"^1.0.0\",\n \"compressible\": \"^2.0.18\",\n \"compression\": \"^1.7.3\",\n \"content-disposition\": \"^0.5.2\",\n \"content-type\": \"^1.0.4\",\n \"cookie\": \"^0.3.1\",\n \"cookie-signature\": \"^1.0.6\",\n \"core-js\": \"^2.6.12\",\n \"core-util-is\": \"^1.0.3\",\n \"cors\": \"^2.8.5\",\n \"crypto2\": \"^2.0.0\",\n \"datasette\": \"^1.0.1\",\n \"debug\": \"^2.6.9\",\n \"decode-uri-component\": \"^0.2.0\",\n \"define-properties\": \"^1.1.3\",\n \"depd\": \"^1.1.2\",\n \"destroy\": \"^1.0.4\",\n \"draht\": \"^1.0.1\",\n \"ecdsa-sig-formatter\": \"^1.0.11\",\n \"ee-first\": \"^1.1.1\",\n \"electron-to-chromium\": \"^1.4.35\",\n \"encodeurl\": \"^1.0.2\",\n \"es-abstract\": \"^1.19.1\",\n \"es-to-primitive\": \"^1.2.1\",\n \"esbuild\": \"^0.13.15\",\n \"esbuild-windows-64\": \"^0.13.15\",\n \"escalade\": \"^3.1.1\",\n \"escape-html\": \"^1.0.3\",\n \"escape-string-regexp\": \"^1.0.5\",\n \"etag\": \"^1.8.1\",\n \"eventemitter2\": \"^5.0.1\",\n \"express\": \"^4.16.4\",\n \"fast-deep-equal\": \"^2.0.1\",\n \"fast-json-stable-stringify\": \"^2.1.0\",\n \"finalhandler\": \"^1.1.1\",\n \"find-root\": \"^1.1.0\",\n \"flaschenpost\": \"^5.0.49\",\n \"formats\": \"^1.0.0\",\n \"forwarded\": \"^0.2.0\",\n \"fraction.js\": \"^4.1.2\",\n \"fresh\": \"^0.5.2\",\n \"function-bind\": \"^1.1.1\",\n \"get-intrinsic\": \"^1.1.1\",\n \"get-own-enumerable-property-symbols\": \"^3.0.2\",\n \"get-symbol-description\": \"^1.0.0\",\n \"has\": \"^1.0.3\",\n \"has-bigints\": \"^1.0.1\",\n \"has-flag\": \"^3.0.0\",\n \"has-symbols\": \"^1.0.2\",\n \"has-tostringtag\": \"^1.0.0\",\n \"hase\": \"^2.0.0\",\n \"http-errors\": \"^1.6.3\",\n \"iconv-lite\": \"^0.4.23\",\n \"inherits\": \"^2.0.4\",\n \"internal-slot\": \"^1.0.3\",\n \"ipaddr.js\": \"^1.9.1\",\n \"is-bigint\": \"^1.0.4\",\n \"is-boolean-object\": \"^1.1.2\",\n \"is-callable\": \"^1.2.4\",\n \"is-core-module\": \"^2.8.0\",\n \"is-date-object\": \"^1.0.5\",\n \"is-negative-zero\": \"^2.0.2\",\n \"is-number-object\": \"^1.0.6\",\n \"is-obj\": \"^1.0.1\",\n \"is-regex\": \"^1.1.4\",\n \"is-regexp\": \"^1.0.0\",\n \"is-shared-array-buffer\": \"^1.0.1\",\n \"is-string\": \"^1.0.7\",\n \"is-symbol\": \"^1.0.4\",\n \"is-weakref\": \"^1.0.2\",\n \"isarray\": \"^0.0.1\",\n \"json-lines\": \"^1.0.0\",\n \"json-schema-traverse\": \"^0.4.1\",\n \"jsonwebtoken\": \"^8.5.0\",\n \"jwa\": \"^1.4.1\",\n \"jws\": \"^3.2.2\",\n \"limes\": \"^2.0.0\",\n \"lodash\": \"^4.17.11\",\n \"lodash.includes\": \"^4.3.0\",\n \"lodash.isboolean\": \"^3.0.3\",\n \"lodash.isinteger\": \"^4.0.4\",\n \"lodash.isnumber\": \"^3.0.3\",\n \"lodash.isplainobject\": \"^4.0.6\",\n \"lodash.isstring\": \"^4.0.1\",\n \"lodash.once\": \"^4.1.1\",\n \"lusca\": \"^1.6.1\",\n \"media-typer\": \"^0.3.0\",\n \"merge-descriptors\": \"^1.0.1\",\n \"methods\": \"^1.1.2\",\n \"mime\": \"^1.4.1\",\n \"mime-db\": \"^1.51.0\",\n \"mime-types\": \"^2.1.34\",\n \"moment\": \"^2.22.2\",\n \"morgan\": \"^1.9.1\",\n \"ms\": \"^2.0.0\",\n \"nanoid\": \"^3.1.30\",\n \"negotiator\": \"^0.6.2\",\n \"nocache\": \"^2.0.0\",\n \"node-releases\": \"^2.0.1\",\n \"node-rsa\": \"^0.4.2\",\n \"node-statsd\": \"^0.1.1\",\n \"normalize-range\": \"^0.1.2\",\n \"object-assign\": \"^4.1.1\",\n \"object-inspect\": \"^1.12.0\",\n \"object-keys\": \"^1.1.1\",\n \"object.assign\": \"^4.1.2\",\n \"object.getownpropertydescriptors\": \"^2.1.3\",\n \"on-finished\": \"^2.3.0\",\n \"on-headers\": \"^1.0.2\",\n \"parseurl\": \"^1.3.3\",\n \"partof\": \"^1.0.0\",\n \"path-parse\": \"^1.0.7\",\n \"path-to-regexp\": \"^0.1.7\",\n \"picocolors\": \"^1.0.0\",\n \"postcss-value-parser\": \"^4.2.0\",\n \"processenv\": \"^1.1.0\",\n \"proxy-addr\": \"^2.0.7\",\n \"punycode\": \"^2.1.1\",\n \"qs\": \"^6.5.2\",\n \"range-parser\": \"^1.2.1\",\n \"raw-body\": \"^2.3.3\",\n \"readable-stream\": \"^1.1.14\",\n \"regenerator-runtime\": \"^0.12.1\",\n \"resolve\": \"^1.21.0\",\n \"retry\": \"^0.12.0\",\n \"rollup\": \"^2.63.0\",\n \"safe-buffer\": \"^5.1.2\",\n \"safer-buffer\": \"^2.1.2\",\n \"semver\": \"^5.7.1\",\n \"send\": \"^0.16.2\",\n \"serve-static\": \"^1.13.2\",\n \"setprototypeof\": \"^1.1.0\",\n \"sha-1\": \"^0.1.1\",\n \"side-channel\": \"^1.0.4\",\n \"source-map\": \"^0.6.1\",\n \"source-map-js\": \"^1.0.1\",\n \"source-map-resolve\": \"^0.6.0\",\n \"split2\": \"^3.0.0\",\n \"stack-trace\": \"^0.0.10\",\n \"statuses\": \"^1.4.0\",\n \"stethoskop\": \"^1.0.0\",\n \"string_decoder\": \"^0.10.31\",\n \"string.prototype.trimend\": \"^1.0.4\",\n \"string.prototype.trimstart\": \"^1.0.4\",\n \"stringify-object\": \"^3.3.0\",\n \"supports-color\": \"^5.5.0\",\n \"supports-preserve-symlinks-flag\": \"^1.0.0\",\n \"timer2\": \"^1.0.0\",\n \"tsscmp\": \"^1.0.6\",\n \"type-is\": \"^1.6.18\",\n \"unbox-primitive\": \"^1.0.1\",\n \"unpipe\": \"^1.0.0\",\n \"untildify\": \"^3.0.3\",\n \"uri-js\": \"^4.4.1\",\n \"util-deprecate\": \"^1.0.2\",\n \"util.promisify\": \"^1.0.0\",\n \"utils-merge\": \"^1.0.1\",\n \"uuid\": \"^3.3.2\",\n \"uuidv4\": \"^3.0.1\",\n \"varname\": \"^2.0.3\",\n \"vary\": \"^1.1.2\",\n \"which-boxed-primitive\": \"^1.0.2\",\n \"ws\": \"^6.2.0\"\n },\n \"description\": \"\"\n}\n```\n\n========================================\n\nTop Answer:\nIt also happened to me while I was trying to install `tailwindcss` and I installed `tailwind` by mistake. Just uninstall it if that's also your case.\n\n========================================\n\nCode:\n```text\nnpm WARN idealTree Removing dependencies.vite in favor of devDependencies.vite\nnpm WARN EBADENGINE Unsupported engine {    \nnpm WARN EBADENGINE   package: 'amqplib@0.5.2',    \nnpm WARN EBADENGINE   required: { node: '>=0.8 <=9' },\nnpm WARN EBADENGINE   current: { node: 'v16.13.1', npm: '8.1.2' }\nnpm WARN EBADENGINE }\n```\n\n```json\n{\n  \"name\": \"tailwind-css-part-7\",\n  \"version\": \"1.0.0\",\n  \"main\": \"index.js\",\n  \"devDependencies\": {\n    \"autoprefixer\": \"^10.4.2\",\n    \"css\": \"^3.0.0\",\n    \"postcss\": \"^8.4.5\",\n    \"tailwind\": \"^4.0.0\",\n    \"vite\": \"^2.7.10\"\n  },\n  \"scripts\": {\n    \"start\": \"vite\"\n  },\n  \"keywords\": [],\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"accepts\": \"^1.3.7\",\n    \"ajv\": \"^6.10.0\",\n    \"amqplib\": \"^0.5.2\",\n    \"ansi-styles\": \"^3.2.1\",\n    \"app-root-path\": \"^2.1.0\",\n    \"array-flatten\": \"^1.1.1\",\n    \"asn1\": \"^0.2.3\",\n    \"async-limiter\": \"^1.0.1\",\n    \"async-retry\": \"^1.2.3\",\n    \"atob\": \"^2.1.2\",\n    \"babel-runtime\": \"^6.26.0\",\n    \"basic-auth\": \"^2.0.1\",\n    \"bitsyntax\": \"^0.0.4\",\n    \"bluebird\": \"^3.7.2\",\n    \"body-parser\": \"^1.18.3\",\n    \"browserslist\": \"^4.19.1\",\n    \"buffer-equal-constant-time\": \"^1.0.1\",\n    \"buffer-more-ints\": \"^0.0.2\",\n    \"bytes\": \"^3.0.0\",\n    \"call-bind\": \"^1.0.2\",\n    \"caniuse-lite\": \"^1.0.30001296\",\n    \"chalk\": \"^2.4.1\",\n    \"color-convert\": \"^1.9.3\",\n    \"color-name\": \"^1.1.3\",\n    \"commands-events\": \"^1.0.4\",\n    \"comparejs\": \"^1.0.0\",\n    \"compressible\": \"^2.0.18\",\n    \"compression\": \"^1.7.3\",\n    \"content-disposition\": \"^0.5.2\",\n    \"content-type\": \"^1.0.4\",\n    \"cookie\": \"^0.3.1\",\n    \"cookie-signature\": \"^1.0.6\",\n    \"core-js\": \"^2.6.12\",\n    \"core-util-is\": \"^1.0.3\",\n    \"cors\": \"^2.8.5\",\n    \"crypto2\": \"^2.0.0\",\n    \"datasette\": \"^1.0.1\",\n    \"debug\": \"^2.6.9\",\n    \"decode-uri-component\": \"^0.2.0\",\n    \"define-properties\": \"^1.1.3\",\n    \"depd\": \"^1.1.2\",\n    \"destroy\": \"^1.0.4\",\n    \"draht\": \"^1.0.1\",\n    \"ecdsa-sig-formatter\": \"^1.0.11\",\n    \"ee-first\": \"^1.1.1\",\n    \"electron-to-chromium\": \"^1.4.35\",\n    \"encodeurl\": \"^1.0.2\",\n    \"es-abstract\": \"^1.19.1\",\n    \"es-to-primitive\": \"^1.2.1\",\n    \"esbuild\": \"^0.13.15\",\n    \"esbuild-windows-64\": \"^0.13.15\",\n    \"escalade\": \"^3.1.1\",\n    \"escape-html\": \"^1.0.3\",\n    \"escape-string-regexp\": \"^1.0.5\",\n    \"etag\": \"^1.8.1\",\n    \"eventemitter2\": \"^5.0.1\",\n    \"express\": \"^4.16.4\",\n    \"fast-deep-equal\": \"^2.0.1\",\n    \"fast-json-stable-stringify\": \"^2.1.0\",\n    \"finalhandler\": \"^1.1.1\",\n    \"find-root\": \"^1.1.0\",\n    \"flaschenpost\": \"^5.0.49\",\n    \"formats\": \"^1.0.0\",\n    \"forwarded\": \"^0.2.0\",\n    \"fraction.js\": \"^4.1.2\",\n    \"fresh\": \"^0.5.2\",\n    \"function-bind\": \"^1.1.1\",\n    \"get-intrinsic\": \"^1.1.1\",\n    \"get-own-enumerable-property-symbols\": \"^3.0.2\",\n    \"get-symbol-description\": \"^1.0.0\",\n    \"has\": \"^1.0.3\",\n    \"has-bigints\": \"^1.0.1\",\n    \"has-flag\": \"^3.0.0\",\n    \"has-symbols\": \"^1.0.2\",\n    \"has-tostringtag\": \"^1.0.0\",\n    \"hase\": \"^2.0.0\",\n    \"http-errors\": \"^1.6.3\",\n    \"iconv-lite\": \"^0.4.23\",\n    \"inherits\": \"^2.0.4\",\n    \"internal-slot\": \"^1.0.3\",\n    \"ipaddr.js\": \"^1.9.1\",\n    \"is-bigint\": \"^1.0.4\",\n    \"is-boolean-object\": \"^1.1.2\",\n    \"is-callable\": \"^1.2.4\",\n    \"is-core-module\": \"^2.8.0\",\n    \"is-date-object\": \"^1.0.5\",\n    \"is-negative-zero\": \"^2.0.2\",\n    \"is-number-object\": \"^1.0.6\",\n    \"is-obj\": \"^1.0.1\",\n    \"is-regex\": \"^1.1.4\",\n    \"is-regexp\": \"^1.0.0\",\n    \"is-shared-array-buffer\": \"^1.0.1\",\n    \"is-string\": \"^1.0.7\",\n    \"is-symbol\": \"^1.0.4\",\n    \"is-weakref\": \"^1.0.2\",\n    \"isarray\": \"^0.0.1\",\n    \"json-lines\": \"^1.0.0\",\n    \"json-schema-traverse\": \"^0.4.1\",\n    \"jsonwebtoken\": \"^8.5.0\",\n    \"jwa\": \"^1.4.1\",\n    \"jws\": \"^3.2.2\",\n    \"limes\": \"^2.0.0\",\n    \"lodash\": \"^4.17.11\",\n    \"lodash.includes\": \"^4.3.0\",\n    \"lodash.isboolean\": \"^3.0.3\",\n    \"lodash.isinteger\": \"^4.0.4\",\n    \"lodash.isnumber\": \"^3.0.3\",\n    \"lodash.isplainobject\": \"^4.0.6\",\n    \"lodash.isstring\": \"^4.0.1\",\n    \"lodash.once\": \"^4.1.1\",\n    \"lusca\": \"^1.6.1\",\n    \"media-typer\": \"^0.3.0\",\n    \"merge-descriptors\": \"^1.0.1\",\n    \"methods\": \"^1.1.2\",\n    \"mime\": \"^1.4.1\",\n    \"mime-db\": \"^1.51.0\",\n    \"mime-types\": \"^2.1.34\",\n    \"moment\": \"^2.22.2\",\n    \"morgan\": \"^1.9.1\",\n    \"ms\": \"^2.0.0\",\n    \"nanoid\": \"^3.1.30\",\n    \"negotiator\": \"^0.6.2\",\n    \"nocache\": \"^2.0.0\",\n    \"node-releases\": \"^2.0.1\",\n    \"node-rsa\": \"^0.4.2\",\n    \"node-statsd\": \"^0.1.1\",\n    \"normalize-range\": \"^0.1.2\",\n    \"object-assign\": \"^4.1.1\",\n    \"object-inspect\": \"^1.12.0\",\n    \"object-keys\": \"^1.1.1\",\n    \"object.assign\": \"^4.1.2\",\n    \"object.getownpropertydescriptors\": \"^2.1.3\",\n    \"on-finished\": \"^2.3.0\",\n    \"on-headers\": \"^1.0.2\",\n    \"parseurl\": \"^1.3.3\",\n    \"partof\": \"^1.0.0\",\n    \"path-parse\": \"^1.0.7\",\n    \"path-to-regexp\": \"^0.1.7\",\n    \"picocolors\": \"^1.0.0\",\n    \"postcss-value-parser\": \"^4.2.0\",\n    \"processenv\": \"^1.1.0\",\n    \"proxy-addr\": \"^2.0.7\",\n    \"punycode\": \"^2.1.1\",\n    \"qs\": \"^6.5.2\",\n    \"range-parser\": \"^1.2.1\",\n    \"raw-body\": \"^2.3.3\",\n    \"readable-stream\": \"^1.1.14\",\n    \"regenerator-runtime\": \"^0.12.1\",\n    \"resolve\": \"^1.21.0\",\n    \"retry\": \"^0.12.0\",\n    \"rollup\": \"^2.63.0\",\n    \"safe-buffer\": \"^5.1.2\",\n    \"safer-buffer\": \"^2.1.2\",\n    \"semver\": \"^5.7.1\",\n    \"send\": \"^0.16.2\",\n    \"serve-static\": \"^1.13.2\",\n    \"setprototypeof\": \"^1.1.0\",\n    \"sha-1\": \"^0.1.1\",\n    \"side-channel\": \"^1.0.4\",\n    \"source-map\": \"^0.6.1\",\n    \"source-map-js\": \"^1.0.1\",\n    \"source-map-resolve\": \"^0.6.0\",\n    \"split2\": \"^3.0.0\",\n    \"stack-trace\": \"^0.0.10\",\n    \"statuses\": \"^1.4.0\",\n    \"stethoskop\": \"^1.0.0\",\n    \"string_decoder\": \"^0.10.31\",\n    \"string.prototype.trimend\": \"^1.0.4\",\n    \"string.prototype.trimstart\": \"^1.0.4\",\n    \"stringify-object\": \"^3.3.0\",\n    \"supports-color\": \"^5.5.0\",\n    \"supports-preserve-symlinks-flag\": \"^1.0.0\",\n    \"timer2\": \"^1.0.0\",\n    \"tsscmp\": \"^1.0.6\",\n    \"type-is\": \"^1.6.18\",\n    \"unbox-primitive\": \"^1.0.1\",\n    \"unpipe\": \"^1.0.0\",\n    \"untildify\": \"^3.0.3\",\n    \"uri-js\": \"^4.4.1\",\n    \"util-deprecate\": \"^1.0.2\",\n    \"util.promisify\": \"^1.0.0\",\n    \"utils-merge\": \"^1.0.1\",\n    \"uuid\": \"^3.3.2\",\n    \"uuidv4\": \"^3.0.1\",\n    \"varname\": \"^2.0.3\",\n    \"vary\": \"^1.1.2\",\n    \"which-boxed-primitive\": \"^1.0.2\",\n    \"ws\": \"^6.2.0\"\n  },\n  \"description\": \"\"\n}\n```\n\n```text\nnpm install -D tailwind css postcss autoprefixer vite\n```\n\n```text\n8.1.2\n```\n\n```text\n16.13.1\n```\n\n```text\nnpm WARN EBADENGINE   required: { node: '>=0.8 <=9' }\n```\n\n```text\ntailwindcss\n```\n\n```text\ntailwind\n```\n\n```text\nnpm WARN EBADENGINE Unsupported engine {\nnpm WARN EBADENGINE   package: '@eslint/eslintrc@1.3.0',\nnpm WARN EBADENGINE   required: { node: '^12.22.0 || ^14.17.0 || >=16.0.0' },\nnpm WARN EBADENGINE   current: { node: 'v14.16.1', npm: '8.2.0' }\nnpm WARN EBADENGINE }\n```\n\n```text\ntailwind\n```\n\n```text\nnode.js\n```\n\n```text\n14.17.0\n```\n\n```text\nnpm uninstall tailwind\n```\n\n```text\nnpm install tailwindcss@latest postcss@latest autoprefixer@latest\n```\n\n========================================\n\nComments:\n- Could you please add your `package.json` content here?\n- @RazLuvaton drive.google.com/file/d/1uLHLbJquCepDwXzlR1kGt0FFUjxx-wr5/&hellip; this is link of my package .json\n- You can include the package json content in your question itself\n- With this specific issue its because the OP installed the wrong tailwind package.\n- Thank you! This was exactly the problem I was having and I had no idea.\n- mend.io/free-developer-tools/blog/&hellip;\n- I don't think downgrading from Node 16 to Node 9 is an acceptable solution.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:46.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":525,"estimatedTokens":3460}}226{"id":"stack-73408434","source":"stackoverflow","questionId":73408434,"title":"vite failed to load config from vite.config.js,","tags":["javascript","node.js","vue.js","vite"],"text":"Title: vite failed to load config from vite.config.js,\nTags: javascript, node.js, vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI created a new vue app by doing these (*according to vue docs*)\n\n- `npm init vue@latest`\n\n- `npm install`\n\nThen I try to run `npm run dev`.Then this happened.\n\nhttps://i.sstatic.net/Q22IX.png\n\n**My environments are these**\n\n- OS => Ubuntu\n\n- Node version => 18.7.0\n\n- npm version => 8.15.0\n\n**My package.json**\n\n```\n{\n \"name\": \"vue-project\",\n \"version\": \"0.0.0\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview --port 4173\"\n },\n \"dependencies\": {\n \"vue\": \"^3.2.37\"\n },\n \"devDependencies\": {\n \"@vitejs/plugin-vue\": \"^3.0.1\",\n \"vite\": \"^3.0.4\"\n }\n}\n```\n\n**My vite.config.js**\n\n```\nimport { fileURLToPath, URL } from 'node:url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [vue()],\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url))\n }\n }\n})\n```\n\nI have been searching for a while now but no avail.Thanks in advance.\n\n========================================\n\nTop Answer:\nUpdate: **Dec 2024**\n\nThe latest version of vite is having build issues.\nThe current version is 6 series.\n\nYou can use the version 5 for now, it'll fix the issue.\n\nI am using this:\n`\"vite\": \"^5.4.10\"`\n\nYou can keep an eye on vite's github repo for latest resolves.\n\n========================================\n\nCode:\n```text\n{\n  \"name\": \"vue-project\",\n  \"version\": \"0.0.0\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"preview\": \"vite preview --port 4173\"\n  },\n  \"dependencies\": {\n    \"vue\": \"^3.2.37\"\n  },\n  \"devDependencies\": {\n    \"@vitejs/plugin-vue\": \"^3.0.1\",\n    \"vite\": \"^3.0.4\"\n  }\n}\n```\n\n```text\nimport { fileURLToPath, URL } from 'node:url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue()],\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url))\n    }\n  }\n})\n```\n\n```text\nnpm init vue@latest\n```\n\n```text\nnpm install\n```\n\n```text\nnpm run dev\n```\n\n```js\nimport { resolve } from 'path';\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n    plugins: [],\n    build: {\n        lib: {\n            entry: resolve(__dirname, 'src/index.ts'),\n            name: 'myLib',\n            fileName: 'myLib',\n        },\n        rollupOptions: {\n            external: [/^node:\\w+/], // <-- ignores all 'node:*'\n        },\n    },\n});\n```\n\n```text\n\"vite\": \"^5.4.10\"\n```\n\n========================================\n\nComments:\n- Just try to delete `node_modules`, and install again\n- @MichalLev&#253; I tried it a lot of times,but still the same error,also changed node version back and forth but still the same error.\n- There is one vital step missing in your procedure that you didn't mention. After `npm init vue@latest vue-project` it is essential you do a `cd vue-project` and there do `npm install`\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review\n- This answer is (essentially) already listed.\n- This has already been discussed in the comment section on the question itself\n- YES! This solved my issue: \"Expected identifier but found \"import\"\" Was so frustrating that the app wasn't running out of the box thanks\n- I kindly suggest to put a bit more effort in the way you write your answer. For guidance, please check How do I write a good answer?\n- I tried to delete node_modules and re-install, then delete package-lock.json and re-install and that didn’t solve the problem. Then I deleted both at the same time and that solve this issue for me! Thank’s","metadata":{"transformedAt":"2026-08-18T18:33:46.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":167,"estimatedTokens":1032}}227{"id":"stack-66402879","source":"stackoverflow","questionId":66402879,"title":"In Vite2, How to import an ESModule in tailwind.config.js","tags":["javascript","tailwind-css","vite"],"text":"Title: In Vite2, How to import an ESModule in tailwind.config.js\nTags: javascript, tailwind-css, vite\nSource: Stack Overflow\n\nQuestion:\nBuilding a Vite2 app.\n\ntried to import an `ESModule` in `tailwind.config.js`.\nThe Module was exported like:\n\n```\nexport default xxx;\n```\n\nThen I imported the module in `tailwind.config.js` like:\n\n```\nconst xx = require('./xx/xxx');\n```\n\nBut I got an Error:\n\n```\n[plugin:vite:css] Cannot use import statement outside a module\n```\n\nHow do I fix this?\n\n========================================\n\nCode:\n```text\nexport default xxx;\n```\n\n```text\nconst xx = require('./xx/xxx');\n```\n\n```text\n[plugin:vite:css] Cannot use import statement outside a module\n```\n\n```text\nESModule\n```\n\n```text\ntailwind.config.js\n```\n\n```text\ntailwind.config.js\n```\n\n```text\nexport default {\n  purge: ['./*.html', './src/**/*.{vue,js,ts,jsx,tsx,css}'],\n  darkMode: false, // or 'media' or 'class'\n  theme: {\n    extend: {},\n  },\n  variants: {\n    extend: {},\n  },\n  plugins: [],\n}\n```\n\n```text\nimport tailwind from 'tailwindcss'\nimport autoprefixer from 'autoprefixer'\nimport tailwindConfig from './tailwind.config.js'\n\nexport default {\n  plugins: [tailwind(tailwindConfig), autoprefixer],\n}\n```\n\n```text\ncss: {\n  postcss,\n},\n```\n\n```text\nimport\n```\n\n```text\nimport postcss from './postcss.config.js'\n```\n\n========================================\n\nComments:\n- Thank you very much! BTW, can use `.mjs` extension for webpack: `await import('.&#47;postcss.config.mjs').then((m) => m.default)`\n- I wonder why the Tailwind Vue 3 and Vite official installation guide tailwindcss.com/docs/guides/vite doesn't mention these essential steps?\n- Indeed it seems to work even though Tailwind authors say it's not supported github.com/tailwindlabs/tailwindcss/issues/&hellip;\n- It's not worked for me unfortunately, glad you got it fixed though.","metadata":{"transformedAt":"2026-08-18T18:33:46.411Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":100,"estimatedTokens":460}}228{"id":"stack-71064299","source":"stackoverflow","questionId":71064299,"title":"Scss not loaded with Vite","tags":["vuejs3","storybook","vite"],"text":"Title: Scss not loaded with Vite\nTags: vuejs3, storybook, vite\nSource: Stack Overflow\n\nQuestion:\nThe build with Vite and Vue works like a charm (so ist the path correct). However, it does not with storybook.\n\nHere my config:\n\nvite.config.js\n\n```\nimport { defineConfig } from 'vite'\nimport { resolve } from 'path'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n css: {\n preprocessorOptions: {\n scss: { \n additionalData: `@import \"./src/css/global.scss\";` \n },\n },\n },\n})\n```\n\n.storybook/main.js:\n\n```\nmodule.exports = {\n \"stories\": [\n \"../src/**/*.stories.mdx\",\n \"../src/**/*.stories.@(js|jsx|ts|tsx)\"\n ],\n \"addons\": [\n \"@storybook/addon-links\",\n \"@storybook/addon-essentials\",\n \"@storybook/preset-scss\"\n ],\n \"framework\": \"@storybook/vue3\",\n \"core\": {\n \"builder\": \"storybook-builder-vite\"\n }\n}\n```\n\nI am using storybook-builder-vite as vite is used to build the project too.\n\npackage.json\n\n```\n\"devDependencies\": {\n \"@storybook/addon-actions\": \"^6.4.18\",\n \"@storybook/addon-essentials\": \"^6.4.18\",\n \"@storybook/addon-links\": \"^6.4.18\",\n \"@storybook/preset-scss\": \"^1.0.3\",\n \"@storybook/vue3\": \"^6.4.18\",\n \"sass\": \"^1.49.7\",\n \"sass-loader\": \"^12.4.0\",\n \"storybook-builder-vite\": \"^0.1.15\",\n \"typescript\": \"^4.4.4\",\n \"vite\": \"^2.7.2\",\n \"vue-i18n\": \"^8.27.0\",\n \"vue-loader\": \"^16.8.3\",\n \"vue-tsc\": \"^0.29.8\"\n}\n```\n\nAny ideas ?\n\n========================================\n\nTop Answer:\nThe `preprocessorOptions.*.additionalData` parameter will only work if there are already loaded/imported css to prepend to, so basically using both options of importing directly into your `main.ts` file for the bulk and any other preprocessing can be defined in the `vite.config.js` file.\n\nTh documentation at https://vitejs.dev/config/#css-preprocessoroptions unfortunately does NOT explain this, which did tarnish a perfectly good Saturday night\n\n========================================\n\nCode:\n```js\nimport { defineConfig } from 'vite'\nimport { resolve } from 'path'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  css: {\n    preprocessorOptions: {\n      scss: { \n         additionalData: `@import \"./src/css/global.scss\";` \n     },\n    },\n  },\n})\n```\n\n```js\nmodule.exports = {\n  \"stories\": [\n    \"../src/**/*.stories.mdx\",\n    \"../src/**/*.stories.@(js|jsx|ts|tsx)\"\n  ],\n  \"addons\": [\n    \"@storybook/addon-links\",\n    \"@storybook/addon-essentials\",\n    \"@storybook/preset-scss\"\n  ],\n  \"framework\": \"@storybook/vue3\",\n  \"core\": {\n    \"builder\": \"storybook-builder-vite\"\n  }\n}\n```\n\n```json\n\"devDependencies\": {\n    \"@storybook/addon-actions\": \"^6.4.18\",\n    \"@storybook/addon-essentials\": \"^6.4.18\",\n    \"@storybook/addon-links\": \"^6.4.18\",\n    \"@storybook/preset-scss\": \"^1.0.3\",\n    \"@storybook/vue3\": \"^6.4.18\",\n    \"sass\": \"^1.49.7\",\n    \"sass-loader\": \"^12.4.0\",\n    \"storybook-builder-vite\": \"^0.1.15\",\n    \"typescript\": \"^4.4.4\",\n    \"vite\": \"^2.7.2\",\n    \"vue-i18n\": \"^8.27.0\",\n    \"vue-loader\": \"^16.8.3\",\n    \"vue-tsc\": \"^0.29.8\"\n}\n```\n\n```js\nimport { createApp } from 'vue'\nimport { createPinia } from 'pinia'\n\nimport App from './App.vue'\nimport router from './router'\n\n//import your scss here\nimport \"@/assets/scss/style.scss\";\n\nconst app = createApp(App)\n\napp.use(createPinia())\napp.use(router)\n\napp.mount('#app')\n```\n\n```text\nmain.ts\n```\n\n```text\n1.49.8\n```\n\n```text\n3.2.29\n```\n\n```text\npreprocessorOptions.*.additionalData\n```\n\n```text\nmain.ts\n```\n\n```text\nvite.config.js\n```\n\n```text\nnpm install @storybook/builder-vite --save-dev\n```\n\n```text\nyarn add --dev @storybook/builder-vite\n```\n\n```js\nconst { mergeConfig } = require('vite');\n\nmodule.exports = {\n  async viteFinal(config, { configType }) {\n    // return the customized config\n    return mergeConfig(config, {\n      css: {\n        preprocessorOptions: {\n          scss: {\n            // Next line will prepend the import in all you scss files as you did with your vite.config.js file\n            additionalData: `@import \"./src/styles/main\";`,\n          },\n        },\n      },\n    });\n  },\n  // ... other options here\n};\n```\n\n```text\ncss: {\n   preprocessorOptions: {\n     scss: {\n       includePaths: ['node_modules']\n     }\n   }\n },\n```\n\n```text\n@import 'my-npm-module/sass/file'\n```\n\n```text\n\"vite\": \"^3.2.0\"\n```\n\n```text\n\"lit\": \"^2.3.1\",\n```\n\n========================================\n\nComments:\n- I see that you are using `storybook-builder-vite` in this example. Note that the package has been renamed to `@storybook&#47;builder-vite`, so if you haven't already updated, you should do so when you have a chance.\n- It is already done. The package was correct at the time I wrote this question.\n- Same issue, same method solved it. \"sass\":\"1.53.0\" and \"vue\":\"3.2.25\"\n- I maybe add a little addition this comment via vite's docs: vitejs.dev/guide/features.html#import-inlining-and-rebasing\n- I also would like to mention my personal experience. Unless your style file somehow not `@import`ed by your component or other style files, vite won't process it. And `@import` keyword, at-rule, directive (whatever your preprocessor call it) is the important to use, For instance, I am using SCSS and try `@use` instead of `@import` and it won't work. I mean vite does not pick up my SCSS file where it's included via `@use` another SCSS file.\n- I had the same issue with `@use` as Halil. The issue was I forgot the `as *`. This solved my problem: `@use \".&#47;styles&#47;global\" as *;`","metadata":{"transformedAt":"2026-08-18T18:33:46.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":237,"estimatedTokens":1360}}229{"id":"stack-68654761","source":"stackoverflow","questionId":68654761,"title":"How to add a public directory in vitejs configuration file","tags":["javascript","building","vite"],"text":"Title: How to add a public directory in vitejs configuration file\nTags: javascript, building, vite\nSource: Stack Overflow\n\nQuestion:\nI have a folder (named `assets`) with pictures, pdf files and 3d models that I want to include in the public static path at `dist` directory after building with Vite.js.\n\nI am using this code for the `vite.config.js`:\n\n```\nexport default {\n publicDir: './assets'\n }\n```\n\nHowever after building, the files are not copied to the `dist` folder. When I run `vite serve` the website works, but I get \"not found error\" for all the files that should've been in that public folder.\nThanks a lot for the help.\n\n========================================\n\nTop Answer:\nJust adding to this one because I was stuck on it with react:\n\nThe Vite config docs specify this format:\n\n```\nexport default {\n // config options\n}\n```\n\nThey also suggest you pop this tag on the top for auto completion:\n\n```\n/** @type {import('vite').UserConfig} */\nexport default defineConfig({\n // config options\n})\n```\n\nWhen I added the tag it auto completed the build directory config for me:\n\n```\nexport default defineConfig({\n build: {\n outDir: 'public',\n },\n})\n```\n\n========================================\n\nCode:\n```text\nexport default {\n    publicDir: './assets'\n  }\n```\n\n```text\nassets\n```\n\n```text\ndist\n```\n\n```text\nvite.config.js\n```\n\n```text\ndist\n```\n\n```text\nvite serve\n```\n\n```text\nmodule.exports = {\n    root: './',\n    build: {\n        outDir: 'dist',\n    },\n    publicDir: 'assets'\n }\n```\n\n```text\nvite.config.js\n```\n\n```text\nexport default {\n  // config options\n}\n```\n\n```text\n/** @type {import('vite').UserConfig} */\nexport default defineConfig({\n  // config options\n})\n```\n\n```text\nexport default defineConfig({\n    build: {\n        outDir: 'public',\n    },\n})\n```\n\n========================================\n\nComments:\n- Is it working for default directory `&#47;public` ?\n- I actually managed to solve it with this code: `module.exports = { root: '.&#47;', build: { outDir: 'dist', }, publicDir: 'assets' }`\n- typo in your first vite.config.js: pulicDir","metadata":{"transformedAt":"2026-08-18T18:33:46.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":120,"estimatedTokens":516}}230{"id":"stack-69078675","source":"stackoverflow","questionId":69078675,"title":"Custom URL in Vite dev server (multi page app)","tags":["javascript","reactjs","vite"],"text":"Title: Custom URL in Vite dev server (multi page app)\nTags: javascript, reactjs, vite\nSource: Stack Overflow\n\nQuestion:\nI'm building a multi page app with Vite (migrating from Webpack).\n\nTo open the login page in the dev server I have to go to: `localhost:3010/login.html`\n\nIs it possible to tweak the Vite config to serve login.html with the URL as: `localhost:3010/login` (without .html)?\n\n```\n// vite.config.js excerpt\n\nexport default {\n build: {\n rollupOptions: {\n input: {\n index: new URL('./index.html', import.meta.url).pathname,\n login: new URL('./login.html', import.meta.url).pathname,\n }\n }\n },\n server: {\n port: 3010,\n proxy: {\n '/api': 'http://localhost:5000/',\n },\n },\n};\n```\n\n========================================\n\nTop Answer:\nAs Rafael pointed out, rewriting the URL breaks the HMR feature for that page. Using a redirect, however, does not:\n\n```\n//req.url += '.html'\nres.writeHead(301, { Location: `${req.url}.html` })\n```\n\nYou will get an \"ugly\" URL during development, but you can revert to URL rewriting on your production server (since HMR would not be needed then).\n\n========================================\n\nCode:\n```json\n// vite.config.js excerpt\n\nexport default {\n  build: {\n    rollupOptions: {\n      input: {\n        index: new URL('./index.html', import.meta.url).pathname,\n        login: new URL('./login.html', import.meta.url).pathname,\n      }\n    }\n  },\n  server: {\n    port: 3010,\n    proxy: {\n      '/api': 'http://localhost:5000/',\n    },\n  },\n};\n```\n\n```text\nlocalhost:3010/login.html\n```\n\n```text\nlocalhost:3010/login\n```\n\n```js\nimport { defineConfig } from 'vite'\n\nconst LoginHtmlFallbackPlugin = {\n  name: 'login-html-fallback',\n  configureServer(server) {\n    server.middlewares.use('/login', (req, res, next) => {\n      req.url += '.html'\n      next()\n    })\n  }\n}\n\nexport default defineConfig({\n  plugins: [\n    LoginHtmlFallbackPlugin\n  ],\n})\n```\n\n```js\n// build/plugins/html-ext-fallback.js\nimport path from 'path'\nimport fs from 'fs'\n\nexport default (options) => ({\n  name: 'html-ext-fallback',\n  configureServer(server) {\n    server.middlewares.use((req, res, next) => {\n      // Check extensionless URLs but ignore the `/` root path\n      if (req.originalUrl.length > 1 && !path.extname(req.originalUrl)) {\n        if (fs.existsSync(path.join(options.rootDir, `${req.originalUrl}.html`))) {\n          req.url += '.html'\n        }\n      }\n      next()\n    })\n  }\n})\n\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport HtmlExtFallbackPlugin from './build/plugins/html-ext-fallback'\n\nexport default defineConfig({\n  plugins: [\n    HtmlExtFallbackPlugin({ rootDir: __dirname })\n  ],\n})\n```\n\n```text\nconfigureServer(server)\n```\n\n```text\nserver\n```\n\n```text\nViteDevServer\n```\n\n```text\nmiddlewares\n```\n\n```text\nmiddlewares.use()\n```\n\n```text\n/login\n```\n\n```text\n/login.html\n```\n\n```text\nplugins\n```\n\n```text\n.html\n```\n\n```text\n.html\n```\n\n```text\n//req.url += '.html'\nres.writeHead(301, { Location: `${req.url}.html` })\n```\n\n```js\n//config.Testing.js\n\nprocess.env.PORT = 3000;\nprocess.env.HOST = 'localhost';\nprocess.env.CLIENT_ID = 'your_client_id';\nprocess.env.REDIRECT_URI = 'your_callback_endpoint';\n\nvar VITE_APP_UI_URL = \"your_test_url_1 , your_test_url_2\";\nvar VITE_SITE_KEY = \"your_site_key\";\nvar VITE_APP_API_BASEURL = \"your_baseurl\";\n```\n\n```text\npublic/env/config.js\n```\n\n```text\nconfig.testing.js\n```\n\n```text\nVITE_APP_UI_URL\n```\n\n========================================\n\nComments:\n- I noticed that this solution breaks the Vite HMR when accessing `&#47;page-name`, but `&#47;page-name.html` still works (the content is refreshed when you save the code in the `page-name.html` file). Do you know how to fix this issue?","metadata":{"transformedAt":"2026-08-18T18:33:46.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":201,"estimatedTokens":921}}231{"id":"stack-70454977","source":"stackoverflow","questionId":70454977,"title":"Vite production build errors: `...is not a constructor' for node_modules","tags":["vue.js","rollupjs","vite","esbuild"],"text":"Title: Vite production build errors: `...is not a constructor' for node_modules\nTags: vue.js, rollupjs, vite, esbuild\nSource: Stack Overflow\n\nQuestion:\nI'm trying to do a build for a simple Vue-based project with Vite, but I am running into an error when actually processing the build.\n\nMy `vite.config.js` file:\n\n```\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport nodePolyfills from 'rollup-plugin-node-polyfills'\nimport commonjs from '@rollup/plugin-commonjs'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n vue(),\n nodePolyfills(),\n commonjs(),\n ],\n\n resolve: {\n alias: [\n {\n // this is required for the SCSS modules\n find: /^~(.*)$/,\n replacement: '$1',\n },\n ],\n },\n\n build: {\n outDir: './dist',\n },\n})\n```\n\nThe build command `vite build` runs fine without warnings and compiles these files in the `dist` folder:\n\n- dist/index.html\n\n- dist/assets/index.83eff058.js\n\n- dist/assets/index.acd5fd56.css\n\n- dist/assets/vendor.96c4e7e1.js (the problem file)\n\nAnd when serving my built project, I get this error that crashes the entire thing and doesn't load anything besides CSS:\n\n```\nUncaught TypeError: Vg is not a constructor\n XA http://localhost:5000/assets/vendor.96c4e7e1.js:5\n http://localhost:5000/assets/vendor.96c4e7e1.js:5\nvendor.96c4e7e1.js:5:11738\n XA http://localhost:5000/assets/vendor.96c4e7e1.js:5\n http://localhost:5000/assets/vendor.96c4e7e1.js:5\n InnerModuleEvaluation self-hosted:2388\n InnerModuleEvaluation self-hosted:2388\n evaluation self-hosted:2349\n```\n\nI've read through the Vite and Rollup documentation and really can't figure out what to even look for. Is this occurring because of the lack of Babel, or is this something else?\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport nodePolyfills from 'rollup-plugin-node-polyfills'\nimport commonjs from '@rollup/plugin-commonjs'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    vue(),\n    nodePolyfills(),\n    commonjs(),\n  ],\n\n  resolve: {\n    alias: [\n      {\n        // this is required for the SCSS modules\n        find: /^~(.*)$/,\n        replacement: '$1',\n      },\n    ],\n  },\n\n  build: {\n    outDir: './dist',\n  },\n})\n```\n\n```text\nUncaught TypeError: Vg is not a constructor\n    XA http://localhost:5000/assets/vendor.96c4e7e1.js:5\n    <anonymous> http://localhost:5000/assets/vendor.96c4e7e1.js:5\nvendor.96c4e7e1.js:5:11738\n    XA http://localhost:5000/assets/vendor.96c4e7e1.js:5\n    <anonymous> http://localhost:5000/assets/vendor.96c4e7e1.js:5\n    InnerModuleEvaluation self-hosted:2388\n    InnerModuleEvaluation self-hosted:2388\n    evaluation self-hosted:2349\n```\n\n```text\nvite.config.js\n```\n\n```text\nvite build\n```\n\n```text\ndist\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  build: {\n    commonjsOptions: { include: [] },\n  },\n  optimizeDeps: {\n    disabled: false,\n  },\n});\n```\n\n========================================\n\nComments:\n- did you ever find a solution to this? I've encounter a similar issue. Dev build works fine, but when I run what's in the `dist` folder I get a similar error\n- This is the result of that as of TODAY: \"Experimental optimizeDeps.disabled and deps pre-bundling during build were removed in Vite 5.1. Setting it to false now has no effect. Please remove optimizeDeps.disabled from your config.\"\n- @philw I haven't been using Vite for a while now, but the issue I linked to was recently closed as fixed in Vite 6.0","metadata":{"transformedAt":"2026-08-18T18:33:46.411Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":144,"estimatedTokens":909}}232{"id":"stack-70982306","source":"stackoverflow","questionId":70982306,"title":"Get raw string value by import with vite","tags":["css","import","web-component","vite","lit"],"text":"Title: Get raw string value by import with vite\nTags: css, import, web-component, vite, lit\nSource: Stack Overflow\n\nQuestion:\nI want to get raw string of css in npm module through vite.\nAccording to vite manual,\n\nhttps://vitejs.dev/guide/assets.html#importing-asset-as-string\n\nIt says we can get raw string by putting \"?raw\" at the end of identifier.\n\nSo I try this:\n\nimport style from \"swiper/css/bundle?raw\";\n\nBut this shows error like:\n\n[vite] Internal server error: Missing \"./css/bundle?raw\" export in\n\"swiper\" package\n\nIf I use this:\n\nimport style from \"swiper/css/bundle\";\n\nThere are no error, but css is not just load as string but handled as bundle css.\n\nThis is not good, because I want to use this css in my lit-based web components.\n\nAre there any way to get css as raw string through vite?\n\n========================================\n\nCode:\n```text\nimport style from \"swiper/css/bundle.css?inline\";\n```\n\n```text\ninline\n```\n\n========================================\n\nComments:\n- Have you tried fetch?\n- In my case, fetch doesn't help, maybe, because I don't want to bind it in document root but want to bind it inside of web component's shadow root.\n- Does this answer help? stackoverflow.com/a/70767978/534858","metadata":{"transformedAt":"2026-08-18T18:33:46.411Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":48,"estimatedTokens":305}}233{"id":"stack-70561989","source":"stackoverflow","questionId":70561989,"title":"Loading PostCSS Plugin failed: Cannot find module 'tailwindcss'","tags":["npm","tailwind-css","postcss","vite","autoprefixer"],"text":"Title: Loading PostCSS Plugin failed: Cannot find module 'tailwindcss'\nTags: npm, tailwind-css, postcss, vite, autoprefixer\nSource: Stack Overflow\n\nQuestion:\nThis is my first Tailwind CSS project and started with CDN, but I did not always have internet, so I tried it installing using PostCSS, and I am using Vite as my server.\n\nFollowed this video from CodeWithHarry https://www.youtube.com/watch?v=aUunolbb1xU&list=PLu0W_9lII9ahwFDuExCpPFHAK829Wto2O&index=3\n\nI first initiated the project by\n\n```\nnpm init -y\n```\n\nand installed required packages by\n\n```\nnpm install -D tailwind postcss autoprefixer vite\n```\n\nand then initiated the Tailwind CSS by\n\n```\nnpx tailwindcss init -p\n```\n\nand also I entered @tailwind directives in a input.css file.\n\nBut when I ran:\n\n```\nnpm start\n```\n\nMy vite server greeted me with this error:\n\n```\n[plugin:vite:css] Loading PostCSS Plugin failed: Cannot find module 'tailwindcss'\nRequire stack:\n - C:\\projects\\2 Shidhu\\twproject\\noop.js\n \n (@C:\\projects\\2 Shidhu\\twproject\\postcss.config.js)\n```\n\nhttps://i.sstatic.net/sumN5.png\n\nMy index.html:\n\n```\n\n \n \n \n \n My first tailwindcss project\n\n \n \n \n \n \n- Home\n \n- About Us\n \n- Contact Us\n \n- Blog\n \n \n \n \n \n RubyMine\n\n RubyMine is a dedicated Ruby and Rails development environment. The IDE provides a wide range of essential tools for Ruby developers, tightly integrated together to create a convenient environment for productive Ruby development and Web development with Ruby on Rails. RubyMine is available for a free 30-day evaluation.\n\n \n \n \n \n \n\n```\n\nMy tailwind.config.js:\n\n```\nmodule.exports = {\n content: [\"*\"],\n theme: {\n extend: {},\n },\n plugins: [],\n}\n```\n\nMy postcss.config.js:\n\n```\nmodule.exports = {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n}\n```\n\nMy package.json:\n\n```\n{\n \"name\": \"twproject\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"start\": \"vite\"\n },\n \"keywords\": [],\n \"author\": \"\",\n \"license\": \"ISC\",\n \"devDependencies\": {\n \"autoprefixer\": \"^10.4.1\",\n \"postcss\": \"^8.4.5\",\n \"tailwind\": \"^4.0.0\",\n \"vite\": \"^2.7.10\"\n }\n}\n```\n\nHow can I solve this?\n\n========================================\n\nTop Answer:\nCreate React App does not support custom PostCSS configurations and is incompatible with many important tools in the PostCSS ecosystem, like `postcss-import`.\n\nhttps://tailwindcss.com/docs/guides/create-react-app\n\n========================================\n\nCode:\n```text\nnpm init -y\n```\n\n```text\nnpm install -D tailwind postcss autoprefixer vite\n```\n\n```text\nnpx tailwindcss init -p\n```\n\n```text\nnpm start\n```\n\n```none\n[plugin:vite:css] Loading PostCSS Plugin failed: Cannot find module 'tailwindcss'\nRequire stack:\n - C:\\projects\\2 Shidhu\\twproject\\noop.js\n \n (@C:\\projects\\2 Shidhu\\twproject\\postcss.config.js)\n```\n\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <link rel=\"stylesheet\" href=\"input.css\">\n    <title>My first tailwindcss project</title>\n</head>\n<body>\n    <nav class=\"bg-purple-900 text-white flex justify-between\">\n        \n        <img src=\"./assets/logo.png\" alt=\"logo\" class=\"h-20 px-3 py-4\">\n        <ul class=\"flex space-x-11 justify-end pt-6 px-8 font-bold \">\n            <li><a href=\"#\" class=\"hover:border-b-2 hover:text-fuchsia-600 hover:border-fuchsia-600\">Home</a></li>\n            <li><a href=\"#\" class=\"hover:border-b-2 hover:text-fuchsia-600 hover:border-fuchsia-600\">About Us</a></li>\n            <li><a href=\"#\" class=\"hover:border-b-2 hover:text-fuchsia-600 hover:border-fuchsia-600\">Contact Us</a></li>\n            <li><a href=\"#\" class=\"hover:border-b-2 hover:text-fuchsia-600 hover:border-fuchsia-600\">Blog</a></li>\n        </ul>\n    </nav>\n    <main>\n        <div class=\"bg-fuchsia-200 pb-8 flex justify-between\">\n            <div>\n            <p class=\"font-bold text-3xl px-8 py-10\">RubyMine</p>\n            <p class=\"mx-8 w-80\">RubyMine is a dedicated Ruby and Rails development environment. The IDE provides a wide range of essential tools for Ruby developers, tightly integrated together to create a convenient environment for productive Ruby development and Web development with Ruby on Rails. RubyMine is available for a free 30-day evaluation.</p>\n            </div>\n            <img src=\"./assets/logo.png\" alt=\"logo\" class=\"h-60 pt-16 pr-16\">\n        </div>\n        <hr>\n    </main>\n</body>\n</html>\n```\n\n```js\nmodule.exports = {\n    content: [\"*\"],\n    theme: {\n        extend: {},\n    },\n    plugins: [],\n}\n```\n\n```js\nmodule.exports = {\n    plugins: {\n        tailwindcss: {},\n        autoprefixer: {},\n    },\n}\n```\n\n```json\n{\n  \"name\": \"twproject\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"start\": \"vite\"\n  },\n  \"keywords\": [],\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"devDependencies\": {\n    \"autoprefixer\": \"^10.4.1\",\n    \"postcss\": \"^8.4.5\",\n    \"tailwind\": \"^4.0.0\",\n    \"vite\": \"^2.7.10\"\n  }\n}\n```\n\n```text\nnpm install -D tailwindcss postcss autoprefixer vite\nnpm tailwindcss init\n```\n\n```text\nnpm install -D tailwind postcss autoprefixer vite\n```\n\n```text\ntailwindcss\n```\n\n```text\ntailwind\n```\n\n```text\npostcss-import\n```\n\n========================================\n\nComments:\n- I had same issue but with autoprefixer, yarn add fixed it. Thanks.\n- Hi, what should be the name of the tailwind config file please ? tailwind.config.js or tailwindcss.config.js ?\n- @GBETNKOMNJIFON the name of the tailwindcss config file need to be `tailwind.config.js`\n- \"npx tailwindcss init\" would be better","metadata":{"transformedAt":"2026-08-18T18:33:46.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":271,"estimatedTokens":1400}}234{"id":"stack-74159670","source":"stackoverflow","questionId":74159670,"title":"Vite multiple apps with same source","tags":["javascript","html","vite","project-structure"],"text":"Title: Vite multiple apps with same source\nTags: javascript, html, vite, project-structure\nSource: Stack Overflow\n\nQuestion:\nI am new to vite, to start with, I don't actually know what kind of structure I need.\n\nI need to build multiple apps but some of them depend on the same components.\n\nhttps://i.sstatic.net/N0WHB.png\n\nIt worked well by far however I think mixed something\n\n```\n\n \n \n \n \n Vite App\n \n \n \n \n \n \n \n \n\n```\n\nHrefs are wrong, what am I missing?\n\nforgot to attach vite config:\n\n```\nimport { fileURLToPath, URL } from 'node:url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport vueJsx from '@vitejs/plugin-vue-jsx'\nimport path, { resolve } from 'path'\nimport glob from 'glob';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [vue(), vueJsx()],\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url))\n }\n },\n build: {\n rollupOptions: {\n input: Object.fromEntries(\n glob.sync(\"src/modules/**/*.html\").map((file:string) => [\n path.relative(\n \"src\",\n file.slice(0, file.length - path.extname(file).length)\n ),\n fileURLToPath(new URL(file, import.meta.url)),\n \n ])\n ),\n output: {\n chunkFileNames: 'assets/js/[name]-[hash].js',\n entryFileNames: 'assets/modules/[name]-[hash].js',\n dir: \"dist\"\n }\n },\n },\n})\n```\n\n========================================\n\nCode:\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <link rel=\"icon\" href=\"/favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>Vite App</title>\n    <script type=\"module\" crossorigin src=\"/assets/modules/modules\\\\VPlayerList\\\\index-74e8dd8e.js\"></script>\n    <link rel=\"modulepreload\" crossorigin href=\"/assets/js/main-a0df4ea4.js\">\n    <link rel=\"stylesheet\" href=\"/assets/main.44382b18.css\">\n  </head>\n  <body>\n    <div id=\"app\"></div>\n    \n  </body>\n</html>\n```\n\n```js\nimport { fileURLToPath, URL } from 'node:url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport vueJsx from '@vitejs/plugin-vue-jsx'\nimport path, { resolve } from 'path'\nimport glob from 'glob';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue(), vueJsx()],\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url))\n    }\n  },\n  build: {\n    rollupOptions: {\n      input: Object.fromEntries(\n        glob.sync(\"src/modules/**/*.html\").map((file:string) => [\n          path.relative(\n            \"src\",\n            file.slice(0, file.length - path.extname(file).length)\n          ),\n          fileURLToPath(new URL(file, import.meta.url)),\n          \n        ])\n      ),\n      output: {\n        chunkFileNames: 'assets/js/[name]-[hash].js',\n        entryFileNames: 'assets/modules/[name]-[hash].js',\n        dir: \"dist\"\n      }\n    },\n  },\n})\n```\n\n```js\nimport { resolve } from 'path';\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\n\nexport default defineConfig({\n  plugins: [react()],\n  base: \"\",\n  build: {\n    rollupOptions: {\n      input: {\n        web: resolve(__dirname, './index_web.html'),\n        mobile: resolve(__dirname, './index_mobile.html'),\n        lite: resolve(__dirname, './index_lite.html'),\n      },\n      output: [\n        {\n          name: \"web\",\n          dir: \"dist_web\",\n        },\n        {\n          name: \"mobile\",\n          dir: \"dist_mobile\",\n        },\n        {\n          name: \"lite\",\n          dir: \"dist_lite\",\n        }\n      ]\n    },\n  },\n});\n```\n\n```json\n{\n  \"name\": \"vite-multiple-build\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build-web\": \"vite build --config vite.config.web.js\",\n    \"build-mobile\": \"vite build --config vite.config.mobile.js\",\n    \"build-lite\": \"vite build --config vite.config.lite.js\",\n    \"preview\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^18.0.24\",\n    \"@types/react-dom\": \"^18.0.8\",\n    \"@vitejs/plugin-react\": \"^2.2.0\",\n    \"vite\": \"^3.2.3\"\n  }\n}\n```\n\n```text\nindex.html\n```\n\n```text\nvite.config.js\n```\n\n```text\ndist\n```\n\n```text\nvite.config.js\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- Please do not upload images of code/data/errors when asking a question.\n- Please see the linked meta post. tl;dr images of code can't be indexed by search engines, they are harder to read, and they can't be copy-pasted. If you change the screenshot with a copy-pasted block of the code shown, then I will happily retract my downvote.\n- @MichaelM. do you want the file structure to be written down as well?\n- No, that is a legitimate reason for using an image. Project structures are not text because they are charts that show connections. Good question.\n- @MichaelM. thank you good sir, so do I kindly ask you do you know any idea how should I proceed?\n- Unfortunately, I am not an expert on this subject matter. However, it is a good question and I have upvoted it to attract more attention. I have also edited it to include relevant tags, so more people will see it and help. Best wishes on fixing the issue.\n- thank you, I will try when I am free, this was one of my side projects =))\n- Sorry, I marked it as answer but forgot to add comment. It worked like a charm. Thank you!! Edit: I added a function to dynmically generate entry points too, I have a folder that holds each page and using the folder name I targeted them as entry point\n- @ Matias Micheletto Have you reached a solution for your statement?: Maybe I'm missing a way to link outputs to inputs","metadata":{"transformedAt":"2026-08-18T18:33:46.412Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":227,"estimatedTokens":1409}}235{"id":"stack-74269160","source":"stackoverflow","questionId":74269160,"title":"how to import google-font with vitejs?","tags":["vite","google-fonts"],"text":"Title: how to import google-font with vitejs?\nTags: vite, google-fonts\nSource: Stack Overflow\n\nQuestion:\nTroubles with google-font & vitejs\n\nI would like to know how to import google-font (or other fonts) for my Vite project, despite Vite has already all config in index.html for css, scss, sass, etc.., but there is nothing about how to configure Vite for google-font. Please, help me. (My config = Vite -> React -> TypeScript -> sass).\n\n========================================\n\nTop Answer:\nSo, you can import the url in your css file(s), it´s so simple:\n\n```\n@import url('https://fonts.googleapis.com/css2family=__CHOSEN_FONT__);\n\nbody{\n font-family: '__CHOSEN_FONT__', sans-serif;\n}\n```\n\n========================================\n\nCode:\n```text\n<link>\n```\n\n```text\n@import url('https://fonts.googleapis.com/css2family=__CHOSEN_FONT__);\n\nbody{\n  font-family: '__CHOSEN_FONT__', sans-serif;\n}\n```\n\n========================================\n\nComments:\n- Yes, Fontsource is great. It's all I use now.\n- Nice! First time I've heard of this site (FontSource). Bookmarked!\n- This will work, but it will cause either delayed loading, or likely a FOUT (Flash of unstyled text) as the font loads and is swapped out. Better to preload the font.","metadata":{"transformedAt":"2026-08-18T18:33:46.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":43,"estimatedTokens":309}}236{"id":"stack-68547439","source":"stackoverflow","questionId":68547439,"title":"assets not showing after build process with vite and vue3","tags":["vue.js","vuejs3","vite"],"text":"Title: assets not showing after build process with vite and vue3\nTags: vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nWhen running `npm run build` my pictures under `src/assets/...` are not available in the dist directory / production build. So not shown on the site. In dev mode it works for sure.\n\nAny ideas how to make them available after building?\n\n========================================\n\nTop Answer:\nVite by default sets the default path to '/', you need to override it to use your project default path for the production build.\n\nGo to your `vite.config.ts` (if you have a JS project instead of TS, it would be `filename.js` instead) and add the `base`; check the example below.\n\n```\nexport default defineConfig({\n plugins: [react()],\n base: '',\n})\n```\n\n========================================\n\nCode:\n```text\nnpm run build\n```\n\n```text\nsrc/assets/...\n```\n\n```text\nsrc/assets\n```\n\n```text\nimport\n```\n\n```text\npublic/\n```\n\n```text\nexport default defineConfig({\n  plugins: [react()],\n  base: '',\n})\n```\n\n```text\nvite.config.ts\n```\n\n```text\nfilename.js\n```\n\n```text\nbase\n```\n\n========================================\n\nComments:\n- The imports must be done for every single file in main,js? Or how should I accomplish this? If I use the public folder it works just fine. But I'm curious.\n- Webpack or equivalent follows all imports and compiles up the resulting files. As a general rule, code goes in src and media in public.\n- The provided link has nothing to do with Vite. Please update to: vitejs.dev/guide/assets.html\n- What does react() do? Links to the appropriate documentation website would be helpful.","metadata":{"transformedAt":"2026-08-18T18:33:46.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":72,"estimatedTokens":406}}237{"id":"stack-71778929","source":"stackoverflow","questionId":71778929,"title":"How to setup PostCSS nesting in Vite?","tags":["vue.js","vuejs3","vite","postcss"],"text":"Title: How to setup PostCSS nesting in Vite?\nTags: vue.js, vuejs3, vite, postcss\nSource: Stack Overflow\n\nQuestion:\nThis is what I’ve tried so far:\n\nInstalled via `npm install postcss-nesting --save-dev`\n\nSetup vite.config.js:\n\n```\nimport { fileURLToPath, URL } from 'url';\nimport { defineConfig } from 'vite';\nimport vue from '@vitejs/plugin-vue';\nimport postcssNesting from 'postcss-nesting';\n\nexport default defineConfig({\n plugins: [\n vue(),\n postcssNesting\n ],\n \n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url))\n }\n }\n});\n```\n\nBut it’s not working. What’s the right way to setup PostCSS so that I can use CSS nesting?\n\n========================================\n\nTop Answer:\nJust create a file on the root of your project called `postcss.config.js`:\n\n```\nmodule.exports = {\n plugins: {\n 'postcss-nesting': { /* plugin options */ },\n },\n}\n```\n\nVite uses postcss-load-config which means that it can pick up the postcss config file (file name can be one of the many formats supported by this package e.g. `postcss.config.js`, `.postcssrc`, `.postcssrc.js` etc).\n\nIf you want nesting with PostCSS just like you do it in SASS, I suggest you use postcss-nested.\n\nIf you want to use it together with TailwindCSS, you don't have to install it since it's included directly in the `tailwindcss` package itself:\n\n```\n// postcss.config.js\nmodule.exports = {\n plugins: {\n 'tailwindcss/nesting': {},\n tailwindcss: {},\n autoprefixer: {},\n }\n}\n```\n\nTailwindDocs: Nesting\n\n========================================\n\nCode:\n```text\nimport { fileURLToPath, URL } from 'url';\nimport { defineConfig } from 'vite';\nimport vue from '@vitejs/plugin-vue';\nimport postcssNesting from 'postcss-nesting';\n\nexport default defineConfig({\n    plugins: [\n        vue(),\n        postcssNesting\n    ],\n  \n    resolve: {\n        alias: {\n            '@': fileURLToPath(new URL('./src', import.meta.url))\n        }\n    }\n});\n```\n\n```text\nnpm install postcss-nesting --save-dev\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport postcssNesting from 'postcss-nesting';\n\nexport default defineConfig({\n    css: {\n        postcss: {\n            plugins: [\n                postcssNesting\n            ],\n        },\n    },\n});\n```\n\n```js\nmodule.exports = {\n  plugins: {\n    'postcss-nesting': { /* plugin options */ },\n  },\n}\n```\n\n```js\n// postcss.config.js\nmodule.exports = {\n  plugins: {\n    'tailwindcss/nesting': {},\n    tailwindcss: {},\n    autoprefixer: {},\n  }\n}\n```\n\n```text\npostcss.config.js\n```\n\n```text\npostcss.config.js\n```\n\n```text\n.postcssrc\n```\n\n```text\n.postcssrc.js\n```\n\n```text\ntailwindcss\n```\n\n========================================\n\nComments:\n- It's confusing how some plugins need paranthesis (e.g. `tailwind()`) and some don't\n- Somewhat related: Is there a way to then configure vite to not extract the CSS? stackoverflow.com/questions/58858580/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:46.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":151,"estimatedTokens":717}}238{"id":"stack-79498214","source":"stackoverflow","questionId":79498214,"title":"How to fix Tailwind PostCSS plugin error?","tags":["reactjs","tailwind-css","vite","postcss","tailwind-css-4"],"text":"Title: How to fix Tailwind PostCSS plugin error?\nTags: reactjs, tailwind-css, vite, postcss, tailwind-css-4\nSource: Stack Overflow\n\nQuestion:\nNot one LLM was able to help me fix this issue, so here I am. I'm building a Vite + React + TS project and it fails to build because of this error: [plugin:vite:css] [postcss] It looks like you're trying to use `tailwindcss` directly as a PostCSS plugin. The PostCSS plugin has moved to a separate package, so to continue using Tailwind CSS with PostCSS you'll need to install `@tailwindcss/postcss` and update your PostCSS configuration. The first one is a\n\nI have tried:\n\n- uninstalling tailwindcss/postcss\nreconfiguring the plugin array inside postcss from\n`require('tailwindcss') to require('@tailwindcss/postcss')`\n\n- adding import @tailwindcss to my global css\n\nMy PostCSS file\n\n```\nplugins: {\n '@tailwindcss/postcss': {},\n autoprefixer: {},\n },\n}\n```\n\nMy Vite file\n\n```\nimport react from '@vitejs/plugin-react'\nimport tailwindcss from '@tailwindcss/vite'\n\n// https://vite.dev/config/\nexport default defineConfig({\n plugins: [\n react(),\n tailwindcss(),\n ],\n})\n```\n\nmy index.css (snippet)\n\n```\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n@layer base {\n html {\n```\n\nAppreciate any help\n\n========================================\n\nTop Answer:\nYou seem to be using some v3 configs with some v4 configs at the same time.\n\nConsidering you want to use latest tailwindcss v4 with vite, you do not need to handle PostCSS manually.\n\nUninstall PostCSS, delete the PostCSS file and the steps here.\n\nYour vite file seems to be correct.\n\nYour index.css can lose the old v3 @tailwind directives in favour of the new @import \"tailwindcss\";\n\n========================================\n\nCode:\n```none\nplugins: {\n    '@tailwindcss/postcss': {},\n    autoprefixer: {},\n  },\n}\n```\n\n```none\nimport react from '@vitejs/plugin-react'\nimport tailwindcss from '@tailwindcss/vite'\n\n// https://vite.dev/config/\nexport default defineConfig({\n  plugins: [\n    react(),\n    tailwindcss(),\n  ],\n})\n```\n\n```text\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n\n@layer base {\n  html {\n```\n\n```text\ntailwindcss\n```\n\n```text\n@tailwindcss/postcss\n```\n\n```text\nrequire('tailwindcss') to require('@tailwindcss/postcss')\n```\n\n```css\n@import \"tailwindcss\";\n```\n\n```text\nnpm install -D tailwindcss@3\n```\n\n```text\n@tailwindcss/vite\n```\n\n```text\n@tailwind\n```\n\n========================================\n\nComments:\n- What's your TailwindCSS version? It looks like you're trying to install v4 based on v3 practices, using the new `@tailwindcss&#47;postcss` and `@tailwindcss&#47;vite` packages created for v4. These two packages can only be used with v4. In TailwindCSS v3, PostCSS support was still implemented directly, and Vite support didn’t even exist yet. Read more in my answer.\n- I'm using Tailwind v4 (@tailwindcss/vite@4.0.12 @tailwindcss/node@4.0.12/ tailwindcss@4.0.12)\n- Well, if you really want to use v4, just my answer and integrate it with Vite using the steps I've outlined. One very important change is that the `tailwind.config.js` file is gone, and instead, a CSS-first configuration has been introduced. The `@tailwind` directive (which you're using) has been removed, and instead, they introduced `@import \"tailwindcss\"`. I really tried to provide sources for everything in my answer.\n- I did the following for v4, installed tailwindcss and @tailwindcss/vite via npm, added @tailwindcss/vite plugin to my vite.config, and used @import \"tailwindcss\" for my CSS. The error persisted, but let me go through your answer in detail.\n- Starting from v4, TailwindCSS can communicate directly with Vite through the @tailwindcss/vite plugin, so you no longer need PostCSS. Also, you no longer need autoprefixer, as it has been integrated into v4. --- So, delete the `postcss.config.js` file. Everything you've done is correct. Now, just remove the 3 `@tailwind` lines from your CSS file and replace them with: `@import \"tailwindcss\"`;\n- More example: From this answer can read \"TailwindCSS v4\" section or can read How can I integrate TailwindCSS for React project with Vite?\n- It worked! Thank you so much.","metadata":{"transformedAt":"2026-08-18T18:33:46.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":138,"estimatedTokens":1036}}239{"id":"stack-74390015","source":"stackoverflow","questionId":74390015,"title":"How to do multiple bundles with vite?","tags":["reactjs","webpack","vite","rollup","esbuild"],"text":"Title: How to do multiple bundles with vite?\nTags: reactjs, webpack, vite, rollup, esbuild\nSource: Stack Overflow\n\nQuestion:\nUsing vite js to bundle my library, I need to provide two versions at the same time:\n\n- production usage\n\n- development specific code and warnings with devtools integration.\n\nWhen I was using webpack, I had:\n\n```\nmodule.exports = [\n defaultUmdBuild(\"production\"),\n defaultUmdBuild(\"development\"),\n];\n```\n\nwhich outputs two files and then I have this entrypoint to my library:\n\n```\n'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./mylib.production.js');\n} else {\n module.exports = require('./mylib.development.js');\n}\n```\n\nHow to do the same using vite ?\n\nThanks.\n\n========================================\n\nTop Answer:\nI think you can achieve this using vite modes.\n\nRun the build command using different modes:\n\n```\nvite build --mode production #default\nvite build --mode development\n```\n\nIn your vite.config file you can then have different build configurations based on the mode value.\n\n```\n// vite.config.js\nimport { defineConfig } from 'vite';\n\nexport default defineConfig(({ mode }) => {\n if (mode === 'production') {\n return {\n // ...\n build: {\n outDir: 'build_production'\n }\n }\n }\n\n if (mode === 'development') {\n return {\n // ...\n build: {\n outDir: 'build_development'\n }\n }\n }\n return {}\n});\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = [\n  defaultUmdBuild(\"production\"),\n  defaultUmdBuild(\"development\"),\n];\n```\n\n```text\n'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n  module.exports = require('./mylib.production.js');\n} else {\n  module.exports = require('./mylib.development.js');\n}\n```\n\n```json\n\"build\": \"tsc && vite build --config vite.config.lib.dev.ts && vite build --config vite.config.lib.prod.ts\"\n```\n\n```text\npackage.json\n```\n\n```bash\nvite build --mode production #default\nvite build --mode development\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite';\n\nexport default defineConfig(({ mode }) => {\n  if (mode === 'production') {\n    return {\n      // ...\n      build: {\n        outDir: 'build_production'\n      }\n    }\n  }\n\n  if (mode === 'development') {\n    return {\n      // ...\n      build: {\n        outDir: 'build_development'\n      }\n    }\n  }\n  return {}\n});\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite';\nimport { build } from 'vite';\n\nawait build(defineConfig({\n  build: {\n    rolldownOptions: {\n      // options for build target #1\n    }\n  }\n}));\n\nexport default defineConfig({\n  build: {\n    rolldownOptions: {\n      // options for build target #2\n    }\n  }\n});\n```\n\n========================================\n\nComments:\n- I appreciate your answer, thanks a lot. But I need in a single run to execute two build jobs, each one with different value for the mode variable. I can easily achieve this with rollup and/or webpack. I think I ll stick to them for now.\n- Does not work because vite clears the directory before each build\n- Sure it will if you tell vite not to remove it. emptyDir was the prop name i guess.\n- You should use || instead of && otherwise Vite will clean up the first file.","metadata":{"transformedAt":"2026-08-18T18:33:46.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":164,"estimatedTokens":793}}240{"id":"stack-77593613","source":"stackoverflow","questionId":77593613,"title":"'Vite. http proxy error at /weatherforecast...' error when launching the Angular and ASP.NET Core app in Visual Studio","tags":[".net","angular","visual-studio","vite","visual-studio-2022"],"text":"Title: 'Vite. http proxy error at /weatherforecast...' error when launching the Angular and ASP.NET Core app in Visual Studio\nTags: .net, angular, visual-studio, vite, visual-studio-2022\nSource: Stack Overflow\n\nQuestion:\nI created an app from the 'Angular with ASP.NET Core' project template in Visual Studio 2022 17.8 and .NET 8. It launches the API app in Chrome and the Angular app in Edge. In Edge it doesn't show the weather temperature values. I see the error below in the console. The app used to work but then I tried to make Chrome the default browser for the Angular app and it never properly anymore. I made Edge the default browser for the Angular project. I also deleted and recreated the app several times and it never worked correctly anymore. Using Node 20 and Angular 17.\n\nWhat could be the issue? I don't know much about Vite and how it relates to the reverse proxy in ASP.NET.\n\n**Error:**\n\n[vite] http proxy error at /weatherforecast: AggregateError\nat internalConnectMultiple (node:net:1114:18)\nat afterConnectMultiple (node: net: 1667:5)\n\nhttps://i.sstatic.net/WXnZr.png\n\n========================================\n\nTop Answer:\n[vite] http proxy error at /weatherforecast: AggregateError at internalConnectMultiple (node:net:1114:18) at afterConnectMultiple (node: net: 1667:5)\n\nThe reason is that the client loads faster than the server. Right click the server project, and execute debug from there, and see if you still get the error.\n\nIn Edge it doesn't show the weather temperature values.\n\nIt actually does show the values, however, the color of the font is silver, and is semi transparent. Click down, and drag your mouse over the weather table.\n\n========================================\n\nCode:\n```js\nserver: {\n    port: 5176,    \n    proxy: {\n      '/api': {\n        target: 'http://localhost',\n        changeOrigin: true,\n        secure: false,\n        ws: false\n      },\n      '/PluginsAPI': {\n        target: 'https://localhost:55434/',\n        changeOrigin: true,\n        secure: false,\n        ws: false\n      },\n```\n\n```js\nconst PROXY_CONFIG = [\n  {\n    context: [\n      \"/weatherforecast\",\n    ],\n    target: \"https://localhost:40443\",   //**\n    secure: false\n  }\n]\n```\n\n```json\n\"https\": {\n  \"commandName\": \"Project\",\n  \"dotnetRunMessages\": true,\n  \"launchBrowser\": false,\n  \"launchUrl\": \"swagger\",\n  \"applicationUrl\": \"https://localhost:40443;http://localhost:40080\",  //**\n  \"environmentVariables\": {\n    \"ASPNETCORE_ENVIRONMENT\": \"Development\",\n    \"ASPNETCORE_HOSTINGSTARTUPASSEMBLIES\": \"Microsoft.AspNetCore.SpaProxy\"\n  }\n}\n```\n\n```html\nconst target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :\n  env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'https://localhost:32775';\n```\n\n========================================\n\nComments:\n- I had the same issue when using the Docker support option for this template - using the template without Docker support fixed this issue for me\n- lol this answer made me chuckle, typical MS for not thinking of these things LOL\n- Windows is not case sensitive.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:46.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":87,"estimatedTokens":839}}241{"id":"stack-67031295","source":"stackoverflow","questionId":67031295,"title":"How to open a static website in localhost but generated with Vite and without running a server?","tags":["typescript","vuejs3","vite","primevue"],"text":"Title: How to open a static website in localhost but generated with Vite and without running a server?\nTags: typescript, vuejs3, vite, primevue\nSource: Stack Overflow\n\nQuestion:\nNote: the example I'm using is available on GitHub repository https://github.com/mary-perret-1986/primevue-poc\n\nI created a simple project with Vue.js 3 + Vite + PrimeVue.\n\nSo far everything works like a charm when I'm developping and if I'm serving the build (i.e. `/dist`) with a server.\n\nBut I wanted to see if I could open the `/dist/index.html` directly from my browser... I mean it should be possible, technically-speaking.\n\nHere are below the bits of configuration:\n\n`package.json`\n\n```\n{\n \"name\": \"my-vue-app\",\n \"version\": \"0.0.0\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"preview\": \"vite build && vite preview\"\n },\n \"dependencies\": {\n \"primeflex\": \"^2.0.0\",\n \"primeicons\": \"^4.1.0\",\n \"primevue\": \"^3.2.0-rc.1\",\n \"vue\": \"^3.0.5\",\n \"vue-property-decorator\": \"^9.1.2\",\n \"vue-class-component\": \"^8.0.0-0\",\n \"vue-router\": \"^4.0.0-0\",\n \"vuex\": \"^4.0.0-0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^14.14.37\",\n \"@vitejs/plugin-vue\": \"^1.2.1\",\n \"@vue/compiler-sfc\": \"^3.0.5\",\n \"sass\": \"^1.26.5\",\n \"typescript\": \"^4.1.3\",\n \"vite\": \"^2.1.5\",\n \"vue-tsc\": \"^0.0.15\"\n }\n}\n```\n\n`vite.config.ts`:\n\n```\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [vue()],\n server: {\n open: true,\n },\n build: {},\n resolve: {\n alias: [\n { find: '@', replacement: '/src' },\n { find: 'views', replacement: '/src/views' },\n { find: 'components', replacement: '/src/components' },\n ]\n },\n define: {\n 'process.env': process.env\n }\n})\n```\n\nInstall packages work fine:\n\n```\n$ yarn\nyarn install v1.22.10\nwarning package-lock.json found. Your project contains lock files generated by tools other than Yarn. It is advised not to mix \npackage managers in order to avoid resolution inconsistencies caused by unsynchronized lock files. To clear this warning, remove package-lock.json.\n[1/4] Resolving packages...\nsuccess Already up-to-date.\nDone in 0.17s.\n```\n\nDevelopping as well:\n\n```\n$ yarn dev\nyarn run v1.22.10\n$ vite\nPre-bundling dependencies:\n vue\n primevue/config\n vuex\n vue-router\n vue-class-component\n (...and 1 more)\n(this will be run only when your dependencies or config have changed)\n\n vite v2.1.5 dev server running at:\n\n > Network: http://192.168.0.10:3000/\n > Local: http://localhost:3000/ \n > Network: http://172.17.128.1:3000/\n\n ready in 632ms.\n```\n\nChecking with the preview server the build, works as well:\n\n```\n$ yarn preview\nyarn run v1.22.10\n$ vite build && vite preview\nvite v2.1.5 building for production...\n✓ 34 modules transformed.\ndist/assets/logo.03d6d6da.png 6.69kb\ndist/assets/primeicons.7362b83d.eot 56.21kb\ndist/assets/color.473bc8ca.png 10.11kb\ndist/assets/roboto-v20-latin-ext_latin-regular.b86b128b.woff2 22.11kb\ndist/assets/roboto-v20-latin-ext_latin-500.fa074f87.woff2 22.20kb\ndist/assets/roboto-v20-latin-ext_latin-700.8d9364a0.woff2 22.19kb\ndist/assets/roboto-v20-latin-ext_latin-regular.e70a908b.woff 28.36kb\ndist/assets/primeicons.c1e93246.ttf 56.04kb\ndist/assets/roboto-v20-latin-ext_latin-500.d092ad8e.woff 28.39kb\ndist/assets/roboto-v20-latin-ext_latin-700.e24c2752.woff 28.41kb\ndist/assets/primeicons.3929b551.woff 56.11kb\ndist/assets/primeicons.8f9d2aaf.svg 229.14kb\ndist/index.html 0.47kb\ndist/assets/About.17af8924.js 0.19kb / brotli: 0.14kb\ndist/assets/index.e5d45779.js 3.63kb / brotli: 1.52kb\ndist/assets/vendor.9f2b5e0c.js 90.90kb / brotli: 29.73kb\ndist/assets/index.6f411dd0.css 226.74kb / brotli: 20.14kb\n\n vite v2.1.5 build preview server running at:\n\n > Network: http://192.168.0.10:5000/\n > Local: http://localhost:5000/\n > Network: http://172.17.128.1:5000/\n```\n\nThe issue arises when I'm willing to open my build without a server, which by all accounts should be doable, except that when I'm opening the `/dist/index.html`, the console is shouting at me:\n\n```\nindex.html:1 Access to script at 'file:///C:/assets/vendor.9f2b5e0c.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted.\nindex.html:9 GET file:///C:/assets/vendor.9f2b5e0c.js net::ERR_FAILED\nindex.html:1 Access to script at 'file:///C:/assets/index.6aa5dbbe.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted.\nindex.html:8 GET file:///C:/assets/index.6aa5dbbe.js net::ERR_FAILED\nindex.html:10 GET file:///C:/assets/index.96fff16b.css net::ERR_FILE_NOT_FOUND\n/C:/favicon.ico:1 GET file:///C:/favicon.ico net::ERR_FILE_NOT_FOUND\n```\n\nLooking at the context of the newly built `/dist/index.html`:\n\n```\n\n \n \n \n \n Vite App\n \n \n\n \n \n \n \n\n```\n\nI've checked this part of the Vite documentation https://vitejs.dev/guide/static-deploy.html, but still can't manage to have a real old-fashioned build that doesn't require a server.\n\nAny idea?\n\n========================================\n\nTop Answer:\nTo do this with vite on-board tools set\n\n```\nbase: \"./\"\n```\n\nin your vite config or build with\n\n```\nvite build --base=\"./\"\n```\n\n### base**​**\n\nType: `string` Default: `/`\n\nBase public path when served in development or production. Valid values include:\n\nAbsolute URL pathname, e.g. `/example/`\n\nFull URL, e.g. `https://example.com/`\n\n**Empty string or `./` (for embedded deployment)**\n\n### Public Base Path​\n\nIf you are deploying your project under a nested public path, simply specify the `base` config option and all asset paths will be rewritten accordingly. This option can also be specified as a command line flag, e.g. `vite build --base=/my/public/path/`.\n\nJS-imported asset URLs, CSS `url()` references, and asset references in your `.html` files are all automatically adjusted to respect this option during build.\n\nThe exception is when you need to dynamically concatenate URLs on the fly. In this case, you can use the globally injected `import.meta.env.BASE_URL` variable which will be the public base path. Note this variable is statically replaced during build so it must appear exactly as-is (i.e. `import.meta.env['BASE_URL']` won't work).\n\nRelated: **Asset Handling**\n\n========================================\n\nCode:\n```json\n{\n  \"name\": \"my-vue-app\",\n  \"version\": \"0.0.0\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"preview\": \"vite build && vite preview\"\n  },\n  \"dependencies\": {\n    \"primeflex\": \"^2.0.0\",\n    \"primeicons\": \"^4.1.0\",\n    \"primevue\": \"^3.2.0-rc.1\",\n    \"vue\": \"^3.0.5\",\n    \"vue-property-decorator\": \"^9.1.2\",\n    \"vue-class-component\": \"^8.0.0-0\",\n    \"vue-router\": \"^4.0.0-0\",\n    \"vuex\": \"^4.0.0-0\"\n  },\n  \"devDependencies\": {\n    \"@types/node\": \"^14.14.37\",\n    \"@vitejs/plugin-vue\": \"^1.2.1\",\n    \"@vue/compiler-sfc\": \"^3.0.5\",\n    \"sass\": \"^1.26.5\",\n    \"typescript\": \"^4.1.3\",\n    \"vite\": \"^2.1.5\",\n    \"vue-tsc\": \"^0.0.15\"\n  }\n}\n```\n\n```json\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue()],\n  server: {\n    open: true,\n  },\n  build: {},\n  resolve: {\n    alias: [\n      { find: '@', replacement: '/src' },\n      { find: 'views', replacement: '/src/views' },\n      { find: 'components', replacement: '/src/components' },\n    ]\n  },\n  define: {\n    'process.env': process.env\n  }\n})\n```\n\n```sh\n$ yarn\nyarn install v1.22.10\nwarning package-lock.json found. Your project contains lock files generated by tools other than Yarn. It is advised not to mix \npackage managers in order to avoid resolution inconsistencies caused by unsynchronized lock files. To clear this warning, remove package-lock.json.\n[1/4] Resolving packages...\nsuccess Already up-to-date.\nDone in 0.17s.\n```\n\n```sh\n$ yarn dev\nyarn run v1.22.10\n$ vite\nPre-bundling dependencies:\n  vue\n  primevue/config\n  vuex\n  vue-router\n  vue-class-component\n  (...and 1 more)\n(this will be run only when your dependencies or config have changed)\n\n  vite v2.1.5 dev server running at:\n\n  > Network:  http://192.168.0.10:3000/\n  > Local:    http://localhost:3000/   \n  > Network:  http://172.17.128.1:3000/\n\n  ready in 632ms.\n```\n\n```sh\n$ yarn preview\nyarn run v1.22.10\n$ vite build && vite preview\nvite v2.1.5 building for production...\n✓ 34 modules transformed.\ndist/assets/logo.03d6d6da.png                                   6.69kb\ndist/assets/primeicons.7362b83d.eot                             56.21kb\ndist/assets/color.473bc8ca.png                                  10.11kb\ndist/assets/roboto-v20-latin-ext_latin-regular.b86b128b.woff2   22.11kb\ndist/assets/roboto-v20-latin-ext_latin-500.fa074f87.woff2       22.20kb\ndist/assets/roboto-v20-latin-ext_latin-700.8d9364a0.woff2       22.19kb\ndist/assets/roboto-v20-latin-ext_latin-regular.e70a908b.woff    28.36kb\ndist/assets/primeicons.c1e93246.ttf                             56.04kb\ndist/assets/roboto-v20-latin-ext_latin-500.d092ad8e.woff        28.39kb\ndist/assets/roboto-v20-latin-ext_latin-700.e24c2752.woff        28.41kb\ndist/assets/primeicons.3929b551.woff                            56.11kb\ndist/assets/primeicons.8f9d2aaf.svg                             229.14kb\ndist/index.html                                                 0.47kb\ndist/assets/About.17af8924.js                                   0.19kb / brotli: 0.14kb\ndist/assets/index.e5d45779.js                                   3.63kb / brotli: 1.52kb\ndist/assets/vendor.9f2b5e0c.js                                  90.90kb / brotli: 29.73kb\ndist/assets/index.6f411dd0.css                                  226.74kb / brotli: 20.14kb\n\n  vite v2.1.5 build preview server running at:\n\n  > Network:  http://192.168.0.10:5000/\n  > Local:    http://localhost:5000/\n  > Network:  http://172.17.128.1:5000/\n```\n\n```sh\nindex.html:1 Access to script at 'file:///C:/assets/vendor.9f2b5e0c.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted.\nindex.html:9 GET file:///C:/assets/vendor.9f2b5e0c.js net::ERR_FAILED\nindex.html:1 Access to script at 'file:///C:/assets/index.6aa5dbbe.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted.\nindex.html:8 GET file:///C:/assets/index.6aa5dbbe.js net::ERR_FAILED\nindex.html:10 GET file:///C:/assets/index.96fff16b.css net::ERR_FILE_NOT_FOUND\n/C:/favicon.ico:1 GET file:///C:/favicon.ico net::ERR_FILE_NOT_FOUND\n```\n\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <link rel=\"icon\" href=\"/favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>Vite App</title>\n  <script type=\"module\" crossorigin src=\"/assets/index.7ed2b14a.js\"></script>\n  <link rel=\"modulepreload\" href=\"/assets/vendor.9f2b5e0c.js\">\n<link rel=\"stylesheet\" href=\"/assets/style.5b5d95b2.css\">\n</head>\n  <body>\n    <div id=\"app\"></div>\n    \n  </body>\n</html>\n```\n\n```text\n/dist\n```\n\n```text\n/dist/index.html\n```\n\n```text\npackage.json\n```\n\n```text\nvite.config.ts\n```\n\n```text\n/dist/index.html\n```\n\n```text\n/dist/index.html\n```\n\n```json\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport { viteSingleFile } from \"vite-plugin-singlefile\"\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue(), viteSingleFile()],\n    build: {\n        cssCodeSplit: false,\n        assetsInlineLimit: 100000000,\n        rollupOptions: {\n            output: {\n                manualChunks: () => \"everything.js\",\n            },\n        },\n    },\n  resolve: {\n    alias: [\n      { find: '@', replacement: '/src' },\n      { find: 'views', replacement: '/src/views' },\n      { find: 'components', replacement: '/src/components' },\n    ]\n  },\n  server: {\n    open: true,\n  },\n  define: {\n    'process.env': process.env\n  }\n})\n```\n\n```json\n{\n  \"name\": \"my-vue-app\",\n  \"version\": \"0.0.0\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"preview\": \"vite build && vite preview\",\n    \"inlined-build\": \"vite build --config vite.config.inlined.ts\",\n    \"inlined-preview\": \"vite build --config vite.config.inlined.ts && start ./dist/index.html\"\n  },\n  \"dependencies\": {\n    \"primeflex\": \"^2.0.0\",\n    \"primeicons\": \"^4.1.0\",\n    \"primevue\": \"^3.2.0-rc.1\",\n    \"vue\": \"^3.0.5\",\n    \"vue-class-component\": \"^8.0.0-0\",\n    \"vue-property-decorator\": \"^9.1.2\",\n    \"vue-router\": \"^4.0.0-0\",\n    \"vuex\": \"^4.0.0-0\"\n  },\n  \"devDependencies\": {\n    \"@types/node\": \"^14.14.37\",\n    \"@vitejs/plugin-vue\": \"^1.2.1\",\n    \"@vue/compiler-sfc\": \"^3.0.5\",\n    \"sass\": \"^1.26.5\",\n    \"typescript\": \"^4.1.3\",\n    \"vite\": \"^2.1.5\",\n    \"vite-plugin-singlefile\": \"^0.5.1\",\n    \"vue-tsc\": \"^0.0.15\"\n  }\n}\n```\n\n```sh\n$ yarn inlined-preview\nyarn run v1.22.10\n$ vite build --config vite.config.inlined.ts && start ./dist/index.html\nvite v2.1.5 building for production...\n✓ 34 modules transformed.\ndist/assets/primeicons.8f9d2aaf.svg   229.14kb\ndist/index.html                       845.29kb\ndist/assets/style.d35cde0e.css        741.65kb / brotli: skipped (large chunk)\ndist/assets/index.dbc56441.js         103.16kb / brotli: 37.49kb\nDone in 6.63s.\n```\n\n```text\nvite.config.inlined.ts\n```\n\n```text\npackage.json\n```\n\n```text\nbase: \"./\"\n```\n\n```text\nvite build --base=\"./\"\n```\n\n```text\nstring\n```\n\n```text\n/\n```\n\n```text\n/example/\n```\n\n```text\nhttps://example.com/\n```\n\n```text\n./\n```\n\n```text\nbase\n```\n\n```text\nvite build --base=/my/public/path/\n```\n\n```text\nurl()\n```\n\n```text\n.html\n```\n\n```text\nimport.meta.env.BASE_URL\n```\n\n```text\nimport.meta.env['BASE_URL']\n```\n\n========================================\n\nComments:\n- Read books about HTTP. You need *some* server. You could code one with some HTTP server library like libonion\n- @BasileStarynkevitch based on what premise? Didn't need one with angular, why would that be the case with a simple static output?\n- @BasileStarynkevitch I managed to make it work, fyi, my solution is below.\n- Similar questions for self contained embeddings in the 'ghost' CMS\n- @cachius at the time of writing this comment, my question was asked 2 years and 1 month ago, the question you're mentioning was asked 12 months. It seems I have somehow some sort of precedence over it and not the other way around (if that's what you were implying).\n- @NataliePerret No offense, I mentioned them to link this canonical post. :-)","metadata":{"transformedAt":"2026-08-18T18:33:46.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":536,"estimatedTokens":3639}}242{"id":"stack-76651502","source":"stackoverflow","questionId":76651502,"title":"Unable to vite build for production in Laravel","tags":["laravel","vite","laravel-livewire"],"text":"Title: Unable to vite build for production in Laravel\nTags: laravel, vite, laravel-livewire\nSource: Stack Overflow\n\nQuestion:\nI have a Laravel + Livewire app, that I'm trying to build for production.\n\nI can successfully run `./vendor/bin/sail npm run build`:\n\n```\n./vendor/bin/sail npm run build\n\n> build\n> vite build\n\nvite v3.2.7 building for production...\ntransforming (19) node_modules/axios/lib/helpers/buildURL.js\n🌼 daisyUI components 2.52.0 https://daisyui.com\n ✔︎ Including: base, components, 2 themes, utilities\n ❤︎ Support daisyUI: https://opencollective.com/daisyui \n \n✓ 60 modules transformed.\npublic/build/manifest.json 0.25 KiB\npublic/build/assets/app.bf5ec64f.css 80.27 KiB / gzip: 12.73 KiB\npublic/build/assets/app.8c40d1a4.js 143.69 KiB / gzip: 51.52 KiB\n```\n\nThe assets are loaded in a blade layout using the @vite directive:\n\n```\n...\n{{-- Scripts --}}\n@vite(['resources/css/app.css', 'resources/js/app.js'])\n...\n```\n\nHowever when I view the page source, I can see it still references port 5173 (which would be the vite dev server):\n\n```\n\n```\n\nI was expecting to see a reference to `public/build/assets/...`\n\nMy vite.config.js is fairly simple:\n\n```\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\n\nexport default defineConfig({\n plugins: [\n laravel({\n input: [\n 'resources/css/app.css',\n 'resources/js/app.js',\n ],\n refresh: true,\n }),\n ],\n server: {\n hmr: {\n host: 'localhost',\n },\n }\n});\n```\n\nThe documents (https://laravel.com/docs/10.x/vite#loading-your-scripts-and-styles) says that:\n\n\"In build mode, the directive will load your compiled and versioned assets, including any imported CSS.\"\n\n...but it does not appear to be doing that.\n\nHow do I stop the @vite directive / vite from trying to use the vite dev server, and use the compiled assets? (As obviously, the vite server won't be running in prod).\n\nI've tried `APP_DEBUG=false` and `APP_ENV=prod` in my .env, and `./vendor/bin/sail artisan view:clear` which makes no difference.\n\nDeps are up to date: \"laravel/framework\": \"^10.0\", and \"vite\": \"^3.2.7\" (currently 4.4.2).\n\n========================================\n\nCode:\n```text\n./vendor/bin/sail npm run build\n\n> build\n> vite build\n\nvite v3.2.7 building for production...\ntransforming (19) node_modules/axios/lib/helpers/buildURL.js\n🌼 daisyUI components 2.52.0  https://daisyui.com\n  ✔︎ Including:  base, components, 2 themes, utilities\n  ❤︎ Support daisyUI:  https://opencollective.com/daisyui \n  \n✓ 60 modules transformed.\npublic/build/manifest.json             0.25 KiB\npublic/build/assets/app.bf5ec64f.css   80.27 KiB / gzip: 12.73 KiB\npublic/build/assets/app.8c40d1a4.js    143.69 KiB / gzip: 51.52 KiB\n```\n\n```text\n...\n{{-- Scripts --}}\n@vite(['resources/css/app.css', 'resources/js/app.js'])\n...\n```\n\n```text\n<script type=\"module\" src=\"http://localhost:5173/@vite/client\"></script><link rel=\"stylesheet\" href=\"http://localhost:5173/resources/css/app.css\" /><script type=\"module\" src=\"http://localhost:5173/resources/js/app.js\"></script>\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\n\nexport default defineConfig({\n    plugins: [\n        laravel({\n            input: [\n                'resources/css/app.css',\n                'resources/js/app.js',\n            ],\n            refresh: true,\n        }),\n    ],\n    server: {\n        hmr: {\n            host: 'localhost',\n        },\n    }\n});\n```\n\n```text\n./vendor/bin/sail npm run build\n```\n\n```text\npublic/build/assets/...\n```\n\n```text\nAPP_DEBUG=false\n```\n\n```text\nAPP_ENV=prod\n```\n\n```text\n./vendor/bin/sail artisan view:clear\n```\n\n```text\n./public/hot\n```\n\n```text\nvendor/laravel/framework/src/Illuminate/Foundation/Vite.php\n```\n\n```text\n./public/hot\n```\n\n========================================\n\nComments:\n- I normally do `npm run build` in root folder, and I don't have error.. try like this without using sail\n- Tried `npm run build` in root folder / outside of sail - still no difference.\n- It is true. I was looking for this for hours until after deleting the hot file, it now reads the sources from the build folder.\n- Oh dear... The file appeared persistent after running `vite build --watch` in Docker and stopping the container. It's probably so that the process inside the container did not trap its stopping completely: github.com/vitejs/vite/blob/v5.0.10/packages/vite/src/node/&hellip;\n- Thank you so much. Saved my day with removing hot file\n- you are a life saver, I wasted so much time to figure out how to fix this. the worst part was I didn't know the production website was broken for several hours because it actually worked for myself because it would just load the files from my local vite server but everyone else not so much\n- This is gold. Thank you sincerely. This positively should be mentioned in Laravel's deployment guide. laravel.com/docs/master/deployment\n- I had same problem - contents of hot file were http://[::1]:5173 . I was also looking for the answer for hours.\n- This can happen if you accidentally publish the \"hot\" file to production server.\n- OMG! This was so painful. Thank you. Saved me hours.\n- this is a bug.. Which code and when is responsible for deleting this `hot` , i lost couple of hours :|\n- What a shame! No where this is documented.\n- this is helpfull. I was so painful to find the solution. Thank you.","metadata":{"transformedAt":"2026-08-18T18:33:46.412Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":182,"estimatedTokens":1332}}243{"id":"stack-73862386","source":"stackoverflow","questionId":73862386,"title":"How do I compile web workers with vue3+vite?","tags":["vuejs3","web-worker","vite"],"text":"Title: How do I compile web workers with vue3+vite?\nTags: vuejs3, web-worker, vite\nSource: Stack Overflow\n\nQuestion:\nI have a simple Web Worker which executes a initiates and handles messages from a websocket. The logic for the handler is imported from another module \"MessageHandler\". The reason for this is that the websockets rely on an external dependency (stompjs) anyway, and I would like to keep a single module with the message hangling logic for browsers which don't support webworkers.\n\n```\nimport { connect, destroy } from \"../src/utilities/MessageHandler\";\n\nonmessage = (message) => {\n const {type, value} = message.data;\n switch (type?.toLowerCase()) {\n case \"connect\":\n connect(value, message => postMessage(message))\n break;\n case \"destroy\":\n destroy();\n break;\n }\n}\n```\n\nOn the Dev server, this works fine, and I can place the file in the public folder, and start the Worker with:\n\n```\nif (typeof Worker !== \"undefined\") {\n const workerUrl = new URL(\"/worker.js\", import.meta.url);\n const worker = new Worker(workerUrl, {type:\"module\"});\n console.log(workerUrl);\n worker.postMessage({type:\"connect\", value: {...channelInfo}},);\n worker.onmessage = combineValues;\n onUnmounted(() => {\n worker.postMessage({type:\"destroy\"},);\n worker.terminate();\n })\n } else {\n console.log(\"Workers not allowed. Reverting to single threaded application.\");\n connect(channelInfo, combineValues)\n onUnmounted(() => destroy())\n }\n```\n\nHowever when I build for production, the import from MessageHandler is not compiled into the worker file, and the program fails to execute. Is there a way to configure vite to bundle this web worker properly without having to manually copy all of the dependencies into the file, and does the WW file have to remain in the public folder? Bonus points if there is a way to do it using typescript for the Worker file instead of being forced back to JS.\n\n========================================\n\nTop Answer:\nWhile the accepted answer is working well, vite provides an easier way to import workers using query suffix `?worker`.\n\nExample:\n\n```\nimport MyWorker from './worker?worker'\n\nconst worker = new MyWorker()\n```\n\nThis is more useful for a number of reasons:\n\n- You don't need to put your worker script in `public` folder. Instead you can include it in `src` folder.\n\n- You can use aliases. For example if have `@` pointing to `src` folder, so you do `import MyWorker from '@/worker?worker'`.\n\n- If you use typescript in your vue project, you can use a typescript worker as well without the need to compile it separately.\n\nMore info: https://vitejs.dev/guide/features.html#web-workers\n\n========================================\n\nCode:\n```js\nimport { connect, destroy } from \"../src/utilities/MessageHandler\";\n\nonmessage = (message) => {\n  const {type, value} = message.data;\n  switch (type?.toLowerCase()) {\n    case \"connect\":\n      connect(value, message => postMessage(message))\n      break;\n    case \"destroy\":\n      destroy();\n      break;\n  }\n}\n```\n\n```js\nif (typeof Worker !== \"undefined\") {\n    const workerUrl = new URL(\"/worker.js\", import.meta.url);\n    const worker = new Worker(workerUrl, {type:\"module\"});\n    console.log(workerUrl);\n    worker.postMessage({type:\"connect\", value: {...channelInfo}},);\n    worker.onmessage = combineValues;\n    onUnmounted(() => {\n      worker.postMessage({type:\"destroy\"},);\n      worker.terminate();\n    })\n  } else {\n    console.log(\"Workers not allowed. Reverting to single threaded application.\");\n    connect(channelInfo, combineValues)\n    onUnmounted(() => destroy())\n  }\n```\n\n```js\nnew Worker(\n  new URL('./worker', import.meta.url),\n  {type: 'module'}\n);\n```\n\n```text\n./worker\n```\n\n```text\nimport MyWorker from './worker?worker'\n\nconst worker = new MyWorker()\n```\n\n```text\n?worker\n```\n\n```text\npublic\n```\n\n```text\nsrc\n```\n\n```text\n@\n```\n\n```text\nsrc\n```\n\n```text\nimport MyWorker from '@/worker?worker'\n```\n\n========================================\n\nComments:\n- I found in some cases, has to have the file extension added to it e.g. new URL('./file.js, import.meta.url) or else it would give weird MIME type errors\n- Testing this in Vite 5.1.4, this works but only if your web worker is JS, not TS.\n- note that this will simply copy the raw worker js file into the output assets directory. It will not transpile it (as with the rest of the code), so things like typescript doesn't work.\n- Trying this in Vite 5.1.4, it appears this works only if your web worker is JS, not TS. Might be a bug in Vite.\n- @JudahGabrielHimango trying now with Vite 5.2.0 and it is working also with TS. The answer set as accepted is not working for me at build time but only at runtime.\n- This seems to create a module worker (and you thus cannot use importScripts). Is there a way to use this syntax to create a classic worker?\n- How must one write the code inside the imported module? Can the imported module with ?worker be an ES module that exports something, or that at least can import? The documentation doesn't specify about the contents of the file.\n- @Jos&#233;Ram&#237;rez You write like you would a regular web worker. developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/&hellip;\n- @JudahGabrielHimango For the TS version to be working you need to append an other parameter to the import `import MyWorker from '@&#47;worker?worker&type=module`","metadata":{"transformedAt":"2026-08-18T18:33:46.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":158,"estimatedTokens":1332}}244{"id":"stack-66667636","source":"stackoverflow","questionId":66667636,"title":"Vite.js React Build Not Redirecting On Netlify And Vercel","tags":["reactjs","react-router","netlify","vercel","vite"],"text":"Title: Vite.js React Build Not Redirecting On Netlify And Vercel\nTags: reactjs, react-router, netlify, vercel, vite\nSource: Stack Overflow\n\nQuestion:\nI made a react build with vite.js.\nWhen building for production and testing on local host all is working fine. But when i deploy to Netlify or vercel routes that i created with react-router are not accessible via entering their url directly, but only from the main page ('/') via using the links inside of the application.\n\nIf i click on the route link in the application the route is working, but if i enter the url directly (for example: mypage/about) i am getting a 404 error.\n\nI checked in with vercel support and they said that likely a redirect is missing in the configuration, which is for example setup by default by create-react-app. In CRA it looks like this\n\n```\n{\n \"redirects: [\n { \"source\": \"/(.*)\", \"destination\": \"/index.html\" }\n ]\n}\n```\n\nAfter going through the vite.js documentation i can't find any hints on how to setup a redirect in vite.\n\n========================================\n\nTop Answer:\nIf you are using vite\ncreate a folder called public and add a file called _redirects to it, for the rest of the other bundlers just add the _redirects file to the public folder\n\nput this inside the _redirects file\n\n```\n/* /index.html 200\n```\n\nLink Here - thats the link if you want to see the project structure\n\nOn Azure Static Webapp add this file to the base directory of your project `staticwebapp.config.json` and add the following contents\n\n```\n{\n \"navigationFallback\": {\n \"rewrite\": \"/index.html\"\n }\n}\n```\n\nYou can learn more about it here https://learn.microsoft.com/en-us/azure/static-web-apps/configuration\n\n========================================\n\nCode:\n```text\n{\n  \"redirects: [\n    { \"source\": \"/(.*)\", \"destination\": \"/index.html\" }\n  ]\n}\n```\n\n```text\nvercel.json\n```\n\n```text\n{\n  \"rewrites\": [{ \"source\": \"/(.*)\", \"destination\": \"/\" }]\n}\n```\n\n```text\n{\n  \"rewrites\": [{ \"source\": \"/(.*)\", \"destination\": \"/index.html\" }]\n}\n```\n\n```text\n/* /index.html 200\n```\n\n```text\n{\n    \"navigationFallback\": {\n     \"rewrite\": \"/index.html\"\n    }\n}\n```\n\n```text\nstaticwebapp.config.json\n```\n\n```text\n/* /index.html 200\n```\n\n```text\n_redirects\n```\n\n```text\nvercel --prod\n```\n\n========================================\n\nComments:\n- This solution worked for me, but I had to set destination to `\"&#47;\"` instead of `\"&#47;index.html\"` (otherwise, I still get 404 page).\n- Thanks very much. Answer should be accepted as solution.\n- You saved the day bro. I utilized/wasted 3 hours of my night/life finding this answer. btw how do we fix this in heroku, netlify and others?\n- Thanks @Shantiscrip!! Your soltuion worked like cake. I created a new file in my project folder called \"vercel.json\" & used your first solution. Thanks a lot!\n- Could you tell more about this solution? What will be the contents of the file? and will this work for TS?\n- yep 100% i use ts on most of my projects, i edited my answer on top, let me know if you need any help\n- Hapy to help, seems it works on both netlify and vercel. Will try on Azure","metadata":{"transformedAt":"2026-08-18T18:33:46.413Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":113,"estimatedTokens":771}}245{"id":"stack-61949967","source":"stackoverflow","questionId":61949967,"title":"How do I add tailwindcss to vite version 0 to 3? (not including V4)","tags":["vue.js","tailwind-css","vite"],"text":"Title: How do I add tailwindcss to vite version 0 to 3? (not including V4)\nTags: vue.js, tailwind-css, vite\nSource: Stack Overflow\n\nQuestion:\nI'm using vite `0.16.6` and wanted to migrated a vuepress site to using vite.\n\nHowever I was unsure how to configure vite to using tailwindcss.\n\nin my `index.css`\n\n```\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n#app {\n font-family: Avenir, Helvetica, Arial, sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n text-align: center;\n color: #2c3e50;\n margin-top: 60px;\n}\n```\n\n========================================\n\nTop Answer:\nVite has built-in support for PostCSS:\n\n```\nnpm -D install tailwindcss autoprefixer\n```\n\nvite.config.ts\n\n```\nimport { defineConfig } from \"vite\"\nimport tailwind from \"tailwindcss\";\nimport autoprefixer from \"autoprefixer\";\n\nexport default defineConfig({\n css: {\n postcss: {\n plugins: [tailwind, autoprefixer],\n }\n }\n})\n```\n\n========================================\n\nCode:\n```text\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n#app {\n  font-family: Avenir, Helvetica, Arial, sans-serif;\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n  text-align: center;\n  color: #2c3e50;\n  margin-top: 60px;\n}\n```\n\n```text\n0.16.6\n```\n\n```text\nindex.css\n```\n\n```text\nmodule.exports = {\n  plugins: [\n    // ...\n    require('tailwindcss'),\n    require('autoprefixer'),\n    // ...\n  ]\n}\n```\n\n```text\npostcss.config.js\n```\n\n```text\nyarn add tailwindcss @tailwindcss/typography @tailwindcss/ui -D\n```\n\n```text\nmodule.exports={\n plugins: [\n  require('tailwindcss'),\n  require('autoprefixer'),\n  ]\n }\n```\n\n```text\n@import \"tailwindcss/base\";\n@import \"tailwindcss/components\";\n@import \"tailwindcss/utilities\";\n```\n\n```text\nyarn tailwind init\n```\n\n```text\npostcss.config.js\n```\n\n```text\n$ npm create-vite-tailwind\n...\n$ npm run dev\n```\n\n```bash\nnpm -D install tailwindcss autoprefixer\n```\n\n```text\nimport { defineConfig } from \"vite\"\nimport tailwind from \"tailwindcss\";\nimport autoprefixer from \"autoprefixer\";\n\nexport default defineConfig({\n  css: {\n    postcss: {\n      plugins: [tailwind, autoprefixer],\n    }\n  }\n})\n```\n\n```none\nnpm install tailwindcss @tailwindcss/vite\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport tailwindcss from '@tailwindcss/vite'\nexport default defineConfig({\n  plugins: [\n    tailwindcss(),\n  ],\n})\n```\n\n```css\n@import \"tailwindcss\";\n```\n\n```text\n@tailwindcss/vite\n```\n\n========================================\n\nComments:\n- From TailwindCSS v4 can use separated `@tailwindcss&#47;vite` plugin for this.\n- doc tailwindcss.com/docs/guides/vite is missing this part =.=\"\n- putting the `postcss.config.js` in the app root was what fixed it for me. Optionally, you can edit your `vite.config.js` to specify the location of your `postcss.config.js` file. vitejs.dev/config/#css-postcss\n- I love how after 2 years this answer is still applicable :D\n- this worked after i migrated from create-react-app v5 to vite\n- agreed - I've updated the title to ensure it's V0-V3","metadata":{"transformedAt":"2026-08-18T18:33:46.413Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":174,"estimatedTokens":760}}246{"id":"stack-72139073","source":"stackoverflow","questionId":72139073,"title":"Nuxt3 Vite server port","tags":["vue.js","nuxt.js","vite","nuxt3.js"],"text":"Title: Nuxt3 Vite server port\nTags: vue.js, nuxt.js, vite, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI need to config server port for Nuxt3. I try to do it so:\n\n`nuxt.config.ts`\n\n```\nimport { defineNuxtConfig } from 'nuxt3'\n\nexport default defineNuxtConfig(\n vite: {\n server: {\n port: 5000,\n },\n },\n})\n```\n\nBut it doesn't work. How to set server port in Nuxt3?\n\n========================================\n\nTop Answer:\nAs of the time of writing the answer, you can now define the port in your `nuxt.config` as follows:\n\n```\nexport default defineNuxtConfig({\n devServer: {\n port: 3001,\n },\n})\n```\n\nSource\n\n========================================\n\nCode:\n```js\nimport { defineNuxtConfig } from 'nuxt3'\n\nexport default defineNuxtConfig(\n  vite: {\n    server: {\n      port: 5000,\n    },\n  },\n})\n```\n\n```text\nnuxt.config.ts\n```\n\n```json\n{\n  \"scripts\": {\n    \"build\": \"nuxt build\",\n    \"dev\": \"nuxt dev --port=5678\", // here\n    \"generate\": \"nuxt generate\",\n    \"preview\": \"nuxt preview\"\n  },\n  \"devDependencies\": {\n    \"nuxt\": \"3.0.0-rc.1\"\n  }\n}\n```\n\n```bash\nsudo npm i cross-env -g\n```\n\n```json\n{\n  \"private\": true,\n  \"scripts\": {\n    \"build\": \"nuxt build\",\n    \"dev\": \"nuxt dev --port=8001\",\n    \"generate\": \"nuxt generate\",\n    \"preview\": \"cross-env PORT=8001 node .output/server/index.mjs\"\n  },\n  \"devDependencies\": {\n    \"nuxt\": \"3.0.0-rc.4\"\n  },\n}\n```\n\n```bash\nyarn run preview\n```\n\n```text\ndev\n```\n\n```text\nproduction\n```\n\n```text\ncross-env\n```\n\n```text\npackage.json\n```\n\n```js\nmodule.exports = {\n  apps: [\n    {\n      name: 'NuxtAppName',\n      exec_mode: 'cluster',\n      instances: 'max',\n      script: './.output/server/index.mjs',\n    port: 5000\n    }\n  ]\n}\n```\n\n```js\nmodule.exports = {\n  apps: [\n    {\n      name: 'NuxtApp',\n      port: 3001,\n      exec_mode: 'cluster',\n      instances: '1',\n      script: './.output/server/index.mjs',\n      args: 'preview',\n    },\n  ],\n}\n```\n\n```text\necosystem.config.js\n```\n\n```text\nServer: {\n   port: 'xxxx'\n}\n```\n\n```text\nhost: '0'\n```\n\n```text\nserver?: Omit<ServerOptions, 'port' | 'host'>;\n```\n\n```text\n\"dev\": \"nuxt dev --host=0 --port=3000\"\n```\n\n```js\nexport default defineNuxtConfig({\n  devServer: {\n    port: 3001,\n  },\n})\n```\n\n```text\nnuxt.config\n```\n\n```text\nPORT=5000\n```\n\n```text\n.env\n```\n\n```text\nPORT\n```\n\n```text\nexport default defineNuxtConfig({\n  devServer: {\n    port: 3030\n  },\n})\n```\n\n========================================\n\nComments:\n- Btw, as a side note since the RC1, you only need `import { defineNuxtConfig } from 'nuxt'` (no need for `nuxt3`). As shown here: nuxtjs.org/announcements/nuxt3-rc/#vite--webpack\n- product **PORT=5000 node .output/server/index.mjs**\n- The `devServer` configuration is available to set the port. stackoverflow.com/a/76281156/3247405\n- devServer did not work for me, this does. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:46.413Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":200,"estimatedTokens":696}}247{"id":"stack-72848322","source":"stackoverflow","questionId":72848322,"title":"Is the \" npm run watch\" property already in Laravel Vite?","tags":["laravel","vite"],"text":"Title: Is the \" npm run watch\" property already in Laravel Vite?\nTags: laravel, vite\nSource: Stack Overflow\n\nQuestion:\nIs the \"watch\" property already in vitejs?\nI'm starting a new project using Laravel Framework 9.19.0 in which vite is auto-mounted.\nI've added alpine.js for the front. I've tried to run\n\nnpm run watch\n\nThis is my package.json file\n\n```\n{\n\"private\": true,\n\"scripts\": {\n \"watch\": \"npm-watch\", \n \"dev\": \"vite\",\n \"build\": \"vite build\"\n},\n\"devDependencies\": {\n \"axios\": \"^0.25\",\n \"laravel-vite-plugin\": \"^0.2.1\",\n \"lodash\": \"^4.17.19\",\n \"postcss\": \"^8.1.14\",\n \"vite\": \"^2.9.11\"\n},\n\"dependencies\": {\n \"alpinejs\": \"^3.10.2\"\n}\n```\n\n}\n\nand the following error occurred.\n\n```\n0 info it worked if it ends with ok\n1 verbose cli [\n1 verbose cli 'C:\\\\Program Files\\\\nodejs\\\\node.exe',\n1 verbose cli 'C:\\\\Program Files\\\\nodejs\\\\node_modules\\\\npm\\\\bin\\\\npm-cli.js',\n1 verbose cli 'run',\n1 verbose cli 'watch'\n1 verbose cli ]\n2 info using npm@6.14.15\n3 info using node@v14.17.6\n4 verbose run-script [ 'prewatch', 'watch', 'postwatch' ]\n5 info lifecycle @~prewatch: @\n6 info lifecycle @~watch: @\n7 verbose lifecycle @~watch: unsafe-perm in lifecycle true\n8 verbose lifecycle @~watch: PATH: C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\npm-lifecycle\\node-gyp-bin;C:\\Users\\Arotiana's\\laravel9_portfolio\\node_modules\\.bin;C:\\Program Files\\Common Files\\Oracle\\Java\\javapath;C:\\Program Files (x86)\\Common Files\\Oracle\\Java\\javapath;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;C:\\WINDOWS\\System32\\OpenSSH\\;C:\\Program Files (x86)\\Inno Setup 5;C:\\Program Files\\nodejs\\;C:\\ProgramData\\ComposerSetup\\bin;C:\\Program Files\\Java\\jdk-17.0.2\\bin;C:\\Program Files\\Git\\cmd;C:\\flutter\\bin;C:\\Users\\Arotiana's\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\Arotiana's\\AppData\\Roaming\\npm;C:\\Users\\Arotiana's\\AppData\\Local\\Programs\\Microsoft VS Code\\bin;C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin;C:\\Program Files\\PHP;C:\\Users\\Arotiana's\\AppData\\Roaming\\Composer\\vendor\\bin;C:\\Users\\Arotiana's\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python39\\Scripts;C:\\Program Files\\Java\\jdk-17.0.2\\bin;C:\\windows\\System32;C:\\flutter\\bin;\n9 verbose lifecycle @~watch: CWD: C:\\Users\\Arotiana's\\laravel9_portfolio\n10 silly lifecycle @~watch: Args: [ '/d /s /c', 'npm-watch' ]\n11 silly lifecycle @~watch: Returned: code: 1 signal: null\n12 info lifecycle @~watch: Failed to exec watch script\n13 verbose stack Error: @ watch: `npm-watch`\n13 verbose stack Exit status 1\n13 verbose stack at EventEmitter. (C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\npm-lifecycle\\index.js:332:16)\n13 verbose stack at EventEmitter.emit (events.js:400:28)\n13 verbose stack at ChildProcess. (C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\npm-lifecycle\\lib\\spawn.js:55:14)\n13 verbose stack at ChildProcess.emit (events.js:400:28)\n13 verbose stack at maybeClose (internal/child_process.js:1055:16)\n13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5)\n14 verbose pkgid @\n15 verbose cwd C:\\Users\\Arotiana's\\laravel9_portfolio\n16 verbose Windows_NT 10.0.19044\n17 verbose argv \"C:\\\\Program Files\\\\nodejs\\\\node.exe\" \"C:\\\\Program Files\\\\nodejs\\\\node_modules\\\\npm\\\\bin\\\\npm-cli.js\" \"run\" \"watch\"\n18 verbose node v14.17.6\n19 verbose npm v6.14.15\n20 error code ELIFECYCLE\n21 error errno 1\n22 error @ watch: `npm-watch`\n22 error Exit status 1\n23 error Failed at the @ watch script.\n23 error This is probably not a problem with npm. There is likely additional logging output above.\n24 verbose exit [ 1, true ]\n```\n\nCan you help me??\n\n========================================\n\nTop Answer:\n**Laravel 10 here**\n\nThe docs states that you can run:\n\n`npm run dev`\n\nAnd it will perform the same behaviour as a watch, however, when wrapping up your work, you should then run:\n\n`npm run build`\n\n*docs excerpt:*\n\nThere are two ways you can run Vite. You may run the development server via the dev command, which is useful while developing locally. The development server will automatically detect changes to your files and instantly reflect them in any open browser windows.\n\nOr, running the build command will version and bundle your application's assets and get them ready for you to deploy to production:\n\n========================================\n\nCode:\n```text\n{\n\"private\": true,\n\"scripts\": {\n    \"watch\": \"npm-watch\",                       <-<=-----I've added this line------->\n    \"dev\": \"vite\",\n    \"build\": \"vite build\"\n},\n\"devDependencies\": {\n    \"axios\": \"^0.25\",\n    \"laravel-vite-plugin\": \"^0.2.1\",\n    \"lodash\": \"^4.17.19\",\n    \"postcss\": \"^8.1.14\",\n    \"vite\": \"^2.9.11\"\n},\n\"dependencies\": {\n    \"alpinejs\": \"^3.10.2\"\n}\n```\n\n```text\n0 info it worked if it ends with ok\n1 verbose cli [\n1 verbose cli   'C:\\\\Program Files\\\\nodejs\\\\node.exe',\n1 verbose cli   'C:\\\\Program Files\\\\nodejs\\\\node_modules\\\\npm\\\\bin\\\\npm-cli.js',\n1 verbose cli   'run',\n1 verbose cli   'watch'\n1 verbose cli ]\n2 info using npm@6.14.15\n3 info using node@v14.17.6\n4 verbose run-script [ 'prewatch', 'watch', 'postwatch' ]\n5 info lifecycle @~prewatch: @\n6 info lifecycle @~watch: @\n7 verbose lifecycle @~watch: unsafe-perm in lifecycle true\n8 verbose lifecycle @~watch: PATH: C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\npm-lifecycle\\node-gyp-bin;C:\\Users\\Arotiana's\\laravel9_portfolio\\node_modules\\.bin;C:\\Program Files\\Common Files\\Oracle\\Java\\javapath;C:\\Program Files (x86)\\Common Files\\Oracle\\Java\\javapath;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;C:\\WINDOWS\\System32\\OpenSSH\\;C:\\Program Files (x86)\\Inno Setup 5;C:\\Program Files\\nodejs\\;C:\\ProgramData\\ComposerSetup\\bin;C:\\Program Files\\Java\\jdk-17.0.2\\bin;C:\\Program Files\\Git\\cmd;C:\\flutter\\bin;C:\\Users\\Arotiana's\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\Arotiana's\\AppData\\Roaming\\npm;C:\\Users\\Arotiana's\\AppData\\Local\\Programs\\Microsoft VS Code\\bin;C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin;C:\\Program Files\\PHP;C:\\Users\\Arotiana's\\AppData\\Roaming\\Composer\\vendor\\bin;C:\\Users\\Arotiana's\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python39\\Scripts;C:\\Program Files\\Java\\jdk-17.0.2\\bin;C:\\windows\\System32;C:\\flutter\\bin;\n9 verbose lifecycle @~watch: CWD: C:\\Users\\Arotiana's\\laravel9_portfolio\n10 silly lifecycle @~watch: Args: [ '/d /s /c', 'npm-watch' ]\n11 silly lifecycle @~watch: Returned: code: 1  signal: null\n12 info lifecycle @~watch: Failed to exec watch script\n13 verbose stack Error: @ watch: `npm-watch`\n13 verbose stack Exit status 1\n13 verbose stack     at EventEmitter.<anonymous> (C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\npm-lifecycle\\index.js:332:16)\n13 verbose stack     at EventEmitter.emit (events.js:400:28)\n13 verbose stack     at ChildProcess.<anonymous> (C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\npm-lifecycle\\lib\\spawn.js:55:14)\n13 verbose stack     at ChildProcess.emit (events.js:400:28)\n13 verbose stack     at maybeClose (internal/child_process.js:1055:16)\n13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5)\n14 verbose pkgid @\n15 verbose cwd C:\\Users\\Arotiana's\\laravel9_portfolio\n16 verbose Windows_NT 10.0.19044\n17 verbose argv \"C:\\\\Program Files\\\\nodejs\\\\node.exe\" \"C:\\\\Program Files\\\\nodejs\\\\node_modules\\\\npm\\\\bin\\\\npm-cli.js\" \"run\" \"watch\"\n18 verbose node v14.17.6\n19 verbose npm  v6.14.15\n20 error code ELIFECYCLE\n21 error errno 1\n22 error @ watch: `npm-watch`\n22 error Exit status 1\n23 error Failed at the @ watch script.\n23 error This is probably not a problem with npm. There is likely additional logging output above.\n24 verbose exit [ 1, true ]\n```\n\n```text\n\"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"watch\": \"vite build --watch\"\n},\n```\n\n```text\nnpm run watch\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run build\n```\n\n========================================\n\nComments:\n- when i have some typescripts in the input files the watcher just hangs :(\n- @user151496 did you try only use `npm run dev`?","metadata":{"transformedAt":"2026-08-18T18:33:46.413Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":190,"estimatedTokens":2025}}248{"id":"stack-70617812","source":"stackoverflow","questionId":70617812,"title":"Change Environmet Variables at runtime (React, vite) with docker and nginx","tags":["azure","web-applications","environment-variables","azure-web-app-service","vite"],"text":"Title: Change Environmet Variables at runtime (React, vite) with docker and nginx\nTags: azure, web-applications, environment-variables, azure-web-app-service, vite\nSource: Stack Overflow\n\nQuestion:\nat work I need to make it possible to change the environmet variables at runtime, from an Azure web service, through docker and nginx.\nI tried this, this and some similar solutions, but I couln't get any of them to work.\n\nI also couldn't find any solution online or any article/thread/post that explained if this is even possible, I only always find the text that vite statically replaces the env variables at build time.\n\nDuring our CI/CD pipeline vite gets the env variables but our Azure admins want to be able to configure them from Azure, just for the case of it.\n\nDoes anyone know if this is possible and or maybe has a solution or some help, please ? :)\n\n========================================\n\nTop Answer:\nIt is `not` possible to dynamically inject `Vite` env variables. But **what is possible**, is to **change the `window object` variables (assign them on runtime).** \n\n**WARNING!!! DO NOT EXPOSE ANY SENSITIVE VARIABLES THROUGH THE WINDOW OBJECT. YOUR FRONT-END APPLICATION SOURCE IS VISIBLE TO ANYONE USING IT**\n\n**Steps:**\n\nCreate your desired env files and place them in `/public`. Let's call them `env.js` and `env-prod.js`.\n\nInside your `env.js` and `env-prod.js` You want to assign your desired variables using `var` keyword. Also, you will have to reference these values in your source like `window.MY_VAR` to be able to use them.\n\nCreate a script tag inside your `/index.html` like this:\n\n``.\n\n**IMPORTANT!!!** `type=\"text/javascript\"` is important, because if You specify module, `Vite` will include your `env.js` source inside your minified `index.js` file.\n\nVite config (optional):\n\n```\nplugins: [react(), tsConfigPath()],\n build: {\n emptyOutDir: true, // deletes the dist folder before building\n },\n});\n```\n\n- `How to serve the env files on runtime`. Create a `node` server which will serve your frontend application. But before serving the `env.js` file, depending on our `process.env.ENVIRONMENT` you can now choose which env.js to serve. Let's say my node server file is stored at `/server/server.js`:\n\n```\nconst express = require(\"express\");\nconst path = require(\"path\");\n\nconst app = express();\n\nconst env = process.env.ENVIRONMENT || \"\";\n\nconsole.log(\"ENVIRONMENT:\", env);\n\nconst envFile = path.resolve(\"public\", env ? `env-${env}.js` : \"env.js\");\n\nconst indexFile = path.resolve(\"dist\", \"index.html\");\n\napp.use((req, res, next) => {\n const url = req.originalUrl;\n if (url.includes(\"env.js\")) {\n console.log(\"sending\", envFile);\n // instead of env.js we send our desired env file\n res.sendFile(envFile);\n return;\n }\n next();\n});\n\napp.use(express.static(path.resolve(\"dist\")));\napp.get(\"*\", (req, res) => {\n res.sendFile(indexFile);\n});\n\napp.listen(8000);\n```\n\nServe your application build while running `node ./server/sever.js` command in your terminal.\n\n**Finally:** \n\nmy `env.js` contains `var RUNTIME_VAR = 'test'`\n\nmy `env-prod.js` contains `var RUNTIME_VAR = 'prod'`\n\nAfter I set my `process.env.ENVIRONMENT` to `prod`. I get this file served:\nhttps://i.sstatic.net/1Pcqg.png\n\n========================================\n\nCode:\n```text\nVITE_API_URL=http://localhost:5000\nVITE_KEY=jo2i3jkj3kj\n```\n\n```text\nVITE_API_URL=MY_APP_API_URL\nVITE_APP_KEY=MY_APP_KEY\n```\n\n```text\n#!/bin/sh\nfor i in $(env | grep MY_APP_) // Make sure to use the prefix MY_APP_ if you have any other prefix in env.production file varialbe name replace it with MY_APP_\ndo\n    key=$(echo $i | cut -d '=' -f 1)\n    value=$(echo $i | cut -d '=' -f 2-)\n    echo $key=$value\n    # sed All files\n    # find /usr/share/nginx/html -type f -exec sed -i \"s|${key}|${value}|g\" '{}' +\n\n    # sed JS and CSS only\n    find /usr/share/nginx/html -type f \\( -name '*.js' -o -name '*.css' \\) -exec sed -i \"s|${key}|${value}|g\" '{}' +\ndone\n```\n\n```text\n# Stage 1: Build Image\nFROM node:18-alpine as build\nRUN apk add git\nWORKDIR /app\nCOPY package*.json ./\nRUN npm install\nCOPY . .\nRUN npm run build\n\n# Stage 2, use the compiled app, ready for production with Nginx\nFROM nginx:1.21.6-alpine\nCOPY --from=build /app/dist /usr/share/nginx/html\nCOPY /nginx.conf /etc/nginx/conf.d/default.conf\nCOPY env.sh /docker-entrypoint.d/env.sh\nRUN chmod +x /docker-entrypoint.d/env.sh\n```\n\n```text\ndocker build -t image-name\n```\n\n```text\ndocker run --rm -p 3000:80 -e MY_APP_API_URL=api_url -e MY_APP_KEY=key image-name\n```\n\n```text\n#Set variables once\nvariables:\n  configuration: debug\n  platform: x64\n\nsteps:\n\n#Use them once\n- task: MSBuild@1\n  inputs:\n    solution: solution1.sln\n    configuration: $(configuration) # Use the variable\n    platform: $(platform)\n\n#Use them again\n- task: MSBuild@1\n  inputs:\n    solution: solution2.sln\n    configuration: $(configuration) # Use the variable\n    platform: $(platform)\n```\n\n```text\nplugins: [react(), tsConfigPath()],\n  build: {\n    emptyOutDir: true, // deletes the dist folder before building\n  },\n});\n```\n\n```text\nconst express = require(\"express\");\nconst path = require(\"path\");\n\nconst app = express();\n\nconst env = process.env.ENVIRONMENT || \"\";\n\nconsole.log(\"ENVIRONMENT:\", env);\n\nconst envFile = path.resolve(\"public\", env ? `env-${env}.js` : \"env.js\");\n\nconst indexFile = path.resolve(\"dist\", \"index.html\");\n\napp.use((req, res, next) => {\n  const url = req.originalUrl;\n  if (url.includes(\"env.js\")) {\n    console.log(\"sending\", envFile);\n    // instead of env.js we send our desired env file\n    res.sendFile(envFile);\n    return;\n  }\n  next();\n});\n\napp.use(express.static(path.resolve(\"dist\")));\napp.get(\"*\", (req, res) => {\n  res.sendFile(indexFile);\n});\n\napp.listen(8000);\n```\n\n```text\nnot\n```\n\n```text\nVite\n```\n\n```text\nwindow object\n```\n\n```text\n<rootDir>/public\n```\n\n```text\nenv.js\n```\n\n```text\nenv-prod.js\n```\n\n```text\nenv.js\n```\n\n```text\nenv-prod.js\n```\n\n```text\nvar\n```\n\n```text\nwindow.MY_VAR\n```\n\n```text\n<rootDir>/index.html\n```\n\n```text\n<script type=\"text/javascript\" src=\"./env.js\"></script>\n```\n\n```text\ntype=\"text/javascript\"\n```\n\n```text\nVite\n```\n\n```text\nenv.js\n```\n\n```text\nindex.js\n```\n\n```text\nHow to serve the env files on runtime\n```\n\n```text\nnode\n```\n\n```text\nenv.js\n```\n\n```text\nprocess.env.ENVIRONMENT\n```\n\n```text\n<rootDir>/server/server.js\n```\n\n```text\nnode ./server/sever.js\n```\n\n```text\nenv.js\n```\n\n```text\nvar RUNTIME_VAR = 'test'\n```\n\n```text\nenv-prod.js\n```\n\n```text\nvar RUNTIME_VAR = 'prod'\n```\n\n```text\nprocess.env.ENVIRONMENT\n```\n\n```text\nprod\n```\n\n```text\n// src/index.js\nconsole.log(`API base URL is: ${import.meta.env.API_BASE_URL}.`);\n```\n\n```text\n// dist/index.js\nconsole.log(\n  `API base URL is: ${\"__import_meta_env_placeholder__\".API_BASE_URL}.`\n);\n```\n\n```text\n// dist/index.js\nconsole.log(\n  `API base URL is: ${{ API_BASE_URL: \"https://httpbin.org\" }.API_BASE_URL}.`\n);\n// > API base URL is: https://httpbin.org.\n```\n\n```text\nimport.meta.env\n```\n\n```text\nexport default defineConfig(({ command, mode }) => {\n\n  const env = loadEnv(mode, process.cwd(), \"\"); //this line\n\n  return { \n.\n.\n.\n```\n\n```text\nVITE_APP_any = 'any'\n```\n\n```text\nimport.meta.env.VITE_APP_any\n```\n\n```text\nprocess.env.VITE_APP_any\n```\n\n```text\nFROM node:alpine3.14 AS buildJS\nWORKDIR /var/www/html\nCOPY . .\nRUN apk add --no-cache yarn \\\n    && yarn && yarn build\n\nFROM nginx:stable-alpine\nWORKDIR /var/www/html\nCOPY --from=buildJS /var/www/html/dist .\nCOPY ./docker/conf/nginx.conf /etc/nginx/conf.d/default.conf\nCOPY ./docker/conf/config.json /etc/nginx/templates/config.json.template\n\nENTRYPOINT []\n\nCMD sleep 5 && mv /etc/nginx/conf.d/config.json config.json & /docker-entrypoint.sh nginx -g 'daemon off;'\n```\n\n```text\n// ./docker-compose.yml\nversion: '3'\nservices:\n front:\n  /* some params */\n  build:\n   dockerfile: ./Dockerfile\n   context: ./front\n  env_file: .env // its important, no need environment\n\n// ./front/Dockerfile - do not use\n\n// ./.env\n// https://vitejs.dev/guide/env-and-mode.html\n// VITE_* prefix is needed\nVITE_SOME_VAR=value \n\n// ./**/some_script.ts\n// Vite + Vue\nconsole.log('expected: ', import.meta.env.VITE_SOME_VAR) // expected: value\n```\n\n```text\nconfig.js\n```\n\n```text\n<rootDir>/index.html\n```\n\n```text\nconfig.js\n```\n\n```text\nvar\n```\n\n```text\nFROM nginx:alpine\nCOPY dist/ /usr/share/nginx/html\nCOPY docker-entry.sh /docker-entry.sh\nRUN chmod +x /docker-entry.sh\nEXPOSE 80\nENTRYPOINT [\"/docker-entry.sh\"]\nCMD [\"nginx\", \"-g\", \"daemon off;\"]\n```\n\n```text\n#!/bin/sh\n\n# replacing Vite's static env vars with injected one\nvars=$(printenv | grep '^VITE_' | awk -F= '{print $1}')\nfind \"/usr/share/nginx/html\" -type f -name \"*.js\" | while read file; do\n    for var in $vars; do\n        echo \"Replacing $var in $file\"\n        sed -i \"s/\\($var:\\\"\\)[^\\\"]*\\\"/\\1$(printenv \"$var\")\\\"/g\" $file\n    done\ndone\n\nexec \"$@\"\n```\n\n```text\nDockerfile\n```\n\n```text\ndocker-entry.sh\n```\n\n```text\nvite build\n```\n\n```text\n--build-arg VITE_API_URL=${{ secrets.VITE_API_URL }} \\\n```\n\n```text\nARG VITE_API_URL\n\nENV VITE_API_URL=$VITE_API_URL\n```\n\n```text\nnpm run build\n```\n\n========================================\n\nComments:\n- Thanks for your help but I need to be able to change the env-Variables inside of the Azure App service configuration. We use Gitlab and in there I currently have multiple env-Files for each server(dev, staging, prod), that works fine. But I need to do something like in the linked articles and I don't get that to work.\n- Thanks man! I've been googling this all day and only thanks to you I found the solution.\n- This worked well for me using react + vite + docker, thanks for the package !\n- Question is about changing variables at runtime, this answer is only for dev\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- This is excellent. Very neat. Thank you for sharing.\n- Thank you – first proper solution to this problem that I've seen!\n- How do you treat signed docker images? Lets say you provide a signed image that would be deployed on multiple customer-systems and each customer needs specific configuration. Wouldn't that break the certificate if you edit the code after build?\n- I tried this and it doesn't work, the values are set at build time so you can't really do a find and replace. Vite doesn't leave traces of VITE_A, VITE_B etc anywhere to be repalced.\n- @Stokedout Not sure if my answer still valid. At the moment of the answer variable VITE_ still exist in the js bundle even after build.\n- The question is about configuration *after* `npm run build`, so this unfortunately will not help here.","metadata":{"transformedAt":"2026-08-18T18:33:46.413Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":59,"totalLines":488,"estimatedTokens":2670}}249{"id":"stack-67654479","source":"stackoverflow","questionId":67654479,"title":"Error: Cannot find module '@vue/cli-service/generator/template/src/App.vue' with vite","tags":["vue.js","vue-router","vuejs3","vite"],"text":"Title: Error: Cannot find module '@vue/cli-service/generator/template/src/App.vue' with vite\nTags: vue.js, vue-router, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI created a vue 3 project with vite and I wanted to add vue-router to the project, so from the terminal I wrote `vue add router` but after downloading everything I get the following error:\n\n```\nError: Cannot find module '@vue/cli-service/generator/template/src/App.vue' from '/home/frostri/projects/onedrive_local/client/node_modules/@vue/cli-plugin-router/generator/template/src'\n at Function.resolveSync [as sync] (/usr/lib/node_modules/@vue/cli/node_modules/resolve/lib/sync.js:102:15)\n at renderFile (/usr/lib/node_modules/@vue/cli/lib/GeneratorAPI.js:515:17)\n at /usr/lib/node_modules/@vue/cli/lib/GeneratorAPI.js:300:27\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\n at async Generator.resolveFiles (/usr/lib/node_modules/@vue/cli/lib/Generator.js:268:7)\n at async Generator.generate (/usr/lib/node_modules/@vue/cli/lib/Generator.js:175:5)\n at async runGenerator (/usr/lib/node_modules/@vue/cli/lib/invoke.js:111:3)\n at async invoke (/usr/lib/node_modules/@vue/cli/lib/invoke.js:92:3)\n```\n\nIs there anything I can do to fix it?\n\n========================================\n\nTop Answer:\nI don't know if this helps, but at least works for me.\n\nfirst I installed @vue/cli-service\n\n`npm install --save-dev @vue/cli-service`\n\nand then Vue Router.\n\n`vue add router`\n\nLet me know if this works for you! Have a nice day!\n\n========================================\n\nCode:\n```text\nError: Cannot find module '@vue/cli-service/generator/template/src/App.vue' from '/home/frostri/projects/onedrive_local/client/node_modules/@vue/cli-plugin-router/generator/template/src'\n    at Function.resolveSync [as sync] (/usr/lib/node_modules/@vue/cli/node_modules/resolve/lib/sync.js:102:15)\n    at renderFile (/usr/lib/node_modules/@vue/cli/lib/GeneratorAPI.js:515:17)\n    at /usr/lib/node_modules/@vue/cli/lib/GeneratorAPI.js:300:27\n    at processTicksAndRejections (node:internal/process/task_queues:96:5)\n    at async Generator.resolveFiles (/usr/lib/node_modules/@vue/cli/lib/Generator.js:268:7)\n    at async Generator.generate (/usr/lib/node_modules/@vue/cli/lib/Generator.js:175:5)\n    at async runGenerator (/usr/lib/node_modules/@vue/cli/lib/invoke.js:111:3)\n    at async invoke (/usr/lib/node_modules/@vue/cli/lib/invoke.js:92:3)\n```\n\n```text\nvue add router\n```\n\n```text\nnpm i -S vue-router@4\n# or:\nyarn add vue-router@4\n```\n\n```js\nimport { createRouter, createWebHistory } from 'vue-router'\nimport HelloWorld from './components/HelloWorld.vue'\n\nexport default createRouter({\n  history: createWebHistory(),\n  routes: [\n    {\n      path: '/',\n      component: HelloWorld,\n    }\n  ]\n})\n```\n\n```js\nimport { createApp } from 'vue'\nimport App from './App.vue'\nimport './index.css'\nimport router from './router' 👈\n\ncreateApp(App)\n  .use(router) 👈\n  .mount('#app')\n```\n\n```html\n<template>\n  <router-view />\n</template>\n```\n\n```text\nvue\n```\n\n```text\nvue add router\n```\n\n```text\nvue-router\n```\n\n```text\nvue-router\n```\n\n```text\nsrc/router.js\n```\n\n```text\nsrc/main.js\n```\n\n```text\nsrc/App.vue\n```\n\n```text\nnpm install --save-dev @vue/cli-service\n```\n\n```text\nvue add router\n```\n\n========================================\n\nComments:\n- This saved me a lot of time. Thank you so much, this should be in their official docs!\n- This worked for me! I *had* installed vue cli globally: `npm i -g @vue&#47;cli`, but not in the project I think. (Also I was trying to add typescript, not router, but I ended up here)","metadata":{"transformedAt":"2026-08-18T18:33:46.413Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":134,"estimatedTokens":894}}250{"id":"stack-70494033","source":"stackoverflow","questionId":70494033,"title":"Setting static asset cache TTL in SvelteKit","tags":["svelte","vite","sveltekit"],"text":"Title: Setting static asset cache TTL in SvelteKit\nTags: svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am serving font and CSS files from `/static` using the default SvelteKit application template. I am using SvelteKit Node.js adapter.\n\nThe default cache time-to-live (TTL) seems to be 4 hours for `/static` files. I am not sure if this is set by SvelteKit/Vite itself or does any of the middleboxes like CloudFlare make this assumption.\n\nHow can I override this in SvelteKit? I assume this needs to be configured in Vite somehow, so that the `/static` files are server with correct HTTP caching headers. As the font files do not change, I would like to set them to be immutable and avoid the user web browser redownloading the files again.\n\nhttps://i.sstatic.net/tB4Hh.png\n\n========================================\n\nTop Answer:\nI've been having trouble with fonts in sveltekit recently, and it seems that the currently accepted answer is a tiny bit outdated, so I'll add some new relevant info.\n\nThe `/static` folder is not handled the same way, currently there are no cache settings hardcoded to handle the static assets, so no cache headers are sent at all.\n\nCache headers are still sent for whatever Vite puts in `/${manifest.appPath}/immutable/`, and after looking at some discussions on svelkit discord, it seems that the easiest way to handle cache headers for fonts is to put them under `/src` instead of static and let vite handle it with the css `url()`.\n\nFor example (in svelte context), you can put your fonts under `/src/lib/fonts` and in a css file (that must also be under `/src` or imported in a way Vite handles it):\n\n```\n@font-face {\n font-family: 'Inter';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url('$lib/fonts/Inter-Regular.woff2') format('woff2');\n}\n```\n\nAnd Vite will now rebase the url and serve the font under `/${manifest.appPath}/immutable/` thus sending the cache control headers properly.\n\nSvelte currently does not uses `E-Tag` header for that, but vite will append a hash to the font (like `Inter-Regular.COLGFB3M.woff2`) and will automatically map it to the css file aswell, so modifying the font without changing it's name should not be a problem.\n\nYou can also solve this other ways, like setting an nginx reverse proxy or configuring a service worker to handle the cache.\n\n========================================\n\nCode:\n```text\n/static\n```\n\n```text\n/static\n```\n\n```text\n/static\n```\n\n```text\n/tmp # wget -S \"http://localhost:3000/fonts.css\"\n\n--2021-12-31 00:35:00--  http://localhost:3000/fonts.css\nResolving localhost (localhost)... 127.0.0.1\nConnecting to localhost (localhost)|127.0.0.1|:3000... connected.\nHTTP request sent, awaiting response...\n  HTTP/1.1 200 OK\n  Vary: Accept-Encoding\n  Content-Length: 2249\n  Content-Type: text/css\n  Last-Modified: Thu, 30 Dec 2021 23:34:41 GMT\n  ETag: W/\"2249-1640907281407\"\n  Cache-Control: public,max-age=31536000,immutable\n  Date: Thu, 30 Dec 2021 23:35:00 GMT\n  Connection: keep-alive\n  Keep-Alive: timeout=5\nLength: 2249 (2.2K) [text/css]\n```\n\n```text\n@sveltejs/adapter-node@next\n```\n\n```text\ncache-control\n```\n\n```html\n<script context=\"module\">\n    export async function load({ params, fetch }) {\n    //...\n        return {\n            maxage: 60 // 1 minute\n        };\n    }\n</script>\n```\n\n```css\n@font-face {\n  font-family: 'Inter';\n  font-style: normal;\n  font-weight: 400;\n  font-display: swap;\n  src: url('$lib/fonts/Inter-Regular.woff2') format('woff2');\n}\n```\n\n```text\n/static\n```\n\n```text\n/${manifest.appPath}/immutable/\n```\n\n```text\n/src\n```\n\n```text\nurl()\n```\n\n```text\n/src/lib/fonts\n```\n\n```text\n/src\n```\n\n```text\n/${manifest.appPath}/immutable/\n```\n\n```text\nE-Tag\n```\n\n```text\nInter-Regular.COLGFB3M.woff2\n```\n\n========================================\n\nComments:\n- I have the exact same question, and I wonder how you solved it. The accepted answer doesn't really explain what you did? It only sets the `public,max-age=31536000,immutable` cache header for files within the `&#47;${manifest.appPath}&#47;immutable&#47;` path, which doesn't include the `&#47;static` folder where my font files are also placed.\n- Your question is different. This question is not about setting TTL for pages, but setting TTL for static assets. I suggest that you post self-answer on a new self-question and I can upvote stackoverflow.com/help/self-answer","metadata":{"transformedAt":"2026-08-18T18:33:46.413Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":145,"estimatedTokens":1093}}251{"id":"stack-74688433","source":"stackoverflow","questionId":74688433,"title":"Why loading dynamically assets fails on Nuxt v3","tags":["javascript","nuxt.js","assets","vite","nuxt3.js"],"text":"Title: Why loading dynamically assets fails on Nuxt v3\nTags: javascript, nuxt.js, assets, vite, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm experience a weird situation,\n\nI have a \"standard\" `Nuxt v3` project that comes with vite\n\n**Works**\n\n```\n\n```\n\n**Does not work**\n\n```\n\n```\n\nNote that the image path is the same so it does exist, the error I'm getting is:\n\nCannot find module '@/assets/img/image.png' Require stack\n\nThe docs don't mention anything that has to be done in order to achieve it\n\nhttps://i.sstatic.net/mAxO2.png\n\nIs there anything I should do?\n\n========================================\n\nCode:\n```html\n<img src=\"~/assets/img/image.png\">\n<img src=\"~/assets/video/video.mp4\">\n```\n\n```html\n<img :src=\"require('~/assets/img/image.png')\">\n<img :src=\"require('~/assets/video/video.mp4')\">\n```\n\n```text\nNuxt v3\n```\n\n```js\nexport const useDynamicImage = async (path) => {\n  const images = import.meta.glob(\"/src/assets/images/**/*\");\n  const image = (await images[path.replace(\"@\", \"/src\")]()).default;\n\n  return image as string;\n};\n```\n\n```html\n<img :src=\"`_nuxt/assets/img/${imageName}`\">\n```\n\n```none\nexport const useDynamicImage = (path: string): string =>\n    new URL(path, import.meta.url).toString();\n```\n\n```js\n<script>\nconst glob = import.meta.glob(\"~/assets/images/how-to-use/*\", {\n  eager: true,\n});\n\nconst getImageAbsolutePath = (imageName: string): string => {\n  return glob[`/assets/images/how-to-use/${imageName}`][\"default\"];\n};\n</script>\n```\n\n```none\n<script lang=\"ts\" setup>\n//@ts-ignore\nimport image1 from \"../assets/images/image1.jpg\";\n//@ts-ignore\nimport image2 from \"../assets/images/image2.jpg\";\n//@ts-ignore\nimport image3 from \"../assets/images/image3.jpg\";\n\nconst images = [image1, image2, image3];\n</script>\n```\n\n```text\nrequire\n```\n\n```text\nimport\n```\n\n```text\n/src\n```\n\n```text\n@/\n```\n\n```text\nimageName\n```\n\n========================================\n\nComments:\n- A similar question got asked this morning, here is my comment. Also, you're reading which documentation here? Looks like the one for Nuxt2 (with Webpack4). Since you're using Vite, please my comment.\n- hello @kissu The official docs nuxtjs.org/docs might be from the nuxt 2 version, do you have the link of the version 3? I don't think I understand your links so I would like to go through it\n- Here you have the docs for Nuxt3: nuxt.com\n- thanks! but it doesn't mention any of that.. nuxt.com/docs/getting-started/assets I'm trying with: this code `videoUrl.value = new URL(`/src/assets/video/hero-video-double.${props.isIOS ? 'mp4' : 'webm'}`, import.meta.url)` and that string prints out `&#47;src&#47;assets&#47;video&#47;hero-video-double.webm` but `videoUrl` is `http:&#47;&#47;localhost:3333&#47;undefined` any thougts?\n- Please read my initial comment Everything is written down there.\n- yes, I'm trying with option 3 of that SO answer's link, but is not explaining why to use like that and is failing to me and I don't know where to get more info..\n- Use the `2022 answer: Vite 2.8.6 + Vue 3.2.31` one.\n- I'll give it a shot, although I'm trying to load a video ant that answer is trying to load `().href`","metadata":{"transformedAt":"2026-08-18T18:33:46.413Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":122,"estimatedTokens":780}}252{"id":"stack-76214135","source":"stackoverflow","questionId":76214135,"title":"How to do manual mocks in Vitest?","tags":["unit-testing","testing","jestjs","vite","vitest"],"text":"Title: How to do manual mocks in Vitest?\nTags: unit-testing, testing, jestjs, vite, vitest\nSource: Stack Overflow\n\nQuestion:\nI'm basically trying to mock an external module in the same way for all my vitest tests, and it's surprisingly not trivial. In Jest, I would just create a `__mocks__` folder at the root, and it appears vitest is maybe supposed to support this, but I can't get it to work. Anybody figured out this (seemingly very basic) use case?\n\nTried creating a `__mocks__` folder at the root, tried doing a global mock in vite.config.ts. I want to create one mock that works for all tests\n\n========================================\n\nCode:\n```text\n__mocks__\n```\n\n```text\n__mocks__\n```\n\n```text\ntest: {\n  setupFiles: ['./vitest.setup.ts'],\n}\n```\n\n```text\nnode:\n```\n\n========================================\n\nComments:\n- Given the documentation at vitest.dev/guide/mocking.html#modules, what specifically have you tried, what is not working, and what is the specific minimal reproducible example that you can ?\n- Did you get anywhere? I'm also trying this and can't get it to work at all!\n- Looks like you can go one of two ways, according to the docs (vitest.dev/api/vi.html#vi-mock): 1. add a `__mocks__` folder at the root, but make sure to add vi.mock('module'); in the test file or 2. add a test set up file whih handles your mocks and then add it to your vitest config in the \"setupFiles\" array vitest.dev/config/#setupfiles. From the docs: ...if you don't call vi.mock, modules are not mocked automatically. To replicate Jest's automocking behaviour, you can call vi.mock for each required module inside setupFiles.\n- @ChristopherBorchert why the docs do not provide an example is beyond me","metadata":{"transformedAt":"2026-08-18T18:33:46.413Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":37,"estimatedTokens":427}}253{"id":"stack-76073916","source":"stackoverflow","questionId":76073916,"title":"Load file as string in vue/vite project","tags":["javascript","vuejs3","fetch-api","vite","javascript-marked"],"text":"Title: Load file as string in vue/vite project\nTags: javascript, vuejs3, fetch-api, vite, javascript-marked\nSource: Stack Overflow\n\nQuestion:\nI have a vue/vie project in which I'm trying to read a markdown file I have into html using marked.\n\nI attempted to use the fetch api to import it as a string, but only because I couldn't figure out how to use node.js code in vue.\n\nHere's the vue file:\n\n```\n\nimport { marked } from 'marked'\n\nexport default {\n data() {\n return {\n query: this.getQueryVariable(\"q\"),\n markdown: ''\n }\n },\n mounted() {\n fetch('../src/markdown/About.md')\n .then(response => response.text())\n .then(text => this.markdown = text)\n document.querySelector('.marked').innerHTML = marked.parse(this.markdown)\n }\n}\n\n \n \n\n```\n\n========================================\n\nTop Answer:\nWith Vite, you can import assets as strings using the `?raw` suffix and `async`/`await`:\n\n```\nconst markdownFileContent = (await import(`path/to/markdown/file.md?raw`)).default;\nconst htmlString = marked.parse(markdownFileContent);\n```\n\n========================================\n\nCode:\n```text\n<script setup>\nimport { marked } from 'marked'\n</script>\n\n<script>\nexport default {\n    data() {\n        return {\n            query: this.getQueryVariable(\"q\"),\n            markdown: ''\n        }\n    },\n    mounted() {\n        fetch('../src/markdown/About.md')\n            .then(response => response.text())\n            .then(text => this.markdown = text)\n        document.querySelector('.marked').innerHTML = marked.parse(this.markdown)\n    }\n}\n</script>\n\n<template>\n    <div class='marked'>\n    </div>\n</template>\n```\n\n```js\nfetch(\"../src/markdown/About.md\")\n  .then((response) => response.text())\n  .then((text) => {\n    this.markdown = text;\n    document.querySelector(\".marked\").innerHTML = marked.parse(this.markdown);\n  });\n```\n\n```js\nconst markdownFileContent = (await import(`path/to/markdown/file.md?raw`)).default;\nconst htmlString = marked.parse(markdownFileContent);\n```\n\n```text\n?raw\n```\n\n```text\nasync\n```\n\n```text\nawait\n```\n\n```text\nimport markdownString from './shader.md?raw'\n```\n\n```text\nexport default defineConfig({\n   ...\n   assetsInclude: [\"**/*.md\"],\n}\n```\n\n```text\n?raw\n```\n\n```text\nvite.config\n```\n\n========================================\n\nComments:\n- Hello @abaumg , I liked your solution to load a text file and if I do with a window file where as path I put like `'C:\\\\test.txt'` then it works well... but if I load a text file that has no extensions like `&#47;proc&#47;cpuinfo` that import treats it as URL so it can't be resolved...neither if I set as `.&#47;&#47;proc&#47;&#47;cpuinfo`... how I can set the stuff to make reading the file? Thanks in advance!\n- Thanks. Also, for TypeScript you need some declaration similar to this: `declare module '*?raw' { const text: string; export default text }`\n- HI @Kong , I am facing an obstacle about that: in React Vite, if 1) I try to read on a Windows machine through browser a text file putting just `c:\\\\test.txt` then it reads it perfectly and I can show the content; 2) if I try to read `&#47;home&#47;myuser&#47;test.txt` on Android's browser then it threats like an URL so I can't read the file... how I can tell to read that path just like absolute pat as like on Windows?","metadata":{"transformedAt":"2026-08-18T18:33:46.413Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":127,"estimatedTokens":812}}254{"id":"stack-73288452","source":"stackoverflow","questionId":73288452,"title":"Installing font-awesome with Laravel 9 (Vite)","tags":["laravel","npm","sass","font-awesome","vite"],"text":"Title: Installing font-awesome with Laravel 9 (Vite)\nTags: laravel, npm, sass, font-awesome, vite\nSource: Stack Overflow\n\nQuestion:\ni'm using Laravel 9 which doesn't use mix anymore, but vite, to bundle resources, i'm also not using any preprocessors like sass or less and don't really know anything about them.\n\nEvery text about adding font awesome on the internet is for Laravel 8 and bellow which didn't use vite. Also they all require me to put the font awesome packs in app.sass file which i don't have and am not sure how exactly to install and use.\n\nI'm a student and am developing the application for an offline presentation, so no CDN's allowed.\n\nCould somebody explain the process of installing font awesome without sass and with vite, or if sass is a must, explain to me in short, what it is, how do i install it, and use it.\n\nThanks in advance.\n\n========================================\n\nTop Answer:\nSo i figured it out. Turns out it's as simple as running\n\n```\nnpm install @fortawesome/fontawesome-free\n```\n\nand then adding\n\n```\n@import \"@fortawesome/fontawesome-free/css/all.css\";\n```\n\nto your app.css file.\nYou can then proceed to use\n\n```\n**\n```\n\nand similar in your code.\n\n========================================\n\nCode:\n```text\nnpm install @fortawesome/fontawesome-free\n```\n\n```text\n@import \"@fortawesome/fontawesome-free/css/all.css\";\n\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n```text\nnpm run build or npm run dev\n```\n\n```text\nnpm install @fortawesome/fontawesome-free\n```\n\n```text\n@import \"@fortawesome/fontawesome-free/css/all.css\";\n```\n\n```text\n<i class=\"fa-solid fa-cart-shopping\"></i>\n```\n\n```text\nexport default defineConfig({\n    //... \n          plugins: [\n        laravel([\n            'resources/css/app.css',\n        ]),\n    ],\n    resolve: {\n        alias: {\n            '~fa': path.resolve(__dirname, 'node_modules/@fortawesome/fontawesome-free/scss'),\n        }\n    },\n});\n```\n\n```text\n$fa-font-path:\"~fa/../webfonts\";\n@import \"~fa/fontawesome.scss\";\n@import \"~fa/solid.scss\";\n@import \"~fa/regular.scss\";\n@import \"~fa/brands.scss\";\n```\n\n```text\nvite.config.cs\n```\n\n```text\nresources/sass/app.scss\n```\n\n```text\nnpm install @fortawesome/fontawesome-free\n```\n\n```text\nimport '@fortawesome/fontawesome-free/js/fontawesome';\nimport '@fortawesome/fontawesome-free/js/solid';\n```\n\n```text\n<i class=\"fa-solid fa-sort\"></i>\n```\n\n```text\nnpm install @fortawesome/fontawesome-free\n```\n\n```text\n@import \"@fortawesome/fontawesome-free/css/all.css\";\n```\n\n```text\nnpm install @fortawesome/fontawesome-free\n```\n\n```text\n@import \"@fortawesome/fontawesome-free/css/fontawesome.min.css\";\n@import \"@fortawesome/fontawesome-free/css/solid.css\";\n```\n\n```text\nimport \"@fortawesome/fontawesome-free/js/fontawesome.min\"\nimport \"@fortawesome/fontawesome-free/js/solid.min\"\n```\n\n```text\nnpm run build\n```\n\n```text\n@fortawesome/fontawesome-free\n```\n\n```text\n/resources/css/app.css\n```\n\n```text\n/resources/js/app.js\n```\n\n========================================\n\nComments:\n- When running sail use: `sail npm run dev`\n- I uses karlhillx.medium.com/&hellip; tuto, similar to @Micha&#235;l explanations but with `import '@fortawesome&#47;fontawesome-free&#47;js&#47;all';`. I am not sure I have sass installed… no resources/sass folder, but it works.\n- welcome @Mark Ian, This answer is a duplicate of almost any of those put forward in 2022, over two years ago Please check our guide on how to write good answers here: stackoverflow.com/help/how-to-answer I understand you want to grow your rep, but look at how low mine is and I've been a mod for almost 10 years now :D. I'm sure there are plenty of Laravel questions you could help with, take a look around","metadata":{"transformedAt":"2026-08-18T18:33:46.413Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":159,"estimatedTokens":921}}255{"id":"stack-67616851","source":"stackoverflow","questionId":67616851,"title":"Vue3 / Vite: How to package components for publishing on npm","tags":["vue.js","vuejs3","npm-publish","vite"],"text":"Title: Vue3 / Vite: How to package components for publishing on npm\nTags: vue.js, vuejs3, npm-publish, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to export two web components in a public package on npm, using Vite with TypeScript.\n\nVite has a Library Mode which works well. The ESM and UMD files are both being transpiled into my `/dist` directory. My question is how to export the web components in the entry point file.\n\nI have an entry point file called `export.js`\n\n```\nimport AwesomeHeader from './components/AwesomeHeader.vue'\nimport AwesomeFooter from './components/AwesomeFooter.vue'\n\nexport default { // I feel like the problem is here.\n components: {\n AwesomeHeader: AwesomeHeader,\n AwesomeFooter: AwesomeFooter,\n }\n}\n```\n\nThe idea is that I'll `npm publish` the project and use it like this.\n\n```\nnpm i @sparkyspider/awesome-components #(ficticious example)\n```\n\n```\nimport {AwesomeHeader, AwesomeFooter} from '@sparkyspider/awesome-components' // does not find\n```\n\n*(AwesomeHeader and AwesomeFooter are not found as exports in the node_module, even though the JavaScript files are referenced / found)*\n\nMy package.json below:\n\n```\n{\n \"name\": \"@sparkyspider/awesome-components\",\n \"version\": \"1.0.8\",\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/awesome-components.umd.js\",\n \"module\": \"./dist/awesome-components.es.js\",\n \"exports\": {\n \".\": {\n \"import\": \"./dist/awesome-components.es.js\",\n \"require\": \"./dist/awesome-components.umd.js\"\n }\n },\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vue-tsc --noEmit && vite build\",\n \"serve\": \"vite preview\"\n },\n \"dependencies\": {\n \"vue\": \"^3.0.5\"\n },\n \"devDependencies\": {\n \"@vitejs/plugin-vue\": \"^1.2.2\",\n \"@vue/compiler-sfc\": \"^3.0.5\",\n \"typescript\": \"^4.1.3\",\n \"vite\": \"^2.3.3\",\n \"vue-tsc\": \"^0.0.24\"\n },\n}\n```\n\n========================================\n\nCode:\n```js\nimport AwesomeHeader from './components/AwesomeHeader.vue'\nimport AwesomeFooter from './components/AwesomeFooter.vue'\n\nexport default { // I feel like the problem is here.\n    components: {\n        AwesomeHeader: AwesomeHeader,\n        AwesomeFooter: AwesomeFooter,\n    }\n}\n```\n\n```bash\nnpm i @sparkyspider/awesome-components #(ficticious example)\n```\n\n```js\nimport {AwesomeHeader, AwesomeFooter} from '@sparkyspider/awesome-components' // does not find\n```\n\n```json\n{\n    \"name\": \"@sparkyspider/awesome-components\",\n    \"version\": \"1.0.8\",\n    \"files\": [\n        \"dist\"\n    ],\n    \"main\": \"./dist/awesome-components.umd.js\",\n    \"module\": \"./dist/awesome-components.es.js\",\n    \"exports\": {\n        \".\": {\n            \"import\": \"./dist/awesome-components.es.js\",\n            \"require\": \"./dist/awesome-components.umd.js\"\n        }\n    },\n    \"scripts\": {\n        \"dev\": \"vite\",\n        \"build\": \"vue-tsc --noEmit && vite build\",\n        \"serve\": \"vite preview\"\n    },\n    \"dependencies\": {\n        \"vue\": \"^3.0.5\"\n    },\n    \"devDependencies\": {\n        \"@vitejs/plugin-vue\": \"^1.2.2\",\n        \"@vue/compiler-sfc\": \"^3.0.5\",\n        \"typescript\": \"^4.1.3\",\n        \"vite\": \"^2.3.3\",\n        \"vue-tsc\": \"^0.0.24\"\n    },\n}\n```\n\n```text\n/dist\n```\n\n```text\nexport.js\n```\n\n```text\nnpm publish\n```\n\n```text\n{ component: ... }\n```\n\n```text\nAwesomeHeader\n```\n\n```text\nAwesomeFooter\n```\n\n```text\nexport { AwesomeHeader, AwesomeFooter }\n```\n\n```text\nexport.js\n```\n\n========================================\n\nComments:\n- Haha, such a simple answer - but it worked!","metadata":{"transformedAt":"2026-08-18T18:33:46.413Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":162,"estimatedTokens":843}}256{"id":"stack-75201705","source":"stackoverflow","questionId":75201705,"title":"How to set multiple aliases in vite react?","tags":["reactjs","vite","alias"],"text":"Title: How to set multiple aliases in vite react?\nTags: reactjs, vite, alias\nSource: Stack Overflow\n\nQuestion:\nVite by default does not support src alias like\n\n`import counterReducer from \"@src/pages/counter/counter.slice\";`\n\nEvery time you will have to pass the full relative path like this\n\n`import counterReducer from \"../../src/pages/counter/counter.slice\";`\n\nIs there any way we can shorten these relative paths?\n\n========================================\n\nCode:\n```text\nimport counterReducer from \"@src/pages/counter/counter.slice\";\n```\n\n```text\nimport counterReducer from \"../../src/pages/counter/counter.slice\";\n```\n\n```js\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react-swc\";\nimport path from \"path\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  resolve: {\n    alias: {\n      \"@\": path.resolve(__dirname, \"./src/\"),\n      components: `${path.resolve(__dirname, \"./src/components/\")}`,\n      public: `${path.resolve(__dirname, \"./public/\")}`,\n      pages: path.resolve(__dirname, \"./src/pages\"),\n      types: `${path.resolve(__dirname, \"./src/@types\")}`,\n    },\n  },\n});\n```\n\n```json\n\"baseUrl\": \".\",\n\"paths\": {\n  \"@/*\": [\"./src/*\", \"./dist/*\", \"\"],\n  \"pages/*\": [\"src/pages/*\"],\n  \"components/*\": [\"src/components/*\"],\n  \"types/*\": [\"src/@types/*\"],\n  \"public/*\": [\"public/*\"]\n}\n```\n\n========================================\n\nComments:\n- Okay, that initially solved my problem, but now when I import my component, the import looks like this: `import Container from '..&#47;Container'` but i wanted something like `import Container from '@components&#47;Container'`\n- Your import should look like this \"import Container from \"Container\", if this is not the case, there might be some configuration issue.\n- it works for me in one dir and doesn't work in other dir. Damn, I don't know why\n- @JonasTolentino maybe you need to modify your vscode settings, check stackoverflow.com/questions/77314336/&hellip;\n- Hi, do I need to install \"path\" package..? It doesn't come with a new react-typescript vite template.\n- You need to add the 'path' package, its a nodejs package, doesn't come with react-typescript template","metadata":{"transformedAt":"2026-08-18T18:33:46.413Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":66,"estimatedTokens":547}}257{"id":"stack-78818328","source":"stackoverflow","questionId":78818328,"title":"How to run Vitest tests parallel in Gitlab with multiple jobs","tags":["jestjs","gitlab","gitlab-ci","vite","vitest"],"text":"Title: How to run Vitest tests parallel in Gitlab with multiple jobs\nTags: jestjs, gitlab, gitlab-ci, vite, vitest\nSource: Stack Overflow\n\nQuestion:\nOur unit tests currently run in a single job on Gitlab. We are using React Vitest (800+ tests) but the job takes way to much time for our liking (7+ min). I saw that you can run multiple jobs in parallel in Gitlab. Anyone an idea on how to make a unit test parallel job in Gitlab that would devide our Vitest tests into smaller pieces and run them parallel?\n\nAlso a requisite is to eventually make 1 cobertura code coverage report that we then can use in Gitlab.\n\n========================================\n\nCode:\n```text\nweb:test:\n  stage: test\n  parallel: 7\n  variables:\n    VITE_CI_JOB_INDEX: $CI_NODE_INDEX\n    VITE_CI_PARALLEL_SETTING: $CI_NODE_TOTAL\n  script:\n    - npm run test:coverage\n  artifacts:\n    expire_in: '1 hrs'\n    paths:\n      - $WEB_DIR/coverage/**\n      - $WEB_DIR/test-report.xml\n```\n\n```text\nweb:test:coverage:\n  stage: test\n  needs:\n    - web:test\n  script:\n    - npm run test:coverage:merge\n    - ../build/merge-code-coverage-reports.sh\n  artifacts:\n    expire_in: '5 days'\n    paths:\n      - $WEB_DIR/coverage/**\n    reports:\n      coverage_report:\n        coverage_format: cobertura\n        path: $WEB_DIR/coverage/cobertura-coverage.xml\n  coverage: /All files[^|]*\\|[^|]*\\s+([\\d\\.]+)/\n```\n\n```text\nconst TESTS_PARALLEL_MODE = process.env.VITE_CI_JOB_INDEX && process.env.VITE_CI_PARALLEL_SETTING;\n\nexport default defineConfig({\n  test: {\n    globals: true,\n    testTimeout: 2000,\n    environment: 'jsdom',\n    setupFiles: './tests/setup.ts',\n    sequence: {\n      shuffle: false,\n      sequencer: TESTS_PARALLEL_MODE ? GitlabRunnerSequencer : null,\n    },\n    css: false,\n    coverage: {\n      all: true,\n      reporter: TESTS_PARALLEL_MODE ? ['cobertura', 'json', 'text'] : ['lcov', 'text'],\n      reportsDirectory: TESTS_PARALLEL_MODE ? `./coverage/${process.env.VITE_CI_JOB_INDEX}` : './coverage',\n      provider: 'v8',\n    },\n  },\n});\n```\n\n```text\nimport { BaseSequencer, Vitest, WorkspaceSpec } from 'vitest/node';\n\nclass GitlabRunnerSequencer extends BaseSequencer {\n  private gitlabJobIndex: number;\n\n  private gitlabParallelSetting: number;\n\n  constructor(ctx: Vitest) {\n    super(ctx);\n    this.gitlabJobIndex = Number(process.env.VITE_CI_JOB_INDEX || '0');\n    this.gitlabParallelSetting = Number(process.env.VITE_CI_PARALLEL_SETTING || '1');\n  }\n\n  public async sort(files: WorkspaceSpec[]): Promise<WorkspaceSpec[]> {\n    console.info(`VITE_CI_JOB_INDEX: ${this.gitlabJobIndex}`);\n    console.info(`VITE_CI_PARALLEL_SETTING: ${this.gitlabParallelSetting}`);\n\n    const sortedFiles = GitlabRunnerSequencer.sortByPath(files);\n    const testChunk = this.getChunkForCurrentGitlabRunner(sortedFiles);\n\n    console.info(`A total of ${testChunk.length} will be run`);\n\n    return testChunk;\n  }\n\n  static sortByPath(tests: WorkspaceSpec[]): WorkspaceSpec[] {\n    return tests.sort((a, b) => {\n      if (a[0].path < b[0].path) {\n        return -1;\n      }\n      if (a[0].path > b[0].path) {\n        return 1;\n      }\n      return 0;\n    });\n  }\n\n  getChunkForCurrentGitlabRunner(tests: WorkspaceSpec[]): WorkspaceSpec[] {\n    const chunkSize = tests.length / this.gitlabParallelSetting;\n    const currentChunkPositionRange = [Math.round(chunkSize * (this.gitlabJobIndex - 1)), Math.round(chunkSize * this.gitlabJobIndex)];\n\n    console.info(`Running test chunk ${currentChunkPositionRange[0]} - ${currentChunkPositionRange[1]} for this runner`);\n\n    return tests.filter((_, index) => index + 1 > currentChunkPositionRange[0] && index + 1 <= currentChunkPositionRange[1]);\n  }\n}\n\nexport default GitlabRunnerSequencer;\n```\n\n```text\nconst { createCoverageMap } = require('istanbul-lib-coverage');\nconst { createContext } = require('istanbul-lib-report');\nconst { create } = require('istanbul-reports');\nconst { resolve } = require('path');\nconst { sync } = require('glob');\n\nconsole.log('Generating final report...');\n\nconst coverageMap = createCoverageMap();\n\nconst REPORTS_FOLDER = 'coverage';\nconst coverageDir = resolve(__dirname, `../${REPORTS_FOLDER}`);\nconst reportFiles = sync(`${coverageDir}/*/coverage-final.json`);\n\nconst normalizeReport = (report) => {\n  const normalizedReport = { ...report };\n  Object.entries(normalizedReport).forEach(([k, v]) => {\n    if (v.data) normalizedReport[k] = v.data;\n  });\n  return normalizedReport;\n};\n\nreportFiles\n  .map((reportFile) => {\n    console.log(`Found report file: ${reportFile}`);\n    return require(reportFile);\n  })\n  .map(normalizeReport)\n  .forEach((report) => coverageMap.merge(report));\nconst context = createContext({\n  coverageMap,\n  dir: coverageDir,\n});\n\ncreate('cobertura', {}).execute(context);\nconsole.log(`Cobertura coverage report generated and outputted to ${coverageDir}`);\n```\n\n```text\n#!/bin/sh\n\nREPORT_FILE=\"coverage/cobertura-coverage.xml\"\n\necho \"Retrieving line rate code coverage percentage...\"\n\nBRANCHE_RATE=$(grep -o 'branch-rate=\"[^\"]*' $REPORT_FILE | sed 's/branch-rate=\"//')\nLINE_COVERAGE=${BRANCHE_RATE:2:2}.${BRANCHE_RATE:4:6}\n\necho \"All files          |   ${LINE_COVERAGE}\"\n\necho \"Cleaning up fractured reports...\"\n```\n\n```text\nnpm run test:coverage\n```\n\n```text\nvitest run --coverage\n```\n\n```text\nVITE_CI_JOB_INDEX\n```\n\n```text\nVITE_CI_PARALLEL_SETTING\n```\n\n```text\nsequencer.ts\n```\n\n```text\nweb:test:coverage\n```\n\n```text\ntest:coverage:merge\n```\n\n```text\nnode ./tests/merge-cobertura-reports.cjs\n```\n\n```text\nmerge-code-coverage-reports.sh\n```\n\n========================================\n\nComments:\n- Appreciate you sharing this as its a problem I'm in the middle of solving!\n- For us this is working perfectly for several months now. It really made our pipeline run way quicker","metadata":{"transformedAt":"2026-08-18T18:33:46.413Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":217,"estimatedTokens":1436}}258{"id":"stack-67978459","source":"stackoverflow","questionId":67978459,"title":"Vitejs | Uncaught Error: Dynamic require of \".svg\" is not supported","tags":["reactjs","vite"],"text":"Title: Vitejs | Uncaught Error: Dynamic require of \".svg\" is not supported\nTags: reactjs, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use `react-flagpack` in my project that uses Vite, but whenever I use it i get the following error:\n\n**Uncaught Error: Dynamic require of \"node_modules/flagpack-core/dist/flags/cDBuMQWP.svg\" is not supported**\n\nIs this an issue with Vite? or am I doing something wrong.\n\nThanks in advance!\n\n========================================\n\nTop Answer:\nCan you use this :\n\n```\nnpm i --save @originjs/vite-plugin-require-context\n```\n\nThen Add `ViteRequireContext` into `vit.config.js` :\n\n```\nimport ViteRequireContext from \"@originjs/vite-plugin-require-context\";\nexport default defineConfig(() => { \n plugins: [\n ViteRequireContext(),\n ],\n}\n```\n\n========================================\n\nCode:\n```text\nreact-flagpack\n```\n\n```text\nyarn add @originjs/vite-plugin-commonjs -D\n\nor\n\n npm i @originjs/vite-plugin-commonjs -D\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport { viteCommonjs, esbuildCommonjs } from '@originjs/vite-plugin-commonjs';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    viteCommonjs(),\n  ],\n  optimizeDeps: {\n    esbuildOptions: {\n      plugins: [\n        // Solves:\n        // https://github.com/vitejs/vite/issues/5308\n        esbuildCommonjs(['react-flagpack'])\n      ],\n    },\n  },\n\n});\n```\n\n```text\nvite.config\n```\n\n```text\ntiny-react-slider\n```\n\n```text\nrequire\n```\n\n```text\n.css\n```\n\n```text\nnpm i --save @originjs/vite-plugin-require-context\n```\n\n```text\nimport ViteRequireContext from \"@originjs/vite-plugin-require-context\";\nexport default defineConfig(() => {  \n   plugins: [\n        ViteRequireContext(),\n    ],\n}\n```\n\n```text\nViteRequireContext\n```\n\n```text\nvit.config.js\n```\n\n```text\n\"type\":\"module\"\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport ViteRequireContext from \"@originjs/vite-plugin-require-context\";\n\n\nconst path = require('path');\n\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue(), ViteRequireContext()],\n\n  resolve:  {\n    alias:  {\n      \"@\": path.resolve(__dirname, \"./src\")\n    },\n\n    extensions:  [\n      \".mjs\", \".js\", \".ts\",\n      \".jsx\", \".tsx\", \".json\",\n      \".vue\"\n    ]\n  }\n})\n```\n\n```text\npackage.json\n```\n\n```text\nvite.config.js\n```\n\n========================================\n\nComments:\n- given the fact that google brings up tons of vite-svg-loader I dont think it works out of the box.","metadata":{"transformedAt":"2026-08-18T18:33:46.413Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":150,"estimatedTokens":624}}259{"id":"stack-77288512","source":"stackoverflow","questionId":77288512,"title":"Vite + Vue 3 built project Content-Security-Policy Error (CSP) 'script-src \"self\"' because of new Function constructor in built files","tags":["vite","rollup","content-security-policy"],"text":"Title: Vite + Vue 3 built project Content-Security-Policy Error (CSP) 'script-src \"self\"' because of new Function constructor in built files\nTags: vite, rollup, content-security-policy\nSource: Stack Overflow\n\nQuestion:\nI have added CSP header 'Content-Security-Policy': \"script-src 'self'\", built project, then got error:\n\n*Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: \"script-src 'self'\".*\n\nwhich disables using eval & Function constructors. Is it possible to get rid of using Function constructor in built files?\n\nhttps://i.sstatic.net/DXK33.png\n\nhttps://i.sstatic.net/mIUfv.png\n\n========================================\n\nTop Answer:\nSeveral months later, `vue-i18n` v10 *(which is in beta at writing)* seems to resolve this.\n\nThe reason is that `vue-i18n` v10 by default enables JIT compilation. This specific issue (CSP problems) is also mentioned as one of the reasons for this change:\n\nReason: CSP problems can be solved and dynamic resources can be supported\n\nThis means the flag `__INTLIFY_JIT_COMPILATION__` mentioned in the answer by @Bekzod is no longer needed starting with `vue-i18n` `v10.0.0-alpha.5` and above (see changelog).\n\nJust installing `v10.0.0-beta.1` (at time of writing) without configuring any other settings resolved the `unsafe-eval` CSP errors for me.\n\n========================================\n\nCode:\n```text\n__INTLIFY_JIT_COMPILATION__: true\n```\n\n```text\nvue-i18n\n```\n\n```text\nvue-i18n\n```\n\n```text\n__INTLIFY_JIT_COMPILATION__\n```\n\n```text\nvue-i18n\n```\n\n```text\nv10.0.0-alpha.5\n```\n\n```text\nv10.0.0-beta.1\n```\n\n```text\nunsafe-eval\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.414Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":62,"estimatedTokens":418}}260{"id":"stack-76730788","source":"stackoverflow","questionId":76730788,"title":"CSP style-src-directive with Vue/Vite","tags":["vue.js","vite","content-security-policy"],"text":"Title: CSP style-src-directive with Vue/Vite\nTags: vue.js, vite, content-security-policy\nSource: Stack Overflow\n\nQuestion:\nI'm trying to implement a Content-Security-Policy (CSP) for a webapp that uses Vue + Vite for it's frontend. As far as I understand the javascript-code Vue/Vite produces is generally compliant with most forms of CSP, even though it's difficult to find any explicit information on this.\n\nNow, here is the particular issue I stumbled upon:\n\nPart of the CSP-Policy I'm using is `style-src 'self'`. Even though this would normally block inline-styles it doesn't seem to block styles that are set with the vue-style-binding like so:\n\n```\n\n```\n\nnor does it seem to block inline-styles that are placed in a .vue single-file-component like so:\n\n```\n\n```\n\nEven though I don't mind the first one, as this means I don't have to set `'unsafe-inline'` for style-src, I'm kind of wondering why the second example won't be blocked by a `style-src 'self'` (or even `style-src 'none'`). Is this behavior generally intended with vue/vite?\n\nUnfortunately I couldn't really find any specific information regarding CSP usage with vue/vite in their respective official docs. Any help would be appreciated.\n\n========================================\n\nCode:\n```text\n<div :style=\"{ 'font-size': fontSize + 'px' }\"></div>\n```\n\n```text\n<template>\n<div style=\"background: red\">\n</template>\n```\n\n```text\nstyle-src 'self'\n```\n\n```text\n'unsafe-inline'\n```\n\n```text\nstyle-src 'self'\n```\n\n```text\nstyle-src 'none'\n```\n\n```text\ndocument.getElementById('id').style.background = 'red';\n```\n\n========================================\n\nComments:\n- Looks like same here: stackoverflow.com/questions/77627472/&hellip;\n- I suppose that would make sense, though it seems strange at first glance an inline style would be converted like that. Part of the build output for the example is `()=>F(\"div\", {style:{background:\"red\"}}` so it seems reasonable that vue would use that with CSSOM.","metadata":{"transformedAt":"2026-08-18T18:33:46.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":63,"estimatedTokens":491}}261{"id":"stack-76366628","source":"stackoverflow","questionId":76366628,"title":"How to import types from npm package using vite?","tags":["typescript","npm","build","vite"],"text":"Title: How to import types from npm package using vite?\nTags: typescript, npm, build, vite\nSource: Stack Overflow\n\nQuestion:\nI'm writing a package with a couple of `ts` functions, which will be used by several repos (mobile and web app). As a build tool, our team is always using `vite`, therefore it is also used in the repo.\n\nI have the following `vite.config.ts` file:\n\n```\nimport { defineConfig } from 'vite'\nimport dts from 'vite-plugin-dts'\n\nexport default defineConfig({\n build: {\n lib: { // required, because it is actually the library, whitout any 'index.html'\n name: 'project-name',\n entry: './src/index.ts',\n fileName: 'index',\n formats: ['cjs', 'umd'] // not sure about this line, but in helped to generare 'index.js' and 'index.umd.js' files in the build\n },\n outDir: 'dist'\n },\n plugins: [\n dts({\n insertTypesEntry: true // without this line, the `index.d.ts` file is not generating at all\n })\n ]\n})\n```\n\nAnd the following `tsconfig.json`:\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"esnext\",\n \"module\": \"esnext\",\n \"moduleResolution\": \"node\",\n \"esModuleInterop\": true,\n \"strict\": true,\n \"sourceMap\": true,\n \"declaration\": true,\n \"outDir\": \"dist\",\n \"declarationDir\": \"dist\",\n \"baseUrl\": \".\",\n \"paths\": {\n \"@/*\": [\n \"src/*\"\n ]\n },\n \"lib\": [\n \"esnext\"\n ]\n },\n \"include\": [\n \"src/**/*.ts\",\n \"src/**/*.tsx\"\n ],\n \"exclude\": [\n \"node_modules\",\n \"dist\"\n ]\n}\n```\n\n`package.json` contains the following paths:\n\n```\n{\n ...,\n \"main\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"module\": \"./dist/index.umd.js\",\n \"exports\": {\n \".\": {\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.umd.js\"\n }\n },\n \"scripts\": {\n \"build\": \"vite build\"\n },\n ...\n}\n```\n\nThe problem is, when the package is installed in other repos, the types are not loaded, so all classes have `any` type, all functions are of `any` type and so on. Even types are not imported validly and are marked by VS Code as `any`. Type information is important for me, and I want it to be exported validly\n\nWhat have I tried:\n\n- Usage of `vite-tsconfig-paths` plugin instead of `vite-plugin-dts`. It didn't even generate any `*.d.ts` file in the `/dist` folder\n\n- Different `tsconfig` options. It feels like the plugin doesn't even see the `tsconfig.json` file (named validly, is also in a root directory)\n\nAdditional comments:\n\n- types are exported using syntax `export type ...`\n\n- in `src/index.ts` there is an import of everything, including types\n\n- the `index.d.ts` file, which is generated now, contains single line:\n\n```\nexport * from './index'\n```\n\nWhich means, it exports just the content of `index.js`, generated by the build\n\n========================================\n\nCode:\n```js\nimport { defineConfig } from 'vite'\nimport dts from 'vite-plugin-dts'\n\nexport default defineConfig({\n  build: {\n    lib: { // required, because it is actually the library, whitout any 'index.html'\n      name: 'project-name',\n      entry: './src/index.ts',\n      fileName: 'index',\n      formats: ['cjs', 'umd'] // not sure about this line, but in helped to generare 'index.js' and 'index.umd.js' files in the build\n    },\n    outDir: 'dist'\n  },\n  plugins: [\n    dts({\n      insertTypesEntry: true // without this line, the `index.d.ts` file is not generating at all\n    })\n  ]\n})\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"target\": \"esnext\",\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"esModuleInterop\": true,\n    \"strict\": true,\n    \"sourceMap\": true,\n    \"declaration\": true,\n    \"outDir\": \"dist\",\n    \"declarationDir\": \"dist\",\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@/*\": [\n        \"src/*\"\n      ]\n    },\n    \"lib\": [\n      \"esnext\"\n    ]\n  },\n  \"include\": [\n    \"src/**/*.ts\",\n    \"src/**/*.tsx\"\n  ],\n  \"exclude\": [\n    \"node_modules\",\n    \"dist\"\n  ]\n}\n```\n\n```json\n{\n  ...,\n  \"main\": \"./dist/index.js\",\n  \"types\": \"./dist/index.d.ts\",\n  \"module\": \"./dist/index.umd.js\",\n  \"exports\": {\n    \".\": {\n      \"import\": \"./dist/index.js\",\n      \"require\": \"./dist/index.umd.js\"\n    }\n  },\n  \"scripts\": {\n    \"build\": \"vite build\"\n  },\n  ...\n}\n```\n\n```text\nexport * from './index'\n```\n\n```text\nts\n```\n\n```text\nvite\n```\n\n```text\nvite.config.ts\n```\n\n```text\ntsconfig.json\n```\n\n```text\npackage.json\n```\n\n```text\nany\n```\n\n```text\nany\n```\n\n```text\nany\n```\n\n```text\nvite-tsconfig-paths\n```\n\n```text\nvite-plugin-dts\n```\n\n```text\n*.d.ts\n```\n\n```text\n/dist\n```\n\n```text\ntsconfig\n```\n\n```text\ntsconfig.json\n```\n\n```text\nexport type ...\n```\n\n```text\nsrc/index.ts\n```\n\n```text\nindex.d.ts\n```\n\n```text\nindex.js\n```\n\n```text\nvite\n```\n\n```text\nwebpack\n```\n\n```text\ntsc\n```\n\n========================================\n\nComments:\n- Did you ever discover a solution to this? In the same boat\n- @JabbaWook, yes. The solution is - you just need `tsc` and nothing more to build pure ts repo. In my case `vite` was redundant\n- Thanks for getting back to me! I'll give tsc a go!","metadata":{"transformedAt":"2026-08-18T18:33:46.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":25,"totalLines":280,"estimatedTokens":1208}}262{"id":"stack-79656877","source":"stackoverflow","questionId":79656877,"title":"Angular development server cannot find the external JavaScript file, but works fine with a production build","tags":["node.js","angular","vite"],"text":"Title: Angular development server cannot find the external JavaScript file, but works fine with a production build\nTags: node.js, angular, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to build a \"hello world\" application with some \"external\" assets. When I run `npm run build` and serve the content via nginx, everything works fine. But if I do `ng serve` it fails to find the JavaScript file.\n\nAngular CLI: 20.0.1; Node 22.15.1; npm 10.9.2\n\nCreate new project named angular via `ng new angular --routing` which created a `public` directory for assets.\n\nI added the following content to `public/js/external.js`:\n\n```\nexport const externalConst = \"angular\";\n export function showAlert() {\n alert(\"This is an external JavaScript file.\");\n }\n```\n\nAnd I created `public/assets/css/external.css` as a zero-length file.\n\nFinally, modifying the supplied `index.html` to include both files looks like this:\n\n```\n\n \n \n Angular\n \n \n \n \n \n \n \n \n \n import { showAlert } from \"/js/external.js\";\n showAlert();\n \n \n\n```\n\nRun `npm run build`, and see that `dist/angular/browser` contains both files under `/assets` and `/js` and that the `index.html` file has retained the references. Serve the content under `dist/angular/browser` via nginx, and `index.html` immediately presents an alert of \"This is an external Javascript file.\" as expected, and Developer Tools shows me that both JS and CSS files were loading correctly with no errors. Great!\n\nRun `ng serve` and point the browser at port 4200 and things are not so good. In the console window, I get:\n\n```\n[vite] Internal server error: Failed to resolve import \"/js/external.js\" from \"/index.html?html-proxy&index=0.js\". Does the file exist?\n Plugin: vite:import-analysis\n File: /index.html?html-proxy&index=0.js:2:34\n 1 |\n 2 | import { showAlert } from \"/js/external.js\";\n | ^\n 3 | showAlert();\n 4 |\n at TransformPluginContext._formatLog (file:///home/marcus/angular/node_modules/vite/dist/node/chunks/dep-DBxKXgDP.js:42499:41)\n at TransformPluginContext.error (file:///home/marcus/angular/node_modules/vite/dist/node/chunks/dep-DBxKXgDP.js:42496:16)\n at normalizeUrl (file:///home/marcus/angular/node_modules/vite/dist/node/chunks/dep-DBxKXgDP.js:40475:23)\n [...]\n```\n\nAnd in the browser there's a giant popup with similar text, and via Developer Tools I can see that `index.html?html-proxy&index=0.js` returned a 500 error.\n\nSo presumably I'm not adding these files in quite the right way. I've seen some examples where entries have been added in the `scripts` and `styles` blocks in `angular.json` but I don't fully understand the implications of that - it seems like that's making it \"internal\" rather than external and that the files get \"packed\" that way.\n\nWhat I'm actually trying to do is create a basic app that imports the GOVUK Frontend Framework using the instructions here but this hasn't worked either (JavaScript doesn't load and \"nunjucks\" doesn't appear to work) that I've tried to create the smallest reproducible test-case with external files and I immediately hit this problem.\n\n========================================\n\nCode:\n```text\nexport const externalConst = \"angular\";\n  export function showAlert() {\n    alert(\"This is an external JavaScript file.\");\n  }\n```\n\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <title>Angular</title>\n    <base href=\"/\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <link rel=\"icon\" type=\"image/x-icon\" href=\"favicon.ico\" />\n    <link rel=\"stylesheet\" href=\"assets/css/external.css\" />\n  </head>\n  <body>\n    <app-root></app-root>\n    <script type=\"module\" src=\"js/external.js\"></script>\n    <script type=\"module\">\n      import { showAlert } from \"/js/external.js\";\n      showAlert();\n    </script>\n  </body>\n</html>\n```\n\n```text\n[vite] Internal server error: Failed to resolve import \"/js/external.js\" from \"/index.html?html-proxy&index=0.js\". Does the file exist?\n    Plugin: vite:import-analysis\n            File: /index.html?html-proxy&index=0.js:2:34\n    1  |\n    2  |        import { showAlert } from \"/js/external.js\";\n       |                                   ^\n    3  |        showAlert();\n    4  |\n        at TransformPluginContext._formatLog (file:///home/marcus/angular/node_modules/vite/dist/node/chunks/dep-DBxKXgDP.js:42499:41)\n        at TransformPluginContext.error (file:///home/marcus/angular/node_modules/vite/dist/node/chunks/dep-DBxKXgDP.js:42496:16)\n        at normalizeUrl (file:///home/marcus/angular/node_modules/vite/dist/node/chunks/dep-DBxKXgDP.js:40475:23)\n  [...]\n```\n\n```text\nnpm run build\n```\n\n```text\nng serve\n```\n\n```text\nng new angular --routing\n```\n\n```text\npublic\n```\n\n```text\npublic/js/external.js\n```\n\n```text\npublic/assets/css/external.css\n```\n\n```text\nindex.html\n```\n\n```text\nnpm run build\n```\n\n```text\ndist/angular/browser\n```\n\n```text\n/assets\n```\n\n```text\n/js\n```\n\n```text\nindex.html\n```\n\n```text\ndist/angular/browser\n```\n\n```text\nindex.html\n```\n\n```text\nng serve\n```\n\n```text\nindex.html?html-proxy&index=0.js\n```\n\n```text\nscripts\n```\n\n```text\nstyles\n```\n\n```text\nangular.json\n```\n\n```text\n<script type=\"module\" vite-ignore>\n...\n```\n\n```text\nimport 'govuk-frontend/dist/govuk/govuk-frontend.min.js'\n```\n\n```text\n<script type=\"module\">\n```\n\n```text\n/js/external.js\n```\n\n```text\nsrc\n```\n\n```text\nvite-ignore\n```\n\n```text\ngovuk-frontend\n```\n\n========================================\n\nComments:\n- Vite processes module import as it normally does and fails to find it in src. Try . This could be XY problem because the instruction you refer seems to describe the scenario for plain app that doesn't use build tools. You probably need to import govuk-frontend/dist/govuk/govuk-frontend.min.js within the app\n- Thanks @EstusFlask, this did solve my specific problem as described, so if you'd like to put it as the answer I will then accept it. Meanwhile, I got the GOVUK Frontend working without needing this, but I was happy to learn about 'vite-ignore'.","metadata":{"transformedAt":"2026-08-18T18:33:46.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":29,"totalLines":227,"estimatedTokens":1492}}263{"id":"stack-77861724","source":"stackoverflow","questionId":77861724,"title":"AntD and Vite: is it normal that only a single Button component generates a big bundle?","tags":["reactjs","vite","antd","tree-shaking"],"text":"Title: AntD and Vite: is it normal that only a single Button component generates a big bundle?\nTags: reactjs, vite, antd, tree-shaking\nSource: Stack Overflow\n\nQuestion:\nI'm using AntD and dealing with huge bundle results. I know for a fact that Vite does tree shaking by default and antD should be compatible with it.\n\nBut if for example you create a vite app, install and and import only a `Button` component your bundle will be huge:\n\n- `npm create vite@latest test -- --template react && cd test`\n\n- `npm install antd`\n\n- Import `Button` inside `./src/app.jsx` and use it somewhere.\n\n- Do `npm run build` and see the total amount of bundle.\n\nIn my case it is something like this:\n\n```\n> vite build\n\nvite v5.0.12 building for production...\n✓ 1308 modules transformed.\ndist/index.html 0.39 kB │ gzip: 0.27 kB\ndist/assets/index-mnVFW9LP.js 267.99 kB │ gzip: 88.34 kB\n✓ built in 3.73s\n```\n\nConsidering that by default the Vite boilerplate will have 142kb, if we rest that to 268 we still have 126kb for a single button. Is this fine or maybe vite is not doing the tree shaking?\n\nThanks in advance for any help or insights!\n\n========================================\n\nCode:\n```bash\n> vite build\n\nvite v5.0.12 building for production...\n✓ 1308 modules transformed.\ndist/index.html                  0.39 kB │ gzip:  0.27 kB\ndist/assets/index-mnVFW9LP.js  267.99 kB │ gzip: 88.34 kB\n✓ built in 3.73s\n```\n\n```text\nButton\n```\n\n```text\nnpm create vite@latest test -- --template react && cd test\n```\n\n```text\nnpm install antd\n```\n\n```text\nButton\n```\n\n```text\n./src/app.jsx\n```\n\n```text\nnpm run build\n```\n\n```text\nButton\n```\n\n```text\nantd\n```\n\n```text\n126kb\n```\n\n```text\nimport { Button } from 'antd'\n```\n\n```text\n269.45kb\n```\n\n```text\nimport Button from '../node_modules/antd/es/button/button'\n```\n\n```text\n269.45kb\n```\n\n```text\nBreadCrumbs\n```\n\n```text\nVite\n```\n\n```text\nantd\n```\n\n========================================\n\nComments:\n- Could you with us how you use the Button inside your app please It would help\n- @ArrayConstructor hi thanks for the response, I created two Proof of Concepts, one with vite anotherone with Nx, also opened an Issue on Nx github repo - the PoCs are linked inside the issue: github.com/nrwl/nx/issues/21351 (when doing code splitting it \"helps\" although you can see that the 260 kB size persists also with a vite app...). I think it's the barrel export, for some reason it doesn't tree shake well.\n- @ArrayConstructor I also opened a topic on Discussion inside antd github repository but it I don't solve the problem: github.com/ant-design/ant-design/discussions/47102\n- Could it be possible to tell antd to not use those huge styles files? I think that they are increasing the size. Anyway thanks for the help, at least now I understand the reason.\n- I'm sorry, I believe it's not possible sadly","metadata":{"transformedAt":"2026-08-18T18:33:46.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":118,"estimatedTokens":705}}264{"id":"stack-75081816","source":"stackoverflow","questionId":75081816,"title":"How to set up TypeScript and SCSS as the default languages for script and style of Vue components with Vite?","tags":["typescript","vue.js","sass","vite"],"text":"Title: How to set up TypeScript and SCSS as the default languages for script and style of Vue components with Vite?\nTags: typescript, vue.js, sass, vite\nSource: Stack Overflow\n\nQuestion:\nI have created a project with Vue 2.8 and Vite. To use TypeScript and SCSS I have to explicitly indicate it in every component:\n\n``\n\n``\n\nGiven the project uses **Vite**, how do I set TypeScript as the default script language, and SCSS as the default schema for style?\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n```\n\n```text\n<style scoped lang=\"scss\">\n```\n\n```text\n{\n  \"vue-ts-sfc\": {\n    \"prefix\": \"sfc\",\n    \"body\": [\n      \"<template>\",\n      \"  <div class=\\\"container\\\">\",\n      \"    <!-- content here -->\",\n      \"  </div>\",\n      \"</template>\\n\",\n      \"<script setup lang=\\\"ts\\\">\",\n      \"</script>\\n\",\n      \"<style lang=\\\"scss\\\" scoped>\",\n      \".container {\",\n      \"  box-sizing: border-box;\",\n      \"}\",\n      \"</style>\"\n    }\n}\n```\n\n========================================\n\nComments:\n- AFAIK, you can't. You have to specify it everytime. But you can save time by create a snippet in your IDE to auto generate this for you.\n- Thanks for the effort, but your answer doesn't provide an actual answer to the question.","metadata":{"transformedAt":"2026-08-18T18:33:46.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":50,"estimatedTokens":312}}265{"id":"stack-75991432","source":"stackoverflow","questionId":75991432,"title":"How to bundle a commonjs in vite?","tags":["vite","es6-modules","commonjs","bundling-and-minification","rollupjs"],"text":"Title: How to bundle a commonjs in vite?\nTags: vite, es6-modules, commonjs, bundling-and-minification, rollupjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to bundle a dependency (named flickity) that uses `require`, using `vite` so that I can use it for some client side javascript. I am aware that client side browser doesn't support node's `require` statements, as such, I am trying to bundle it using `vite` and essentially converting it to be browser friendly.\n\n`vite` is using `rollup` under the hood so I should be able to accomplish this by using @rollup/plugin-commonjs to vite's build options.\n\nMinimal `vite.config.js`:\n\n```\nimport { defineConfig } from \"vite\";\nimport { splitVendorChunkPlugin } from \"vite\";\n\nimport { resolve } from \"path\";\n\nconst extensions = [\".js\", \".jsx\", \".ts\", \".tsx\"];\n\nconst root = resolve(__dirname, \"src\");\nconst outDir = resolve(__dirname, \"docs\");\n\nexport default defineConfig({\n plugins: [splitVendorChunkPlugin()],\n\n base: \"./\",\n publicDir: false,\n mode: \"Development\",\n root,\n\n build: {\n target: \"es2020\",\n\n outDir,\n emptyOutDir: true,\n rollupOptions: {\n input: {\n main: resolve(root, \"script.ts\"),\n flickity: resolve(root, \"flickity\", \"flickity.pkgd.min.js\"),\n\n index: resolve(root, \"index.html\"),\n },\n },\n\n modulePreload: {\n polyfill: false,\n },\n\n commonjsOptions: {\n extensions: extensions,\n },\n },\n\n resolve: {\n extensions: [\".cjs\", \".mjs\", \".js\", \".mts\", \".ts\", \".jsx\", \".tsx\", \".json\"],\n mainFields: [\"module\", \"main\", \"jsnext:main\", \"browser\"],\n },\n});\n```\n\nWith that tried, it still didn't worked and was still not converting the `require` statements.\n\nA portion of the output file is included here and as you can see, the `require` statement is still not converted:\n\n```\nvar G=Object.defineProperty;var K=(r,i,c)=>i in r?G(r,i,{enumerable:!0,configurable:!0,writable:!0,value:c}):r[i]=c;var Y=(r,i)=>()=>(i||r((i={exports:{}}).exports,i),i.exports);var A=(r,i,c)=>(K(r,typeof i!=\"symbol\"?i+\"\":i,c),c);import{a as _,$ as C}from\"./vendor-8d31bf49.js\";var nt=Y((ot,y)=>{/*!\n * Flickity PACKAGED v2.3.0\n * Touch, responsive, flickable carousels\n *\n * Licensed GPLv3 for open source use\n * or Flickity Commercial License for commercial use\n *\n * https://flickity.metafizzy.co\n * -2021 Metafizzy\n */(function(r,i){typeof define==\"function\"&&define.amd?define(\"jquery-bridget/jquery-bridget\",[\"jquery\"],function(c){return i(r,c)}):typeof y==\"object\"&&y.exports?y.exports=i(r,require(\"jquery\")):r.jQueryBridget=i(r,r.jQuery)})(window,function(i,c){var l=Array.prototype.slice,s=i.console,n=typeof s>\"u\"?function(){}:function(e)\n--------------/* require statement is still here */-------------------------------------------------------------------------------------------------------------------------------^^^\n```\n\nI am porting my project from `webpack` to `vite` so I am quite new to this. Could this be a bug on vite? rollup? or there's just something wrong with my configuration?\n\n========================================\n\nCode:\n```js\nimport { defineConfig } from \"vite\";\nimport { splitVendorChunkPlugin } from \"vite\";\n\nimport { resolve } from \"path\";\n\nconst extensions = [\".js\", \".jsx\", \".ts\", \".tsx\"];\n\nconst root = resolve(__dirname, \"src\");\nconst outDir = resolve(__dirname, \"docs\");\n\nexport default defineConfig({\n    plugins: [splitVendorChunkPlugin()],\n\n    base: \"./\",\n    publicDir: false,\n    mode: \"Development\",\n    root,\n\n    build: {\n        target: \"es2020\",\n\n        outDir,\n        emptyOutDir: true,\n        rollupOptions: {\n            input: {\n                main: resolve(root, \"script.ts\"),\n                flickity: resolve(root, \"flickity\", \"flickity.pkgd.min.js\"),\n\n                index: resolve(root, \"index.html\"),\n            },\n        },\n\n        modulePreload: {\n            polyfill: false,\n        },\n\n        commonjsOptions: {\n            extensions: extensions,\n        },\n    },\n\n    resolve: {\n        extensions: [\".cjs\", \".mjs\", \".js\", \".mts\", \".ts\", \".jsx\", \".tsx\", \".json\"],\n        mainFields: [\"module\", \"main\", \"jsnext:main\", \"browser\"],\n    },\n});\n```\n\n```text\nvar G=Object.defineProperty;var K=(r,i,c)=>i in r?G(r,i,{enumerable:!0,configurable:!0,writable:!0,value:c}):r[i]=c;var Y=(r,i)=>()=>(i||r((i={exports:{}}).exports,i),i.exports);var A=(r,i,c)=>(K(r,typeof i!=\"symbol\"?i+\"\":i,c),c);import{a as _,$ as C}from\"./vendor-8d31bf49.js\";var nt=Y((ot,y)=>{/*!\n * Flickity PACKAGED v2.3.0\n * Touch, responsive, flickable carousels\n *\n * Licensed GPLv3 for open source use\n * or Flickity Commercial License for commercial use\n *\n * https://flickity.metafizzy.co\n * Copyright 2015-2021 Metafizzy\n */(function(r,i){typeof define==\"function\"&&define.amd?define(\"jquery-bridget/jquery-bridget\",[\"jquery\"],function(c){return i(r,c)}):typeof y==\"object\"&&y.exports?y.exports=i(r,require(\"jquery\")):r.jQueryBridget=i(r,r.jQuery)})(window,function(i,c){var l=Array.prototype.slice,s=i.console,n=typeof s>\"u\"?function(){}:function(e)\n--------------/* require statement is still here */-------------------------------------------------------------------------------------------------------------------------------^^^\n```\n\n```text\nrequire\n```\n\n```text\nvite\n```\n\n```text\nrequire\n```\n\n```text\nvite\n```\n\n```text\nvite\n```\n\n```text\nrollup\n```\n\n```text\nvite.config.js\n```\n\n```text\nrequire\n```\n\n```text\nrequire\n```\n\n```text\nwebpack\n```\n\n```text\nvite\n```\n\n```text\nnpm install flickity@2.3.0\n```\n\n```text\n<script src=\"https://unpkg.com/flickity@2/dist/flickity.pkgd.min.js\"></script>\n```\n\n```text\nvite\n```\n\n```text\nrequires\n```\n\n```text\n2.3.0\n```\n\n```text\n3.0.0\n```\n\n```text\n3.0.0\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":217,"estimatedTokens":1391}}266{"id":"stack-73899894","source":"stackoverflow","questionId":73899894,"title":"Uncaught ReferenceError: $ is not defined - Laravel 9, Vite","tags":["jquery","laravel","import","vite"],"text":"Title: Uncaught ReferenceError: $ is not defined - Laravel 9, Vite\nTags: jquery, laravel, import, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to import jQuery in my Laravel 9 project, which I installed with `npm i jquery`\n\nI'm getting `Uncaught ReferenceError: $ is not defined`\n\nin my `app.blade.php`\n\n```\n\ngetLocale()) }}\">\n\n \n \n\n \n \n\n {{ config('app.name', 'Laravel') }}\n\n \n \n\n \n @vite(['resources/sass/app.scss', 'resources/js/app.js'])\n\n```\n\nin my another view, which extends `app.blade.php`\n\n```\n\n $(function(){\n alert('jquery ok');\n })\n\n```\n\nin `resources/js/app.js`\n\nI tried all sorts of things\n\n```\nimport $ from 'jquery';\n```\n\n```\nimport $ from 'jquery';\n\nwindow.jQuery = $;\nwindow.$ = $;\n```\n\n```\nimport inject from '@rollup/plugin-inject';\n\nexport default {\n plugins: [\n // Add it first\n inject({\n $: 'jquery',\n }),\n // Other plugins...\n ],\n // The rest of your configuration...\n};\n```\n\n```\ntry {\n window.$ = window.jQuery = require('jquery');\n} catch (e) {}\n```\n\nNothing works. How can I fix this?\n\nnpm - 8.11.0\nnode - 16.16.0\nlaravel/framework - 9.32.0\nvite - 3.14\n\n========================================\n\nTop Answer:\nI followed this article to install & setup jQuery in Laravel 9:\n\nInstall jQuery\n\n```\nnpm install jquery --save-dev\n```\n\nImport jQuery through bootstrap\nThis needs to be just after lodash import\n\n```\nimport $ from 'jquery';\nwindow.$ = $;\n```\n\nIn the blade file\n\n```\n\n $('body').html('\n\n### Hello World!\n\n');\n\n```\n\nApp build:\n\n```\nnpm run build\n```\n\n========================================\n\nCode:\n```text\n<!doctype html>\n<html lang=\"{{ str_replace('_', '-', app()->getLocale()) }}\">\n<head>\n    <meta charset=\"utf-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\n    <!-- CSRF Token -->\n    <meta name=\"csrf-token\" content=\"{{ csrf_token() }}\">\n\n    <title>{{ config('app.name', 'Laravel') }}</title>\n\n    <!-- Fonts -->\n    <link rel=\"dns-prefetch\" href=\"//fonts.gstatic.com\">\n\n    <!-- Scripts -->\n    @vite(['resources/sass/app.scss', 'resources/js/app.js'])\n</head>\n```\n\n```text\n<script>\n  $(function(){\n      alert('jquery ok');\n  })\n</script>\n```\n\n```text\nimport $ from 'jquery';\n```\n\n```text\nimport $ from 'jquery';\n\nwindow.jQuery = $;\nwindow.$ = $;\n```\n\n```text\nimport inject from '@rollup/plugin-inject';\n\nexport default {\n    plugins: [\n        // Add it first\n        inject({\n            $: 'jquery',\n        }),\n        // Other plugins...\n    ],\n    // The rest of your configuration...\n};\n```\n\n```text\ntry {\n    window.$ = window.jQuery = require('jquery');\n} catch (e) {}\n```\n\n```text\nnpm i jquery\n```\n\n```text\nUncaught ReferenceError: $ is not defined\n```\n\n```text\napp.blade.php\n```\n\n```text\napp.blade.php\n```\n\n```text\nresources/js/app.js\n```\n\n```text\n<script type=\"module\"> //type=\"module\" is the important part\n    $(function () {\n        alert('jquery ok');\n    })\n</script>\n```\n\n```text\n<link href=\"./jquery-files/jquery-ui.css\" rel=\"stylesheet\">\n<script src=\"./jquery-files/external/jquery/jquery.js\"></script>\n<script src=\"./jquery-files/jquery-ui.min.js\"></script>\n```\n\n```text\n<script type=\"text/javascript\">\n\n    $().ready(function () {\n        //add all JQuery related code here!!\n        alert('jquery ok'); //this will show an alert when the page is loaded\n    });\n\n</script>\n```\n\n```text\nasync function main() {\n  const { default: jQuery } = await import('jquery')\n  window.jquery = window.jQuery = window.$ = jQuery;\n\n  // code that uses jQuery\n  console.log('jQuery v', $().jquery);\n}\n\nmain();\n```\n\n```text\nasync function main() {\n\n  if (document.querySelector('.useJquery')) {\n    const { default: jQuery } = await import('jquery')\n    window.jquery = window.jQuery = window.$ = jQuery;\n\n    // code that uses jQuery\n    console.log('jQuery v', $().jquery);\n  }\n}\n```\n\n```text\napp.js\n```\n\n```text\nclass=\"useJquery\"\n```\n\n```text\nuseJquery\n```\n\n```js\nimport _ from 'lodash';\n// Since I'm using jquery from admin-lte 🤷 \nimport $ from 'admin-lte/plugins/jquery/jquery';\nimport * as Popper from 'popper.js';\n// Since I'm using jquery from admin-lte 🤷 \nimport 'admin-lte/plugins/bootstrap/js/bootstrap'\nwindow._ = _;\nwindow.Popper = Popper.defaults;\nwindow.$ = window.jQuery = $;\n```\n\n```html\n<script type=\"module\">\n    $(function () {\n        console.log('Jquery loaded');    \n    });\n</script>\n```\n\n```text\nbootstrap.js\n```\n\n```text\nnpm install jquery --save-dev\n```\n\n```text\nimport $ from 'jquery';\nwindow.$ = $;\n```\n\n```text\n<script type=\"module\">\n    $('body').html('<h1>Hello World!</h1>');\n</script>\n```\n\n```text\nnpm run build\n```\n\n========================================\n\nComments:\n- See this; devdojo.com/thinkverse/how-to-use-jquery-with-laravel-and-vi&zwnj;&#8203;te\n- @Snapey thank you. but it did not help me solve the issue.\n- Does this answer your question? ReferenceError: $ is not defined, Jquery Import with vite","metadata":{"transformedAt":"2026-08-18T18:33:46.414Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":315,"estimatedTokens":1207}}267{"id":"stack-70824882","source":"stackoverflow","questionId":70824882,"title":"vitePluginString is not a function","tags":["svelte","vite"],"text":"Title: vitePluginString is not a function\nTags: svelte, vite\nSource: Stack Overflow\n\nQuestion:\nCreated a vite + svelte\n\n```\n$ npm init vite@latest\n✔ Project name: … app1\n✔ Select a framework: › svelte\n✔ Select a variant: › svelte-ts\n```\n\nwanted to include vite-plugin-string to use `glsl` file\n\ninstalled\n\n`npm install --save-dev vite-plugin-string`\n\nconfigured `vite.config.js` file as below\n\n```\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\nimport vitePluginString from 'vite-plugin-string'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [svelte(),vitePluginString()]\n})\n```\n\nAs soon as run `npm run dev`\n\nI get this error\n\n```\n> app1@0.0.0 dev\n> vite\n\nfailed to load config from ....../Six/trailRun/vite.config.js\nerror when starting dev server:\nTypeError: vitePluginString is not a function\n at file:///....../Six/trailRun/vite.config.js?t=1642958252054:8:22\n at ModuleJob.run (node:internal/modules/esm/module_job:195:25)\n at async Promise.all (index 0)\n at async ESMLoader.import (node:internal/modules/esm/loader:337:24)\n at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)\n at async loadConfigFromFile (/....../Six/trailRun/node_modules/vite/dist/node/chunks/dep-f5552faa.js:75089:31)\n at async resolveConfig (/....../Six/trailRun/node_modules/vite/dist/node/chunks/dep-f5552faa.js:74656:28)\n at async createServer (/....../Six/trailRun/node_modules/vite/dist/node/chunks/dep-f5552faa.js:60326:20)\n at async CAC. (/....../Six/trailRun/node_modules/vite/dist/node/cli.js:688:24)\n```\n\nWhat changes I need to make to correct this?\n\n========================================\n\nCode:\n```text\n$ npm init vite@latest\n✔ Project name: … app1\n✔ Select a framework: › svelte\n✔ Select a variant: › svelte-ts\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\nimport vitePluginString from 'vite-plugin-string'\n\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [svelte(),vitePluginString()]\n})\n```\n\n```text\n> app1@0.0.0 dev\n> vite\n\nfailed to load config from ....../Six/trailRun/vite.config.js\nerror when starting dev server:\nTypeError: vitePluginString is not a function\n    at file:///....../Six/trailRun/vite.config.js?t=1642958252054:8:22\n    at ModuleJob.run (node:internal/modules/esm/module_job:195:25)\n    at async Promise.all (index 0)\n    at async ESMLoader.import (node:internal/modules/esm/loader:337:24)\n    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)\n    at async loadConfigFromFile (/....../Six/trailRun/node_modules/vite/dist/node/chunks/dep-f5552faa.js:75089:31)\n    at async resolveConfig (/....../Six/trailRun/node_modules/vite/dist/node/chunks/dep-f5552faa.js:74656:28)\n    at async createServer (/....../Six/trailRun/node_modules/vite/dist/node/chunks/dep-f5552faa.js:60326:20)\n    at async CAC.<anonymous> (/....../Six/trailRun/node_modules/vite/dist/node/cli.js:688:24)\n```\n\n```text\nglsl\n```\n\n```text\nnpm install --save-dev vite-plugin-string\n```\n\n```text\nvite.config.js\n```\n\n```text\nnpm run dev\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\nimport vitePluginString from 'vite-plugin-string'\n\nexport default defineConfig({\n  plugins: [\n    svelte(),\n    vitePluginString.default(), 👈\n  ],\n})\n```\n\n```text\ndefault\n```\n\n========================================\n\nComments:\n- I have several Vite plugins where this seems to be a problem, yet they all document their usage as *not* requiring the `.default`. There seems to be a problem at a deeper level, since it seems obvious that this is not the intended usage.\n- Perhaps it is supposed to be imported like this `import { plugin as vitePluginString } from 'vite-plugin-string'`","metadata":{"transformedAt":"2026-08-18T18:33:46.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":136,"estimatedTokens":952}}268{"id":"stack-79502552","source":"stackoverflow","questionId":79502552,"title":"Unknown word \"use strict\" error by upgrading TailwindCSS from v3 to v4","tags":["reactjs","tailwind-css","vite"],"text":"Title: Unknown word \"use strict\" error by upgrading TailwindCSS from v3 to v4\nTags: reactjs, tailwind-css, vite\nSource: Stack Overflow\n\nQuestion:\nI was running Tailwind 3.4.17 in my Vite React app, but I wanted to upgrade it, so I ran 'npx @tailwindcss/upgrade' following this guide and expecting an easy migration.\n\nI now get this error from the Vite server when trying to run the app:\n\n```\n10:15:37 PM [vite] Internal server error: [postcss] postcss-import: /Users/oliver/Documents/code/news-planner/client/node_modules/tailwindcss/lib/index.js:1:1: Unknown word \"use strict\"\n Plugin: vite:css\n File: /Users/oliver/Documents/code/news-planner/client/node_modules/tailwindcss/lib/index.js:1:0\n 1 | \"use strict\";\n | ^\n 2 | module.exports = require(\"./plugin\");\n 3 | \n at Input.error (/Users/oliver/Documents/code/news-planner/client/node_modules/postcss/lib/input.js:113:16)\n at Parser.unknownWord (/Users/oliver/Documents/code/news-planner/client/node_modules/postcss/lib/parser.js:595:22)\n at Parser.other (/Users/oliver/Documents/code/news-planner/client/node_modules/postcss/lib/parser.js:437:12)\n at Parser.parse (/Users/oliver/Documents/code/news-planner/client/node_modules/postcss/lib/parser.js:472:16)\n at parse (/Users/oliver/Documents/code/news-planner/client/node_modules/postcss/lib/parse.js:11:12)\n at get root [as root] (/Users/oliver/Documents/code/news-planner/client/node_modules/postcss/lib/no-work-result.js:43:14)\n at Result.get [as root] (/Users/oliver/Documents/code/news-planner/client/node_modules/postcss/lib/no-work-result.js:77:21)\n at loadImportContent (file:///Users/oliver/Documents/code/news-planner/client/node_modules/vite/dist/node/chunks/dep-BGGf7Pd3.js:696:33)\n at async Promise.all (index 0)\n at async resolveImportId (file:///Users/oliver/Documents/code/news-planner/client/node_modules/vite/dist/node/chunks/dep-BGGf7Pd3.js:629:27)\n at async parseStyles$1 (file:///Users/oliver/Documents/code/news-planner/client/node_modules/vite/dist/node/chunks/dep-BGGf7Pd3.js:537:5)\n at async Object.Once (file:///Users/oliver/Documents/code/news-planner/client/node_modules/vite/dist/node/chunks/dep-BGGf7Pd3.js:794:22)\n at async LazyResult.runAsync (/Users/oliver/Documents/code/news-planner/client/node_modules/postcss/lib/lazy-result.js:293:11)\n at async compileCSS (file:///Users/oliver/Documents/code/news-planner/client/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:48587:21)\n at async TransformPluginContext.transform (file:///Users/oliver/Documents/code/news-planner/client/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:47842:11)\n at async EnvironmentPluginContainer.transform (file:///Users/oliver/Documents/code/news-planner/client/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:47219:18)\n at async loadAndTransform (file:///Users/oliver/Documents/code/news-planner/client/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:41030:27)\n at async viteTransformMiddleware (file:///Users/oliver/Documents/code/news-planner/client/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:42474:24)\n```\n\nI committed and pushed the project to GitHub right before running the upgrade. I would like to know how to get my app working again.\n\nI tried running git checkout to the latest commit, uninstalling the new version of Tailwind and reinstalling the old. I still get the same error.\n\nI'm running macOS 15.1\n\n========================================\n\nCode:\n```text\n10:15:37 PM [vite] Internal server error: [postcss] postcss-import: /Users/oliver/Documents/code/news-planner/client/node_modules/tailwindcss/lib/index.js:1:1: Unknown word \"use strict\"\n  Plugin: vite:css\n  File: /Users/oliver/Documents/code/news-planner/client/node_modules/tailwindcss/lib/index.js:1:0\n  1  |  \"use strict\";\n     |  ^\n  2  |  module.exports = require(\"./plugin\");\n  3  |  \n      at Input.error (/Users/oliver/Documents/code/news-planner/client/node_modules/postcss/lib/input.js:113:16)\n      at Parser.unknownWord (/Users/oliver/Documents/code/news-planner/client/node_modules/postcss/lib/parser.js:595:22)\n      at Parser.other (/Users/oliver/Documents/code/news-planner/client/node_modules/postcss/lib/parser.js:437:12)\n      at Parser.parse (/Users/oliver/Documents/code/news-planner/client/node_modules/postcss/lib/parser.js:472:16)\n      at parse (/Users/oliver/Documents/code/news-planner/client/node_modules/postcss/lib/parse.js:11:12)\n      at get root [as root] (/Users/oliver/Documents/code/news-planner/client/node_modules/postcss/lib/no-work-result.js:43:14)\n      at Result.get [as root] (/Users/oliver/Documents/code/news-planner/client/node_modules/postcss/lib/no-work-result.js:77:21)\n      at loadImportContent (file:///Users/oliver/Documents/code/news-planner/client/node_modules/vite/dist/node/chunks/dep-BGGf7Pd3.js:696:33)\n      at async Promise.all (index 0)\n      at async resolveImportId (file:///Users/oliver/Documents/code/news-planner/client/node_modules/vite/dist/node/chunks/dep-BGGf7Pd3.js:629:27)\n      at async parseStyles$1 (file:///Users/oliver/Documents/code/news-planner/client/node_modules/vite/dist/node/chunks/dep-BGGf7Pd3.js:537:5)\n      at async Object.Once (file:///Users/oliver/Documents/code/news-planner/client/node_modules/vite/dist/node/chunks/dep-BGGf7Pd3.js:794:22)\n      at async LazyResult.runAsync (/Users/oliver/Documents/code/news-planner/client/node_modules/postcss/lib/lazy-result.js:293:11)\n      at async compileCSS (file:///Users/oliver/Documents/code/news-planner/client/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:48587:21)\n      at async TransformPluginContext.transform (file:///Users/oliver/Documents/code/news-planner/client/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:47842:11)\n      at async EnvironmentPluginContainer.transform (file:///Users/oliver/Documents/code/news-planner/client/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:47219:18)\n      at async loadAndTransform (file:///Users/oliver/Documents/code/news-planner/client/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:41030:27)\n      at async viteTransformMiddleware (file:///Users/oliver/Documents/code/news-planner/client/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:42474:24)\n```\n\n```none\nnpm uninstall postcss-import autoprefixer\n```\n\n```none\nnpm install tailwindcss @tailwindcss/postcss postcss\n```\n\n```js\nexport default {\n  plugins: {\n    \"@tailwindcss/postcss\": {},\n  }\n}\n```\n\n```none\nnpm install tailwindcss @tailwindcss/vite\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport tailwindcss from '@tailwindcss/vite'\nexport default defineConfig({\n  plugins: [\n    tailwindcss(),\n  ],\n})\n```\n\n```text\n@tailwindcss/postcss\n```\n\n```text\n@tailwindcss/cli\n```\n\n```text\ntailwindcss\n```\n\n```text\npostcss\n```\n\n```text\n@tailwindcss/postcss\n```\n\n```text\n@tailwindcss/vite\n```\n\n```text\ninit\n```\n\n```text\ntailwind.config.js\n```\n\n```text\n@tailwind\n```\n\n```text\n@import \"tailwindcss\";\n```\n\n========================================\n\nComments:\n- You can actually reset your git head and make it point to the previous commit. if you would like to get the app working again. then push the local changes to the remote repository.\n- Starting with v4, the tailwind.config.js file is no longer needed, therefore the init process for generating it is no longer necessary either. As a result the CLI was separated into its own package, now named `@tailwindcss&#47;cli`, which only needs to be installed by those who want to use the Tailwind CLI Source","metadata":{"transformedAt":"2026-08-18T18:33:46.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":149,"estimatedTokens":1854}}269{"id":"stack-79136524","source":"stackoverflow","questionId":79136524,"title":"Vite - Azure pipelines | React .NET - There was an error exporting the HTTPS developer certificate to a file","tags":["reactjs",".net","azure-pipelines","vite"],"text":"Title: Vite - Azure pipelines | React .NET - There was an error exporting the HTTPS developer certificate to a file\nTags: reactjs, .net, azure-pipelines, vite\nSource: Stack Overflow\n\nQuestion:\n### When trying to push my react .net project my `npx vite build` fails\n\nThe error message in question:\n\n```\nThere was an error exporting the HTTPS developer certificate to a file.\n```\n\n```\nerror during build:\nError: Could not create certificate.\n at file:///D:/a/1/s/name.client/vite.config.ts.timestamp-1730192939030-060bc963903a.mjs:24:11\n at ModuleJob.run (node:internal/modules/esm/module_job:234:25)\n at async ModuleLoader.import (node:internal/modules/esm/loader:473:24)\n at async loadConfigFromBundledFile (file:///D:/a/1/s/name.client/node_modules/vite/dist/node/chunks/dep-CDnG8rE7.js:66634:15)\n at async loadConfigFromFile (file:///D:/a/1/s/name.client/node_modules/vite/dist/node/chunks/dep-CDnG8rE7.js:66475:24)\n at async resolveConfig (file:///D:/a/1/s/name.client/node_modules/vite/dist/node/chunks/dep-CDnG8rE7.js:66083:24)\n at async build (file:///D:/a/1/s/name.client/node_modules/vite/dist/node/chunks/dep-CDnG8rE7.js:65180:18)\n at async CAC. (file:///D:/a/1/s/name.client/node_modules/vite/dist/node/cli.js:828:5)\n```\n\n### Pipeline:\n\n```\npr:\n - Development\n - master\n\npool:\n vmImage: \"windows-latest\"\n\nvariables:\n buildConfiguration: \"Release\"\n buildPlatform: \"any cpu\"\n\nsteps:\n - checkout: self\n fetchDepth: 0\n - task: NuGetToolInstaller@1\n\n - task: UseDotNet@2\n inputs:\n packageType: 'sdk'\n version: '8.x' # Ensure this matches your project's .NET version\n installationPath: $(Agent.ToolsDirectory)/dotnet\n displayName: 'Install .NET SDK'\n\n - task: NuGetCommand@2\n displayName: \"NuGet restore\"\n inputs:\n restoreSolution: \"name.sln\"\n\n - task: SonarCloudPrepare@1\n inputs:\n SonarCloud: \"namename\"\n organization: \"name-test1\"\n scannerMode: \"MSBuild\"\n projectKey: \"namenamepass\"\n projectName: \"name\"\n\n - task: VSBuild@1\n displayName: 'Build solution **\\*.sln'\n inputs:\n solution: \"name.sln\"\n platform: \"$(BuildPlatform)\"\n configuration: \"$(BuildConfiguration)\"\n\n - task: VSTest@2\n displayName: \"VsTest - testAssemblies\"\n inputs:\n testAssemblyVer2: |\n **\\$(BuildConfiguration)\\*Test*.dll\n !**\\obj\\**\n codeCoverageEnabled: true\n platform: \"$(BuildPlatform)\"\n configuration: \"$(BuildConfiguration)\"\n\n - task: SonarCloudAnalyze@1\n displayName: \"Run SonarCloud analysis\"\n\n - task: SonarCloudPublish@1\n displayName: \"Publish results on build summary\"\n```\n\nvite config:\n\n```\nimport { fileURLToPath, URL } from \"node:url\";\n\nimport { defineConfig, UserConfig } from \"vite\";\nimport plugin from \"@vitejs/plugin-react\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport child_process from \"child_process\";\nimport mkcert from \"vite-plugin-mkcert\";\nconst isCI = process.env.CI === 'true' || process.env.AZURE_PIPELINE === 'true';\nconst baseFolder =\n process.env.APPDATA !== undefined && process.env.APPDATA !== \"\" ? `${process.env.APPDATA}/ASP.NET/https` : `${process.env.HOME}/.aspnet/https`;\n\n//@ts-ignore\nconst certificateArg = process.argv.map((arg) => arg.match(/--name=(?.+)/i)).filter(Boolean)[0];\nconst certificateName = certificateArg ? certificateArg.groups.value : \"name.client\";\n\nif (!certificateName) {\n console.error(\"Invalid certificate name. Run this script in the context of an npm/yarn script or pass --name=> explicitly.\");\n process.exit(-1);\n}\n\nconst certFilePath = path.join(baseFolder, `${certificateName}.pem`);\nconst keyFilePath = path.join(baseFolder, `${certificateName}.key`);\n\nif (!fs.existsSync(certFilePath) || !fs.existsSync(keyFilePath)) {\n if (\n 0 !==\n child_process.spawnSync(\"dotnet\", [\"dev-certs\", \"https\", \"--export-path\", certFilePath, \"--format\", \"Pem\", \"--no-password\"], {\n stdio: \"inherit\",\n }).status\n ) {\n throw new Error(\"Could not create certificate.\");\n }\n}\n\nconst configLocal : UserConfig = {\n plugins: [plugin(), mkcert()],\n resolve: {\n alias: {\n \"@\": fileURLToPath(new URL(\"./src\", import.meta.url)),\n },\n },\n server: {\n proxy: {\n \"^/weatherforecast\": {\n target: \"https://localhost:7293/\",\n secure: false,\n },\n },\n port: 5173,\n https: {\n key: fs.readFileSync(keyFilePath),\n cert: fs.readFileSync(certFilePath),\n },\n },\n}\nconst configServer : UserConfig = {\n plugins: [plugin(), mkcert()],\n resolve: {\n alias: {\n \"@\": fileURLToPath(new URL(\"./src\", import.meta.url)),\n },\n },\n server: {\n proxy: {\n \"^/weatherforecast\": {\n target: \"https://localhost:7293/\",\n secure: false,\n },\n },\n port: 5173,\n },\n}\n\nexport default defineConfig(isCI ? configServer : configLocal);\n```\n\n========================================\n\nTop Answer:\nYou can add the following line to your vite.config.ts file to resolve this issue-\n\n```\nfs.mkdirSync(baseFolder, { recursive: true });\n```\n\nAdd this after the following statement-\n\n```\nconst baseFolder =\nenv.APPDATA !== undefined && env.APPDATA !== ''\n ? `${env.APPDATA}/ASP.NET/https`\n : `${env.HOME}/.aspnet/https`;\n```\n\n========================================\n\nCode:\n```text\nThere was an error exporting the HTTPS developer certificate to a file.\n```\n\n```js\nerror during build:\nError: Could not create certificate.\n    at file:///D:/a/1/s/name.client/vite.config.ts.timestamp-1730192939030-060bc963903a.mjs:24:11\n    at ModuleJob.run (node:internal/modules/esm/module_job:234:25)\n    at async ModuleLoader.import (node:internal/modules/esm/loader:473:24)\n    at async loadConfigFromBundledFile (file:///D:/a/1/s/name.client/node_modules/vite/dist/node/chunks/dep-CDnG8rE7.js:66634:15)\n    at async loadConfigFromFile (file:///D:/a/1/s/name.client/node_modules/vite/dist/node/chunks/dep-CDnG8rE7.js:66475:24)\n    at async resolveConfig (file:///D:/a/1/s/name.client/node_modules/vite/dist/node/chunks/dep-CDnG8rE7.js:66083:24)\n    at async build (file:///D:/a/1/s/name.client/node_modules/vite/dist/node/chunks/dep-CDnG8rE7.js:65180:18)\n    at async CAC.<anonymous> (file:///D:/a/1/s/name.client/node_modules/vite/dist/node/cli.js:828:5)\n```\n\n```yaml\npr:\n  - Development\n  - master\n\npool:\n  vmImage: \"windows-latest\"\n\nvariables:\n  buildConfiguration: \"Release\"\n  buildPlatform: \"any cpu\"\n\nsteps:\n  - checkout: self\n    fetchDepth: 0\n  - task: NuGetToolInstaller@1\n\n  - task: UseDotNet@2\n    inputs:\n      packageType: 'sdk'\n      version: '8.x' # Ensure this matches your project's .NET version\n      installationPath: $(Agent.ToolsDirectory)/dotnet\n    displayName: 'Install .NET SDK'\n\n  - task: NuGetCommand@2\n    displayName: \"NuGet restore\"\n    inputs:\n      restoreSolution: \"name.sln\"\n\n  - task: SonarCloudPrepare@1\n    inputs:\n      SonarCloud: \"namename\"\n      organization: \"name-test1\"\n      scannerMode: \"MSBuild\"\n      projectKey: \"namenamepass\"\n      projectName: \"name\"\n\n\n  - task: VSBuild@1\n    displayName: 'Build solution **\\*.sln'\n    inputs:\n      solution: \"name.sln\"\n      platform: \"$(BuildPlatform)\"\n      configuration: \"$(BuildConfiguration)\"\n\n  - task: VSTest@2\n    displayName: \"VsTest - testAssemblies\"\n    inputs:\n      testAssemblyVer2: |\n        **\\$(BuildConfiguration)\\*Test*.dll\n        !**\\obj\\**\n      codeCoverageEnabled: true\n      platform: \"$(BuildPlatform)\"\n      configuration: \"$(BuildConfiguration)\"\n\n  - task: SonarCloudAnalyze@1\n    displayName: \"Run SonarCloud analysis\"\n\n  - task: SonarCloudPublish@1\n    displayName: \"Publish results on build summary\"\n```\n\n```none\nimport { fileURLToPath, URL } from \"node:url\";\n\nimport { defineConfig, UserConfig } from \"vite\";\nimport plugin from \"@vitejs/plugin-react\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport child_process from \"child_process\";\nimport mkcert from \"vite-plugin-mkcert\";\nconst isCI = process.env.CI === 'true' || process.env.AZURE_PIPELINE === 'true';\nconst baseFolder =\n    process.env.APPDATA !== undefined && process.env.APPDATA !== \"\" ? `${process.env.APPDATA}/ASP.NET/https` : `${process.env.HOME}/.aspnet/https`;\n\n//@ts-ignore\nconst certificateArg = process.argv.map((arg) => arg.match(/--name=(?<value>.+)/i)).filter(Boolean)[0];\nconst certificateName = certificateArg ? certificateArg.groups.value : \"name.client\";\n\nif (!certificateName) {\n    console.error(\"Invalid certificate name. Run this script in the context of an npm/yarn script or pass --name=<<app>> explicitly.\");\n    process.exit(-1);\n}\n\nconst certFilePath = path.join(baseFolder, `${certificateName}.pem`);\nconst keyFilePath = path.join(baseFolder, `${certificateName}.key`);\n\nif (!fs.existsSync(certFilePath) || !fs.existsSync(keyFilePath)) {\n    if (\n        0 !==\n        child_process.spawnSync(\"dotnet\", [\"dev-certs\", \"https\", \"--export-path\", certFilePath, \"--format\", \"Pem\", \"--no-password\"], {\n            stdio: \"inherit\",\n        }).status\n    ) {\n        throw new Error(\"Could not create certificate.\");\n    }\n}\n\nconst configLocal : UserConfig  = {\n    plugins: [plugin(), mkcert()],\n    resolve: {\n        alias: {\n            \"@\": fileURLToPath(new URL(\"./src\", import.meta.url)),\n        },\n    },\n    server: {\n        proxy: {\n            \"^/weatherforecast\": {\n                target: \"https://localhost:7293/\",\n                secure: false,\n            },\n        },\n        port: 5173,\n        https: {\n            key: fs.readFileSync(keyFilePath),\n            cert: fs.readFileSync(certFilePath),\n        },\n    },\n}\nconst configServer : UserConfig  = {\n    plugins: [plugin(), mkcert()],\n    resolve: {\n        alias: {\n            \"@\": fileURLToPath(new URL(\"./src\", import.meta.url)),\n        },\n    },\n    server: {\n        proxy: {\n            \"^/weatherforecast\": {\n                target: \"https://localhost:7293/\",\n                secure: false,\n            },\n        },\n        port: 5173,\n    },\n}\n\nexport default defineConfig(isCI ? configServer : configLocal);\n```\n\n```text\nnpx vite build\n```\n\n```text\nsteps:\n  - checkout: self\n    fetchDepth: 0\n  - task: NuGetToolInstaller@1\n\n  - task: UseDotNet@2\n    inputs:\n      packageType: 'sdk'\n      version: '8.0.402' # Ensure this matches your project's .NET version\n      installationPath: $(Agent.ToolsDirectory)/dotnet\n    displayName: 'Install .NET SDK'\n```\n\n```text\n.aspnet/https\n```\n\n```text\nfs.mkdirSync(baseFolder, { recursive: true });\n```\n\n```text\nconst baseFolder =\nenv.APPDATA !== undefined && env.APPDATA !== ''\n    ? `${env.APPDATA}/ASP.NET/https`\n    : `${env.HOME}/.aspnet/https`;\n```\n\n========================================\n\nComments:\n- Great, thank you!\n- @DanielPrzybylski Thanks for your reminding. I have updated my answer.\n- Perhaps wrap the statement in a condition so this isn't executed unless absolutely necessary? `if (!fs.existsSync(baseFolder)) { ... }`","metadata":{"transformedAt":"2026-08-18T18:33:46.414Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":386,"estimatedTokens":2631}}270{"id":"stack-72834388","source":"stackoverflow","questionId":72834388,"title":"Vite with create-react-app is returning 404 error","tags":["reactjs","create-react-app","vite"],"text":"Title: Vite with create-react-app is returning 404 error\nTags: reactjs, create-react-app, vite\nSource: Stack Overflow\n\nQuestion:\nI decided to configure my react application created by create-react-app to start using vite. After following some documentation, I configured the required files. When I run `vite` in the root of my application, it runs but unfortunately I cannot access the files due to 404 errors. The strange is that for my coworkers it runs. When I change to `react-scripts` it runs successfully. Below is some configuration of my application:\n\n`vite.config.ts`\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport path from 'path'\n\nexport default defineConfig({\n plugins: [react()],\n build: {\n outDir: 'build',\n },\n resolve: {\n alias: {\n '@': path.resolve(__dirname, 'src'),\n },\n },\n})\n```\n\n`tsconfig.json`\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"ESNext\",\n \"types\": [\"vite/client\"],\n \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n \"allowJs\": true,\n \"skipLibCheck\": true,\n \"esModuleInterop\": true,\n \"allowSyntheticDefaultImports\": true,\n \"strict\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"noFallthroughCasesInSwitch\": true,\n \"module\": \"esnext\",\n \"moduleResolution\": \"node\",\n \"resolveJsonModule\": true,\n \"isolatedModules\": true,\n \"noEmit\": true,\n \"jsx\": \"react-jsx\",\n \"baseUrl\": \".\",\n \"paths\": {\n \"@/*\": [\"./src/*\"]\n }\n },\n \"include\": [\"src\"]\n}\n```\n\n`package.json`\n\n```\n{\n \"name\": \"my-app\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"scripts\": {\n \"start\": \"vite\",\n \"start:debug\": \"vite --debug\",\n \"build:development\": \"tsc && vite build\",\n \"build:staging\": \"tsc && vite build --mode staging\",\n \"build:production\": \"tsc && vite build --mode production\",\n \"preview\": \"vite preview\",\n \"eslint\": \"eslint --ext .tsx,.ts src/\",\n \"eslint:fix\": \"eslint --fix --ext .tsx,.ts src/\"\n },\n \"dependencies\": {\n \"@azure/msal-browser\": \"^2.24.0\",\n \"@azure/msal-react\": \"^1.4.0\",\n \"@fortawesome/fontawesome-svg-core\": \"^6.1.1\",\n \"@fortawesome/free-regular-svg-icons\": \"^6.1.1\",\n \"@fortawesome/free-solid-svg-icons\": \"^6.1.1\",\n \"@fortawesome/react-fontawesome\": \"^0.1.18\",\n \"react-data-table-component\": \"^7.5.2\",\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\",\n \"react-router\": \"^6.3.0\",\n \"react-router-dom\": \"^6.3.0\",\n \"react-scripts\": \"5.0.1\",\n \"react-sliding-side-panel\": \"^2.0.3\",\n \"web-vitals\": \"^2.1.4\"\n },\n \"devDependencies\": {\n \"@types/cors\": \"^2.8.12\",\n \"@types/node\": \"^16.11.41\",\n \"@types/react\": \"^18.0.9\",\n \"@types/react-dom\": \"^18.0.4\",\n \"@typescript-eslint/eslint-plugin\": \"^5.30.0\",\n \"@typescript-eslint/parser\": \"^5.30.0\",\n \"@vitejs/plugin-react\": \"^1.3.2\",\n \"@vitejs/plugin-react-refresh\": \"^1.3.6\",\n \"autoprefixer\": \"^10.4.7\",\n \"eslint\": \"^8.18.0\",\n \"eslint-config-prettier\": \"^8.5.0\",\n \"eslint-plugin-react\": \"^7.30.1\",\n \"eslint-plugin-react-hooks\": \"^4.6.0\",\n \"postcss\": \"^8.4.14\",\n \"tailwindcss\": \"^3.1.0\",\n \"typescript\": \"^4.7.4\",\n \"vite\": \"^2.9.13\",\n \"vite-plugin-svgr\": \"^2.2.0\"\n },\n \"engines\": {\n \"node\": \">=16.0.0\",\n \"npm\": \">=8.0.0\"\n },\n \"browserslist\": {\n \"production\": [\n \">0.2%\",\n \"not dead\",\n \"not op_mini all\"\n ],\n \"development\": [\n \"last 1 chrome version\",\n \"last 1 firefox version\",\n \"last 1 safari version\"\n ]\n }\n}\n```\n\nAfter execute `npm start`, it returns this content in the command line:\n\n```\nvite v2.9.13 dev server running at:\n\n> Local: http://localhost:3000/\n> Network: use `--host` to expose\n\nready in 308ms.\n```\n\nAfter trying to access the page at that address, I get 404, and nothing is printed into my console.\n\n```\nThis localhost page can’t be foundNo webpage was found for the web address: \nhttp://localhost:3000/\n\nHTTP ERROR 404\n```\n\nI already tryind to use the vite package to create a react application using the CLI, and it worked. I compared the configuration of the project that worked, and this, but I could't find any difference that could change the result.\n\nIf I try to access some `/public` resources, I can. So, the vite is hosting this folder, but the `index.html` from the root is not being building for some reason I guess.\n\nThe structure of my project is avaiable in this image\n\nDo you have some suggestion for what is happaning to my project?\nThanks!\n\n**EDIT 1**\n\nAfter some tests I discovered that when I run `vite build` and host the builded folder with `serve`, it works. The folder structure is generated correctly and the assets too. I think it is something with the live-reload or the `vite` command itself.\n\n**EDIT 2**\n\nUsing `vite preview` in the build folder worked as well.\n\n========================================\n\nCode:\n```js\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport path from 'path'\n\nexport default defineConfig({\n  plugins: [react()],\n  build: {\n    outDir: 'build',\n  },\n  resolve: {\n    alias: {\n      '@': path.resolve(__dirname, 'src'),\n    },\n  },\n})\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"types\": [\"vite/client\"],\n    \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"esModuleInterop\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\",\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@/*\": [\"./src/*\"]\n    }\n  },\n  \"include\": [\"src\"]\n}\n```\n\n```json\n{\n  \"name\": \"my-app\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"scripts\": {\n    \"start\": \"vite\",\n    \"start:debug\": \"vite --debug\",\n    \"build:development\": \"tsc && vite build\",\n    \"build:staging\": \"tsc && vite build --mode staging\",\n    \"build:production\": \"tsc && vite build --mode production\",\n    \"preview\": \"vite preview\",\n    \"eslint\": \"eslint --ext .tsx,.ts src/\",\n    \"eslint:fix\": \"eslint --fix --ext .tsx,.ts src/\"\n  },\n  \"dependencies\": {\n    \"@azure/msal-browser\": \"^2.24.0\",\n    \"@azure/msal-react\": \"^1.4.0\",\n    \"@fortawesome/fontawesome-svg-core\": \"^6.1.1\",\n    \"@fortawesome/free-regular-svg-icons\": \"^6.1.1\",\n    \"@fortawesome/free-solid-svg-icons\": \"^6.1.1\",\n    \"@fortawesome/react-fontawesome\": \"^0.1.18\",\n    \"react-data-table-component\": \"^7.5.2\",\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\",\n    \"react-router\": \"^6.3.0\",\n    \"react-router-dom\": \"^6.3.0\",\n    \"react-scripts\": \"5.0.1\",\n    \"react-sliding-side-panel\": \"^2.0.3\",\n    \"web-vitals\": \"^2.1.4\"\n  },\n  \"devDependencies\": {\n    \"@types/cors\": \"^2.8.12\",\n    \"@types/node\": \"^16.11.41\",\n    \"@types/react\": \"^18.0.9\",\n    \"@types/react-dom\": \"^18.0.4\",\n    \"@typescript-eslint/eslint-plugin\": \"^5.30.0\",\n    \"@typescript-eslint/parser\": \"^5.30.0\",\n    \"@vitejs/plugin-react\": \"^1.3.2\",\n    \"@vitejs/plugin-react-refresh\": \"^1.3.6\",\n    \"autoprefixer\": \"^10.4.7\",\n    \"eslint\": \"^8.18.0\",\n    \"eslint-config-prettier\": \"^8.5.0\",\n    \"eslint-plugin-react\": \"^7.30.1\",\n    \"eslint-plugin-react-hooks\": \"^4.6.0\",\n    \"postcss\": \"^8.4.14\",\n    \"tailwindcss\": \"^3.1.0\",\n    \"typescript\": \"^4.7.4\",\n    \"vite\": \"^2.9.13\",\n    \"vite-plugin-svgr\": \"^2.2.0\"\n  },\n  \"engines\": {\n    \"node\": \">=16.0.0\",\n    \"npm\": \">=8.0.0\"\n  },\n  \"browserslist\": {\n    \"production\": [\n      \">0.2%\",\n      \"not dead\",\n      \"not op_mini all\"\n    ],\n    \"development\": [\n      \"last 1 chrome version\",\n      \"last 1 firefox version\",\n      \"last 1 safari version\"\n    ]\n  }\n}\n```\n\n```bash\nvite v2.9.13 dev server running at:\n\n> Local: http://localhost:3000/\n> Network: use `--host` to expose\n\nready in 308ms.\n```\n\n```text\nThis localhost page can’t be foundNo webpage was found for the web address: \nhttp://localhost:3000/\n\nHTTP ERROR 404\n```\n\n```text\nvite\n```\n\n```text\nreact-scripts\n```\n\n```text\nvite.config.ts\n```\n\n```text\ntsconfig.json\n```\n\n```text\npackage.json\n```\n\n```text\nnpm start\n```\n\n```text\n/public\n```\n\n```text\nindex.html\n```\n\n```text\nvite build\n```\n\n```text\nserve\n```\n\n```text\nvite\n```\n\n```text\nvite preview\n```\n\n```text\n%20\n```\n\n```text\nvite\n```\n\n```text\n%20\n```\n\n```text\nvite\n```\n\n```text\nProject%20\n```\n\n```text\nProject\n```\n\n========================================\n\nComments:\n- More info from docs: vite build and preview process\n- Thanks for this. My project is in a folder with `%20` in its name. The moment I removed that `npm run dev` works as expected.","metadata":{"transformedAt":"2026-08-18T18:33:46.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":378,"estimatedTokens":2070}}271{"id":"stack-72316252","source":"stackoverflow","questionId":72316252,"title":"Sass global variables and mixins not working","tags":["vue.js","sass","vite"],"text":"Title: Sass global variables and mixins not working\nTags: vue.js, sass, vite\nSource: Stack Overflow\n\nQuestion:\nI've set up a project using Vue 3.2.33 and Vite 2.9.5\n\nWhen I try to access any global variable or mixin from within any vue component, I get an undefined error. This problem doesn't occur in scss files.\n\nThe import itself seems working correctly because any css rules in it are working.\n\nvite.config.ts:\n\n```\nimport { fileURLToPath, URL } from 'url';\n\nimport { defineConfig } from 'vite';\nimport vue from '@vitejs/plugin-vue';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [vue()],\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url)),\n },\n },\n css: {\n preprocessorOptions: {\n scss: {\n additionalData: '@use \"@/styles/variables\";',\n },\n },\n },\n});\n```\n\nsrc/styles/_variables.scss:\n\n```\n// breakpoints\n$breakpoints: (\n \"sm\": 576px,\n \"md\": 768px,\n \"lg\": 992px,\n \"xl\": 1200px,\n \"xxl\": 1400px,\n);\n\n@mixin test {\n border: 3px solid red;\n}\n```\n\nExample use:\n\n```\n\n@use 'sass:map';\n\n.container {\n max-width: 100%;\n width: 100%;\n margin: 0 auto;\n @include test; // \n```\n\n========================================\n\nTop Answer:\nuse\n\n```\n@import\n```\n\nin your vite config instead of\n\n```\n@use\n```\n\n`vite.config.ts`:\n\n```\nexport default defineConfig({\n plugins: [vue()],\n css: {\n preprocessorOptions: {\n scss: {\n additionalData: '@import \"./src/styles/variables.scss\";',\n },\n },\n },\n});\n```\n\nkeep in mind that you cannot import the same file `variables.scss` again in your `main.ts` file otherwise, you will get this error\n\n```\n[sass] This file is already being loaded.\n```\n\nby the way, you can also import the `scss` file in every single component manually as you mentioned but that would be really tedious so using a global import in `preprocessorOptions` in `vite.config.ts` is a much better option for files used globally like a `variables.scss` file.\n\n========================================\n\nCode:\n```js\nimport { fileURLToPath, URL } from 'url';\n\nimport { defineConfig } from 'vite';\nimport vue from '@vitejs/plugin-vue';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n    plugins: [vue()],\n    resolve: {\n        alias: {\n            '@': fileURLToPath(new URL('./src', import.meta.url)),\n        },\n    },\n    css: {\n        preprocessorOptions: {\n            scss: {\n                additionalData: '@use \"@/styles/variables\";',\n            },\n        },\n    },\n});\n```\n\n```scss\n// breakpoints\n$breakpoints: (\n    \"sm\": 576px,\n    \"md\": 768px,\n    \"lg\": 992px,\n    \"xl\": 1200px,\n    \"xxl\": 1400px,\n);\n\n@mixin test {\n    border: 3px solid red;\n}\n```\n\n```scss\n<style scoped lang=\"scss\">\n@use 'sass:map';\n\n.container {\n    max-width: 100%;\n    width: 100%;\n    margin: 0 auto;\n    @include test; // <- undefined\n\n    &--fluid {\n        max-width: 100%;\n        width: 100%;\n    }\n}\n\n$widths: (\n    'sm': 540px,\n    'md': 720px,\n    'lg': 960px,\n    'xl': 1140px,\n    'xxl': 1320px,\n);\n\n@each $breakpoint, $width in $widths {\n    @media (min-width: map.get($breakpoints, $breakpoint)) { // <- $breakpoints undefined\n        .container {\n            max-width: $width;\n        }\n    }\n}\n</style>\n```\n\n```text\n@use\n```\n\n```text\n@import\n```\n\n```text\n@use\n```\n\n```text\nadditionalData\n```\n\n```css\n@import\n```\n\n```css\n@use\n```\n\n```js\nexport default defineConfig({\n    plugins: [vue()],\n    css: {\n        preprocessorOptions: {\n            scss: {\n                additionalData: '@import \"./src/styles/variables.scss\";',\n            },\n        },\n    },\n});\n```\n\n```scss\n[sass] This file is already being loaded.\n```\n\n```text\nvite.config.ts\n```\n\n```text\nvariables.scss\n```\n\n```text\nmain.ts\n```\n\n```text\nscss\n```\n\n```text\npreprocessorOptions\n```\n\n```text\nvite.config.ts\n```\n\n```text\nvariables.scss\n```\n\n```text\nscss: {\n    additionalData: '@use \"@/styles/variables\" as *;',\n  },\n```\n\n```text\nas *\n```\n\n```text\nadditionalData\n```\n\n```text\n@import\n```\n\n```text\n@use\n```\n\n```text\n@use\n```\n\n```text\n@import\n```\n\n========================================\n\nComments:\n- it's unknown at which point the problem occurs. Did you try to add use @/styles/variables explicitly?\n- Yes, I've tried\n- Your file is named `_variables.scss` (and not sure where that's even located), but your import is `@&#47;styles&#47;variables`. How is that reconciled?\n- The problem is not with the path, since basic css rules are properly imported. The problem is that the sass-specific code like variables or mixins is not","metadata":{"transformedAt":"2026-08-18T18:33:46.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":287,"estimatedTokens":1113}}272{"id":"stack-79494762","source":"stackoverflow","questionId":79494762,"title":"Is there a way to bypass this error and make pnpm dlx work with TailwindCSS?","tags":["reactjs","typescript","tailwind-css","vite","tailwind-css-4"],"text":"Title: Is there a way to bypass this error and make pnpm dlx work with TailwindCSS?\nTags: reactjs, typescript, tailwind-css, vite, tailwind-css-4\nSource: Stack Overflow\n\nQuestion:\nMy questions are: Is there a way to bypass this error and make `pnpm dlx` work with TailwindCSS? If not, how can I manually locate the necessary binaries to run TailwindCSS?\n\nI'm using pnpm v10.5.2 and TailwindCSS v4.0 Any help would be appreciated!\n\nI'm trying to run TailwindCSS using `pnpm dlx`, but I keep getting this error:\n\nERR_PNPM_DLX_NO_BIN  No binaries found in tailwindcss.\n\nThe command I used:\n\n```\npnpm dlx tailwindcss -i ./src/input.css -o ./dist/output.css --watch\n```\n\nFrom my understanding, `pnpm dlx` runs binaries from the package, but it seems like TailwindCSS doesn't expose any.\n\n========================================\n\nTop Answer:\nThe CLI interface for Tailwind CSS is in a different package, `@tailwindcss/cli`. Thus, your command should look like:\n\n```\npnpm dlx @tailwindcss/cli -i ./src/input.css -o ./dist/output.css --watch\n```\n\n========================================\n\nCode:\n```none\npnpm dlx tailwindcss -i ./src/input.css -o ./dist/output.css --watch\n```\n\n```text\npnpm dlx\n```\n\n```text\npnpm dlx\n```\n\n```text\npnpm dlx\n```\n\n```text\npnpm dlx tailwindcss@3 init\n```\n\n```bash\npnpm dlx @tailwindcss/cli -i ./src/input.css -o ./dist/output.css --watch\n```\n\n```text\n@tailwindcss/cli\n```\n\n========================================\n\nComments:\n- Related: Problem installing TailwindCSS with Vite, after \"npx tailwindcss init -p\" command","metadata":{"transformedAt":"2026-08-18T18:33:46.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":65,"estimatedTokens":385}}273{"id":"stack-73936436","source":"stackoverflow","questionId":73936436,"title":"Laravel Breeze Vite Dev-Server Error: \"cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file\"","tags":["laravel","build","vite","laravel-breeze"],"text":"Title: Laravel Breeze Vite Dev-Server Error: \"cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file\"\nTags: laravel, build, vite, laravel-breeze\nSource: Stack Overflow\n\nQuestion:\nI set up a fresh Laravel Breeze Project with Vite. When I run:\n\n```\nnpm run dev\n```\n\nI get this Error:\n\n```\nfailed to load config from PATH/vite.config.js\nerror when starting dev server:\nError: cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: PATH/dist/client/client.mjs\n at testCaseInsensitiveFS (PATH/node_modules/vite/dist/node-cjs/publicUtils.cjs:3420:15)\n at Object. (PATH/node_modules/vite/dist/node-cjs/publicUtils.cjs:3425:1)\n at Module._compile (node:internal/modules/cjs/loader:1126:14)\n at Module._extensions..js (node:internal/modules/cjs/loader:1180:10)\n at Object._require.extensions. [as .js] (file:///PATH/node_modules/vite/dist/node/chunks/dep-6b3a5aff.js:63517:17)\n at Module.load (node:internal/modules/cjs/loader:1004:32)\n at Function.Module._load (node:internal/modules/cjs/loader:839:12)\n at Module.require (node:internal/modules/cjs/loader:1028:19)\n at require (node:internal/modules/cjs/helpers:102:18)\n at Object. (PATH/node_modules/vite/index.cjs:7:31)\n```\n\nI can't find any Information about this error! A few Weeks ago I had no Problems with this.\n\nHere is my Vite Config File:\n\n```\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\n\nexport default defineConfig({\n plugins: [\n laravel({\n input: [\n 'resources/css/app.css',\n 'resources/js/app.js',\n ],\n refresh: true,\n }),\n ],\n});\n```\n\nThanks in advance\n\n========================================\n\nCode:\n```text\nnpm run dev\n```\n\n```text\nfailed to load config from PATH/vite.config.js\nerror when starting dev server:\nError: cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: PATH/dist/client/client.mjs\n    at testCaseInsensitiveFS (PATH/node_modules/vite/dist/node-cjs/publicUtils.cjs:3420:15)\n    at Object.<anonymous> (PATH/node_modules/vite/dist/node-cjs/publicUtils.cjs:3425:1)\n    at Module._compile (node:internal/modules/cjs/loader:1126:14)\n    at Module._extensions..js (node:internal/modules/cjs/loader:1180:10)\n    at Object._require.extensions.<computed> [as .js] (file:///PATH/node_modules/vite/dist/node/chunks/dep-6b3a5aff.js:63517:17)\n    at Module.load (node:internal/modules/cjs/loader:1004:32)\n    at Function.Module._load (node:internal/modules/cjs/loader:839:12)\n    at Module.require (node:internal/modules/cjs/loader:1028:19)\n    at require (node:internal/modules/cjs/helpers:102:18)\n    at Object.<anonymous> (PATH/node_modules/vite/index.cjs:7:31)\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\n\nexport default defineConfig({\n    plugins: [\n        laravel({\n            input: [\n                'resources/css/app.css',\n                'resources/js/app.js',\n            ],\n            refresh: true,\n        }),\n    ],\n});\n```\n\n```text\n#\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":95,"estimatedTokens":747}}274{"id":"stack-73268373","source":"stackoverflow","questionId":73268373,"title":"Vite build failed on cloudflare pages","tags":["javascript","reactjs","cloudflare","vite","web-frontend"],"text":"Title: Vite build failed on cloudflare pages\nTags: javascript, reactjs, cloudflare, vite, web-frontend\nSource: Stack Overflow\n\nQuestion:\nI'm trying to deploy my vite+react application on cloudflare pages, and it shows\n\n```\n(node:1365) ExperimentalWarning: The ESM module loader is experimental.\nfile:///opt/buildhome/repo/node_modules/vite/bin/vite.js:7\n await import('source-map-support').then((r) => r.default.install())\n ^^^^^\nSyntaxError: Unexpected reserved word\n at Loader.moduleStrategy (internal/modules/esm/translators.js:81:18)\n at async link (internal/modules/esm/module_job.js:37:21)\n```\n\n========================================\n\nCode:\n```text\n(node:1365) ExperimentalWarning: The ESM module loader is experimental.\nfile:///opt/buildhome/repo/node_modules/vite/bin/vite.js:7\n    await import('source-map-support').then((r) => r.default.install())\n    ^^^^^\nSyntaxError: Unexpected reserved word\n    at Loader.moduleStrategy (internal/modules/esm/translators.js:81:18)\n    at async link (internal/modules/esm/module_job.js:37:21)\n```\n\n========================================\n\nComments:\n- CF page's default node version is 12.x however using the ENVAR as mentionned you can use 17.x","metadata":{"transformedAt":"2026-08-18T18:33:46.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":34,"estimatedTokens":299}}275{"id":"stack-72903984","source":"stackoverflow","questionId":72903984,"title":"How to get current route via useRoute outside of router-view component","tags":["vuejs3","vue-router","vite"],"text":"Title: How to get current route via useRoute outside of router-view component\nTags: vuejs3, vue-router, vite\nSource: Stack Overflow\n\nQuestion:\nHow can I get the current route using `useRoute` for a component that's *outside of* the ``? Is this possible?\n\n**Breadcrumbs.vue**\n\n```\n\nimport {useRoute} from 'vue-router'\n\nconst route = useRoute()\nconsole.log(route.name) // undefined\n\n```\n\n**App.vue**\n\n```\n\n \n \n\n```\n\nThe alternative is that I have to put `` at the top of every single view component, and I was hoping to avoid that and instead just include it once in my `App.vue`\n\n========================================\n\nTop Answer:\nIn your main file, try to mount app like this\n\n```\nrouter.isReady().then(() => {\n app.mount('#app');\n});\n```\n\nthen useRoute() should be ready in your component\n\n========================================\n\nCode:\n```text\n<script setup>\nimport {useRoute} from 'vue-router'\n\nconst route = useRoute()\nconsole.log(route.name) // undefined\n</script>\n```\n\n```text\n<template>\n  <Breadcrumbs />\n  <router-view />\n</template>\n```\n\n```text\nuseRoute\n```\n\n```text\n<router-view />\n```\n\n```text\n<Breadcrumbs />\n```\n\n```text\nApp.vue\n```\n\n```js\nimport { watchEffect } from 'vue'\nimport { useRoute } from 'vue-router'\n\nconst route = useRoute()\n\nwatchEffect(() => {\n  console.log(route.name)\n})\n```\n\n```text\nroute.name\n```\n\n```text\nundefined\n```\n\n```text\nwatch\n```\n\n```text\nwatchEffect\n```\n\n```text\nrouter.isReady().then(() => {\n  app.mount('#app');\n});\n```\n\n========================================\n\nComments:\n- It seems like your route does not have a name. Can you show the of of `console.log(route)`\n- I found this after hours of searching. This is essential but not well documented\n- This pointed me in the right direction! And thanks for the demo. Another option I've learned is to use something like: `const route = useRoute(); const name = computed(() => route.name);` then in my template: `name is {{name}}`","metadata":{"transformedAt":"2026-08-18T18:33:46.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":116,"estimatedTokens":482}}276{"id":"stack-72718199","source":"stackoverflow","questionId":72718199,"title":"Vue 3 require is not defined for img src","tags":["vue.js","vue-component","vuejs3","vite"],"text":"Title: Vue 3 require is not defined for img src\nTags: vue.js, vue-component, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nWhen i use require in Vue 3, on vue 2 all works\n\n```\n\n```\n\nI get error:\n\n```\n[Vue warn]: Unhandled error during execution of render function \n at \n at \n at \n\nUncaught ReferenceError: require is not defined\n at Proxy._sfc_render (creator.vue:14:24)\n at renderComponentRoot (runtime-core.esm-bundler.js:895:44)\n at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js:5059:57)\n at ReactiveEffect.run (reactivity.esm-bundler.js:185:25)\n at setupRenderEffect (runtime-core.esm-bundler.js:5185:9)\n at mountComponent (runtime-core.esm-bundler.js:4968:9)\n at processComponent (runtime-core.esm-bundler.js:4926:17)\n at patch (runtime-core.esm-bundler.js:4518:21)\n at mountChildren (runtime-core.esm-bundler.js:4714:13)\n at mountElement (runtime-core.esm-bundler.js:4623:17)\n```\n\nJust text text text text\n\n========================================\n\nTop Answer:\n`require` is a webpack specific feature to handle assets import.\n\nUsing vite, it's done differently: https://vitejs.dev/guide/assets.html#importing-asset-as-url\n\nWith the vue vite plugin (that you certainly are using), you can just use a relative or absolute path inside `:src=\"\"` and vite will convert it to a dynamic import under the hood. So it's transparent for you.\n\n```\n\n```\n\n========================================\n\nCode:\n```text\n<img :src=\"require('./img/1.png')\" />\n```\n\n```text\n[Vue warn]: Unhandled error during execution of render function \n      at <Creator key=1 > \n      at <Character> \n      at <App>\n\nUncaught ReferenceError: require is not defined\n      at Proxy._sfc_render (creator.vue:14:24)\n      at renderComponentRoot (runtime-core.esm-bundler.js:895:44)\n      at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js:5059:57)\n      at ReactiveEffect.run (reactivity.esm-bundler.js:185:25)\n      at setupRenderEffect (runtime-core.esm-bundler.js:5185:9)\n      at mountComponent (runtime-core.esm-bundler.js:4968:9)\n      at processComponent (runtime-core.esm-bundler.js:4926:17)\n      at patch (runtime-core.esm-bundler.js:4518:21)\n      at mountChildren (runtime-core.esm-bundler.js:4714:13)\n      at mountElement (runtime-core.esm-bundler.js:4623:17)\n```\n\n```js\n<img :src=\"imageSrc\" />\n...\n<script>\n...\nexport default {\n  ...\n  computed: {\n    imageSrc() {\n      return new URL(`./img/${selectedItem}.png`, import.meta.url).href;\n    }\n  }\n}\n</script>\n```\n\n```text\n<img src=\"./imgs/cat.jpeg\" width=\"300px\" height=\"50px\">\n<img src=\"~/assets/dog.jpg\" width=\"300px\" height=\"50px\">\n```\n\n```text\nrequire\n```\n\n```text\n:src=\"\"\n```\n\n========================================\n\nComments:\n- I don't understand purpose of this. Why don't you use ? Looks like require is some function you didn't define in \"setup\"\n- It's specific to your vite setup, not vue specifically.\n- I used a static path to simplify the issue, the bottom line is that I need a dynamic import.\n- I need a dynamic import.\n- This works perfectly. Still, too bad of vite to have to do it this way.","metadata":{"transformedAt":"2026-08-18T18:33:46.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":110,"estimatedTokens":772}}277{"id":"stack-71462201","source":"stackoverflow","questionId":71462201,"title":"How to fix the asset file path in my Vue (Vite) application build?","tags":["vue.js","vite"],"text":"Title: How to fix the asset file path in my Vue (Vite) application build?\nTags: vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI recently completed a small project in Vue, but when I uploaded it to my server, I am just seeing a blank screen. From my research, I discovered it was likely an issue relating to the asset path as I had it in a sub-directory (https://digitalspaces.dev/portfolio/wil/). After some time trying to fix it by editing the `vite.config.js` file, I gave up and decided to host it in a subdomain (https://wil.digitalspaces.dev/) instead, where it is now.\n\nThe problem is, the index.html now thinks the assets files are at https://digitalspaces.dev/portfolio/wil/assets/, which is true I suppose, but they don't seem to be working from there (nor should they be). Frustratingly, when the build is in https://digitalspaces.dev/assets/, the assets directory is https://digitalspaces.dev/assets/, so it's broken no matter where I have it.\n\nI based my project on the Vue.js quick start guide using vite.\n\nMy complete repo is on GitHub, and this is the `vite.config.js` file:\n\n```\nimport { fileURLToPath, URL } from 'url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport vueJsx from '@vitejs/plugin-vue-jsx'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [vue(), vueJsx()],\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url))\n }\n }\n})\n```\n\nThanks to anyone who is able to help.\n\n========================================\n\nCode:\n```js\nimport { fileURLToPath, URL } from 'url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport vueJsx from '@vitejs/plugin-vue-jsx'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue(), vueJsx()],\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url))\n    }\n  }\n})\n```\n\n```text\nvite.config.js\n```\n\n```text\nvite.config.js\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  ⋮\n  base: '/portfolio/wii/'\n})\n```\n\n```text\n/portfolio/wii/\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":75,"estimatedTokens":524}}278{"id":"stack-76384397","source":"stackoverflow","questionId":76384397,"title":"No loader is configured for \".html\" files: index.html Vitejs","tags":["javascript","typescript","vue.js","vite"],"text":"Title: No loader is configured for \".html\" files: index.html Vitejs\nTags: javascript, typescript, vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nGreetings I have problem. I am using Visual studio 2022 and created two projects there for one solution. One for back-end (ASP.NET) and the second one for fron-end (vuejs and vite). So here starts the problem. I used npm create vue@3 command to create vue project. And its launched fine , but when I did same thing in folder of front-end in my sln project vite throws error what it can not find index.html file\n\n```\nError: Failed to scan for dependencies from entries:\n D:/Projects/C#/DAINIS/vueapp/index.html\n\n X [ERROR] No loader is configured for \".html\" files: index.html\n\n :1:7:\n 1 │ import \"D:/Projects/C#/DAINIS/vueapp/index.html\"\n ╵ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n at failureErrorWithLog (D:\\Projects\\C#\\DAINIS\\vueapp\\node_modules\\esbuild\\lib\\main.js:1638:15)\n at D:\\Projects\\C#\\DAINIS\\vueapp\\node_modules\\esbuild\\lib\\main.js:1050:25\n at runOnEndCallbacks (D:\\Projects\\C#\\DAINIS\\vueapp\\node_modules\\esbuild\\lib\\main.js:1473:45)\n at buildResponseToResult (D:\\Projects\\C#\\DAINIS\\vueapp\\node_modules\\esbuild\\lib\\main.js:1048:7)\n at D:\\Projects\\C#\\DAINIS\\vueapp\\node_modules\\esbuild\\lib\\main.js:1060:9\n at new Promise ()\n at requestCallbacks.on-end (D:\\Projects\\C#\\DAINIS\\vueapp\\node_modules\\esbuild\\lib\\main.js:1059:54)\n at handleRequest (D:\\Projects\\C#\\DAINIS\\vueapp\\node_modules\\esbuild\\lib\\main.js:725:19)\n at handleIncomingPacket (D:\\Projects\\C#\\DAINIS\\vueapp\\node_modules\\esbuild\\lib\\main.js:747:7)\n at Socket.readFromStdout (D:\\Projects\\C#\\DAINIS\\vueapp\\node_modules\\esbuild\\lib\\main.js:675:7)\n```\n\nJust in case I did not changed project it is as is.\n\nProject structure\n\nError dump example\n\nI tried solutions found here and here in stack overflow but still no luck\n\n========================================\n\nCode:\n```bash\nError:   Failed to scan for dependencies from entries:\n  D:/Projects/C#/DAINIS/vueapp/index.html\n\n  X [ERROR] No loader is configured for \".html\" files: index.html\n\n    <stdin>:1:7:\n      1 │ import \"D:/Projects/C#/DAINIS/vueapp/index.html\"\n        ╵        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\n    at failureErrorWithLog (D:\\Projects\\C#\\DAINIS\\vueapp\\node_modules\\esbuild\\lib\\main.js:1638:15)\n    at D:\\Projects\\C#\\DAINIS\\vueapp\\node_modules\\esbuild\\lib\\main.js:1050:25\n    at runOnEndCallbacks (D:\\Projects\\C#\\DAINIS\\vueapp\\node_modules\\esbuild\\lib\\main.js:1473:45)\n    at buildResponseToResult (D:\\Projects\\C#\\DAINIS\\vueapp\\node_modules\\esbuild\\lib\\main.js:1048:7)\n    at D:\\Projects\\C#\\DAINIS\\vueapp\\node_modules\\esbuild\\lib\\main.js:1060:9\n    at new Promise (<anonymous>)\n    at requestCallbacks.on-end (D:\\Projects\\C#\\DAINIS\\vueapp\\node_modules\\esbuild\\lib\\main.js:1059:54)\n    at handleRequest (D:\\Projects\\C#\\DAINIS\\vueapp\\node_modules\\esbuild\\lib\\main.js:725:19)\n    at handleIncomingPacket (D:\\Projects\\C#\\DAINIS\\vueapp\\node_modules\\esbuild\\lib\\main.js:747:7)\n    at Socket.readFromStdout (D:\\Projects\\C#\\DAINIS\\vueapp\\node_modules\\esbuild\\lib\\main.js:675:7)\n```\n\n```text\nD:/Projects/C#/DAINIS/vueapp/\n```\n\n```text\n#\n```\n\n========================================\n\nComments:\n- For those who want to know *why* this won't work it is because of a dependency called (glob)[npmjs.com/glob]. When glob parses a path a `#` signifies a comment.","metadata":{"transformedAt":"2026-08-18T18:33:46.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":75,"estimatedTokens":836}}279{"id":"stack-79317607","source":"stackoverflow","questionId":79317607,"title":"my SVG assets is missing after running vite build","tags":["reactjs","typescript","svg","vite","svgr"],"text":"Title: my SVG assets is missing after running vite build\nTags: reactjs, typescript, svg, vite, svgr\nSource: Stack Overflow\n\nQuestion:\ni have a vite & react project , i use svgr@rollup to use SVGs as react components\n\nwhen i run build , only png images in the src/assets folder is found in dist/assets, no SVG files.. i want to deploy it on vercel or whatever but i don't know what's wrong.\n\nthis is my folder structure:\n\n```\n|-- index.html\n|-- ... other config files\n|-- package.json\n|-- vite.config.ts\n|-- tsconfig.json\n|-- src\n| |-- App.tsx\n| |-- ...\n| |-- vite-env.d.ts\n| |-- assets\n| |-- avatar-1.png\n| |-- avatar-2.png\n| |-- avatar-3.png\n| |-- ... .png\n| |-- Social-X.svg\n| |-- ... .svg\n| |-- Social-Pin.svg\n```\n\nmy vite.config.ts:\n\n```\nimport path from \"path\";\n\nimport react from \"@vitejs/plugin-react\";\nimport { defineConfig } from \"vite\";\nimport svgr from \"@svgr/rollup\";\n\nexport default defineConfig({\n plugins: [\n react(),\n svgr({\n exportType: \"named\",\n ref: true,\n svgo: false,\n dimensions: false,\n typescript: true,\n }),\n \n ],\n resolve: {\n alias: {\n \"@\": path.resolve(__dirname, \"./src\"),\n },\n },\n});\n```\n\ni use them like:\n`import { ReactComponent as ArrowRight } from \"@/assets/arrow-right.svg\"`\n\n========================================\n\nCode:\n```text\n|-- index.html\n|-- ... other config files\n|-- package.json\n|-- vite.config.ts\n|-- tsconfig.json\n|-- src\n|   |-- App.tsx\n|   |-- ...\n|   |-- vite-env.d.ts\n|   |-- assets\n|       |-- avatar-1.png\n|       |-- avatar-2.png\n|       |-- avatar-3.png\n|       |-- ... .png\n|       |-- Social-X.svg\n|       |-- ... .svg\n|       |-- Social-Pin.svg\n```\n\n```js\nimport path from \"path\";\n\nimport react from \"@vitejs/plugin-react\";\nimport { defineConfig } from \"vite\";\nimport svgr from \"@svgr/rollup\";\n\nexport default defineConfig({\n  plugins: [\n    react(),\n    svgr({\n      exportType: \"named\",\n      ref: true,\n      svgo: false,\n      dimensions: false,\n      typescript: true,\n    }),\n    \n  ],\n  resolve: {\n    alias: {\n      \"@\": path.resolve(__dirname, \"./src\"),\n    },\n  },\n});\n```\n\n```text\nimport { ReactComponent as ArrowRight } from \"@/assets/arrow-right.svg\"\n```\n\n```text\nexport default defineConfig({\n  build: {\n    assetsInlineLimit: 0\n  },\n});\n```\n\n```text\n4KiB\n```\n\n```text\nvite.config.js\n```\n\n========================================\n\nComments:\n- Thank you, i had to upload those and fetch them on runtime\n- Thanks, you saved a ton of work, no words can express appreciation for that answer, I hope you will have a good day, sir. The problem I stumbled upon is that React App started to include SVG in JS bundle during Vite upgrade from v4 to v6, but I wanted SVG to being downloaded via browser as media files.\n- Thank you, you know, ChatGPT was not able to resolve this issue well","metadata":{"transformedAt":"2026-08-18T18:33:46.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":139,"estimatedTokens":688}}280{"id":"stack-67518991","source":"stackoverflow","questionId":67518991,"title":"Basic Vite Vanilla Setup","tags":["javascript","html","vite"],"text":"Title: Basic Vite Vanilla Setup\nTags: javascript, html, vite\nSource: Stack Overflow\n\nQuestion:\nI want to set up a very basic project with Vite vanilla\n\nI scaffolded the project with `yarn create @vitejs/app`\n\nNow I adjusted the following files:\n\n**index.html**\n\n```\n\n \n \n \n \n Vite App\n \n \n \n \n \n \n\n### Chat\n\n Message\n \n\n \n Send\n \n \n\n```\n\n**style.css**\n\n```\nh1 {\n color: blue;\n}\n```\n\n**main.js**\n\n```\nconsole.log('hello main.js')\n\nconst chatInput = document.querySelector('textarea')\n\nexport function sendMessage() {\n let message = chatInput.value\n window.alert(message)\n chatInput.value = \"\";\n}\n```\n\nI am now getting the following error in the browser console when I click the \"Send\" button\n\n```\nclient.ts:13 [vite] connecting...\nmain.js:35 hello main.js\nclient.ts:43 [vite] connected.\n(index):18 Uncaught ReferenceError: sendMessage is not defined\n at HTMLButtonElement.onclick ((index):18)\n```\n\n**Workaround**\n\nI can work around the problem by adding an event listener to the button instead of adding the onclick directly in the HTML\n\n```\nconst sendButton = document.querySelector('button')\nsendButton.addEventListener('click', sendMessage)\n```\n\nBut why can't you use the first approach with `onclick=\"sendMessage()\"` within the HTML?\n\n========================================\n\nCode:\n```text\n<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <link rel=\"icon\" type=\"image/svg+xml\" href=\"favicon.svg\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>Vite App</title>\n    <link rel=\"stylesheet\" href=\"style.css\">\n    <script type=\"module\" src=\"main.js\"></script>\n  </head>\n  <body>\n    <div id=\"app\">\n      <h1>Chat</h1>\n        Message\n      <br/>\n      <textarea placeholder=\"Message\"></textarea>\n      <button onclick=\"sendMessage()\">Send</button>\n    </div>\n  </body>\n</html>\n```\n\n```text\nh1 {\n  color: blue;\n}\n```\n\n```text\nconsole.log('hello main.js')\n\nconst chatInput = document.querySelector('textarea')\n\nexport function sendMessage() {\n    let message =  chatInput.value\n    window.alert(message)\n    chatInput.value = \"\";\n}\n```\n\n```sh\nclient.ts:13 [vite] connecting...\nmain.js:35 hello main.js\nclient.ts:43 [vite] connected.\n(index):18 Uncaught ReferenceError: sendMessage is not defined\n    at HTMLButtonElement.onclick ((index):18)\n```\n\n```js\nconst sendButton = document.querySelector('button')\nsendButton.addEventListener('click', sendMessage)\n```\n\n```text\nyarn create @vitejs/app\n```\n\n```text\nonclick=\"sendMessage()\"\n```\n\n```text\nimport { sendMessage } from './events.js'\nwindow.sendMessage = sendMEssage\n```\n\n```text\nMain.js\n```\n\n```text\ntype=module\n```\n\n```text\nwindow\n```\n\n```text\naddEventListener\n```\n\n========================================\n\nComments:\n- Or you can choose to not import the JS file as a module.","metadata":{"transformedAt":"2026-08-18T18:33:46.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":172,"estimatedTokens":699}}281{"id":"stack-70904395","source":"stackoverflow","questionId":70904395,"title":"How to install Laravel Vite?","tags":["laravel","npm","vite","npx"],"text":"Title: How to install Laravel Vite?\nTags: laravel, npm, vite, npx\nSource: Stack Overflow\n\nQuestion:\nThe Laravel Vite Doc sais to run:\n\n```\nnpx apply laravel:vite --ignore-existing\n```\n\ninside your project root to install `vite` in your `laravel project`.\n\nWhen I try to do that in a freshly installed laravel project it shows this:\n\n```\nzsh:1: command not found: laravel:vite\n```\n\nWhat am I doing wrong?\n\nUsing `Macos Big Sur` with `PhpStorm`.\n\n========================================\n\nTop Answer:\nVite is now the default frontend asset bundler in laravel which replaces webpack. No additional installations are needed for new projects.\n\nhttps://laravel-news.com/vite-is-the-default-frontend-asset-bundler-for-laravel-applications\n\n========================================\n\nCode:\n```text\nnpx apply laravel:vite --ignore-existing\n```\n\n```text\nzsh:1: command not found: laravel:vite\n```\n\n```text\nvite\n```\n\n```text\nlaravel project\n```\n\n```text\nMacos Big Sur\n```\n\n```text\nPhpStorm\n```\n\n```sh\n$ npx apply laravel:vite --ignore-existing\n[ info ]  Applying preset laravel:vite.\n[ error ]  The preset could not be evaluated.\nevalmachine.<anonymous>:13\nvar preset_default = definePreset({\n                     ^\n\nReferenceError: definePreset is not defined\n    at evalmachine.<anonymous>:13:22\n    at Script.runInContext (node:vm:139:12)\n    at Object.runInContext (node:vm:289:6)\n    at ModuleImporter.evaluateConfiguration (/Users/tony/src/laravel-vite-demo/example-app/node_modules/apply/dist/Importer/ModuleImporter.js:68:26)\n    at ModuleImporter.import (/Users/tony/src/laravel-vite-demo/example-app/node_modules/apply/dist/Importer/ModuleImporter.js:17:27)\n    at PresetApplier.run (/Users/tony/src/laravel-vite-demo/example-app/node_modules/apply/dist/Applier/PresetApplier.js:22:87)\n    at async CommandLineInterface.apply (/Users/tony/src/laravel-vite-demo/example-app/node_modules/apply/dist/IO/CommandLineInterface.js:57:16)\n    at async CommandLineInterface.run (/Users/tony/src/laravel-vite-demo/example-app/node_modules/apply/dist/IO/CommandLineInterface.js:54:16)\n```\n\n```sh\n# Run this command from root of Laravel project\nnpx @preset/cli apply --debug laravel:vite\n```\n\n```text\nlaravel-vite\n```\n\n```text\nlaravel-presets/vite\n```\n\n```text\nlaravel:vite\n```\n\n```text\n@preset/cli\n```\n\n```text\n--debug\n```\n\n```text\nexception\n```\n\n```text\nphp@8.0\n```\n\n```text\ncomposer\n```\n\n```text\nPATH\n```\n\n```text\nnpm run dev\n```\n\n```text\nphp artisan serve\n```\n\n========================================\n\nComments:\n- I can't reproduce that error (also on Big Sur). How did you run that command?\n- Hey, thanks for looking into this. I just typed it into the PhpStorm terminal inside my project root directory after creating a laravel/laravel composer project","metadata":{"transformedAt":"2026-08-18T18:33:46.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":130,"estimatedTokens":687}}282{"id":"stack-75437272","source":"stackoverflow","questionId":75437272,"title":"Component testing: cypress with vue, vite and vuetify","tags":["vue.js","cypress","vite"],"text":"Title: Component testing: cypress with vue, vite and vuetify\nTags: vue.js, cypress, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to run a component testing for my vuejs app.\nI configured my cypress server following cypress configuration wizard Configuring Component Testing.\n\n**I wanted to run a basic test with just mounting the component :**\n\n```\nimport ProgressCircular from './ProgressCircular.vue'\ndescribe('', () => {\nit('renders', () => {\ncy.mount(ProgressCircular)\n})\n```\n\n})\n\n**I came into this error :**\n\n[Vuetify] Could not find defaults instance\n\n**My vuetify config :**\n\n```\nimport 'vuetify/styles'\nimport { createVuetify } from 'vuetify'\nimport 'vuetify/lib/util/colors'\n\nconst vuetify = createVuetify({\n icons: {\n defaultSet: 'mdi',\n sets: {},\n },\n})\n\nexport default vuetify\n```\n\n**NB**:\n\nMy application ran and built successfully.\n\nI'm using:\n\nvite 4, Vue 3, Vuetify 3, Cypress 12.5.1\n\n========================================\n\nCode:\n```text\nimport ProgressCircular from './ProgressCircular.vue'\ndescribe('<ProgressCircular />', () => {\nit('renders', () => {\ncy.mount(ProgressCircular)\n})\n```\n\n```text\nimport 'vuetify/styles'\nimport { createVuetify } from 'vuetify'\nimport 'vuetify/lib/util/colors'\n\nconst vuetify = createVuetify({\n  icons: {\n    defaultSet: 'mdi',\n    sets: {},\n  },\n})\n\nexport default vuetify\n```\n\n```text\nimport vuetify from \"@/plugins/vuetify\";\nimport App from \"@/App.vue\";\nconst app = createApp(App);\n// Use plugins\napp.use(vuetify);\n```\n\n```text\nCypress.Commands.add(\"mount\", (component, options = {}) => {\n// Setup options object\noptions.global = options.global || {};\noptions.global.stubs = options.global.stubs || {};\noptions.global.stubs[\"transition\"] = false;\noptions.global.components = options.global.components || {};\noptions.global.plugins = options.global.plugins || [];\n\n/* Add any global plugins */\noptions.global.plugins.push({\n  install(app) {\n    app.use(vuetify); //import vuetify from you vuetify config\n  },\n});\n\nreturn mount(component, options);\n});\n```\n\n========================================\n\nComments:\n- Thank you so very much! This should be more present on Google, it would have saved me lots of time.\n- This works for me, thanks. I just added \" import { createApp } from 'vue' \" and change \"@/plugins/vuetify\"; \" to \" \"@/main\"; \" because my createVuetify() is declared in my main.ts .","metadata":{"transformedAt":"2026-08-18T18:33:46.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":108,"estimatedTokens":589}}283{"id":"stack-76530650","source":"stackoverflow","questionId":76530650,"title":"Node modules broken When using Vite + React + Apollo Client","tags":["javascript","reactjs","graphql","vite","apollo-client"],"text":"Title: Node modules broken When using Vite + React + Apollo Client\nTags: javascript, reactjs, graphql, vite, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI tried `@apollo/client` with this starting apollo client document but wanted to use Vite instead of CRA. I imported the modules in `main.jsx` like this:\n\n```\nimport {\n ApolloClient,\n InMemoryCache,\n ApolloProvider,\n gql,\n} from \"@apollo/client/core\";\n\nconst client = new ApolloClient({\n uri: \"https://flyby-router-demo.herokuapp.com/\",\n cache: new InMemoryCache(),\n});\n\n// ...\n\nReactDOM.createRoot(document.getElementById(\"root\")).render(\n \n \n \n \n \n);\n```\n\nand then my app crushed with this message\n\n```\nUncaught SyntaxError: missing ) in parenthetical chunk-NWQ2EI35.js:1493:112\n```\n\nIn \"chunk-NWQ2EI35.js:1493:112\" I could see this js code.\n\n```\n// node_modules/graphql/jsutils/instanceOf.mjs\nvar _globalThis$process;\nvar instanceOf = (\n /* c8 ignore next 6 */\n // FIXME: https://github.com/graphql/graphql-js/issues/2317\n\n // !!! THIS is the line #1493 !!!\n ((_globalThis$process = globalThis.process) === null || _globalThis$process === void 0 ? void 0 : _globalThis$\"development\") === \"production\" ? function instanceOf2(value, constructor) { \n\n // ...\n```\n\nSource from `node_modules/graphql/jsutils/instanceOf.js` :\n\n```\nconst instanceOf =\n /* c8 ignore next 6 */\n // FIXME: https://github.com/graphql/graphql-js/issues/2317\n ((_globalThis$process = globalThis.process) === null ||\n _globalThis$process === void 0\n ? void 0\n : _globalThis$process.env.NODE_ENV) === 'production'\n ? function instanceOf(value, constructor) {\n return value instanceof constructor;\n }\n : function instanceOf(value, constructor) {\n if (value instanceof constructor) {\n return true;\n }\n\n // ...\n```\n\nSeems `_globalThis$process.env.NODE_ENV` changed to `_globalThis$\"development\"`, and this caused the problem.\n\nI have no idea how to use apollo client with vite environment. Needed some helps based on your experiences.\n\n========================================\n\nTop Answer:\nThis is caused by a `graphql` version update from yesterday. A new release to fix this is in the works, meanwhile you can downgrade `graphql` to `16.6.0`.\n\nEdit: this should be fixed with 16.7.1 now.\n\n========================================\n\nCode:\n```js\nimport {\n  ApolloClient,\n  InMemoryCache,\n  ApolloProvider,\n  gql,\n} from \"@apollo/client/core\";\n\nconst client = new ApolloClient({\n  uri: \"https://flyby-router-demo.herokuapp.com/\",\n  cache: new InMemoryCache(),\n});\n\n// ...\n\nReactDOM.createRoot(document.getElementById(\"root\")).render(\n  <ApolloProvider client={client}>\n    <React.StrictMode>\n      <App />\n    </React.StrictMode>\n  </ApolloProvider>\n);\n```\n\n```text\nUncaught SyntaxError: missing ) in parenthetical chunk-NWQ2EI35.js:1493:112\n```\n\n```js\n// node_modules/graphql/jsutils/instanceOf.mjs\nvar _globalThis$process;\nvar instanceOf = (\n  /* c8 ignore next 6 */\n  // FIXME: https://github.com/graphql/graphql-js/issues/2317\n\n  // !!! THIS is the line #1493 !!!\n  ((_globalThis$process = globalThis.process) === null || _globalThis$process === void 0 ? void 0 : _globalThis$\"development\") === \"production\" ? function instanceOf2(value, constructor) { \n\n  // ...\n```\n\n```js\nconst instanceOf =\n  /* c8 ignore next 6 */\n  // FIXME: https://github.com/graphql/graphql-js/issues/2317\n  ((_globalThis$process = globalThis.process) === null ||\n  _globalThis$process === void 0\n    ? void 0\n    : _globalThis$process.env.NODE_ENV) === 'production'\n    ? function instanceOf(value, constructor) {\n        return value instanceof constructor;\n      }\n    : function instanceOf(value, constructor) {\n        if (value instanceof constructor) {\n          return true;\n        }\n\n    // ...\n```\n\n```text\n@apollo/client\n```\n\n```text\nmain.jsx\n```\n\n```text\nnode_modules/graphql/jsutils/instanceOf.js\n```\n\n```text\n_globalThis$process.env.NODE_ENV\n```\n\n```text\n_globalThis$\"development\"\n```\n\n```text\n\"overrides\": {\n    \"graphql\": \"^17.0.0-alpha.2\"\n  }\n```\n\n```text\ngraphql\n```\n\n```text\n16.7.1\n```\n\n```text\n17.0.0-alpha.2\n```\n\n```text\npackage.json\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql\n```\n\n```text\n16.6.0\n```\n\n========================================\n\nComments:\n- Wow what a coincidence.\n- `17.0.0-alpha.2` is 9 months old, and the next release of v17 will contain the same change. If this still causes problems, please create a reproduction and open an issue - at this point the maintainers assume that all problems should be fixed with `16.7.1`. If that is not the case, you'll have to draw their attention to it.\n- Aha, havent noticed it, thanks.\n- Reported here: github.com/graphql/graphql-js/issues/3928","metadata":{"transformedAt":"2026-08-18T18:33:46.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":208,"estimatedTokens":1156}}284{"id":"stack-71357957","source":"stackoverflow","questionId":71357957,"title":"Unable to map docker port from vite app to local","tags":["reactjs","typescript","docker","vite"],"text":"Title: Unable to map docker port from vite app to local\nTags: reactjs, typescript, docker, vite\nSource: Stack Overflow\n\nQuestion:\nI am trying to dockerize a scratch vite react ts app.\n\n```\nFROM node:15.12.0\n\nWORKDIR /app\n\nCOPY entrypoint.sh /entrypoint.sh\nRUN chmod +x /entrypoint.sh\n\nENTRYPOINT [\"/entrypoint.sh\"]\n\nADD . .\n\nRUN npm install\nEXPOSE 3000\nCMD [\"npm\", \"run\", \"dev\"]\n```\n\nDocker compose:\n\n```\nversion: '3.8'\n\nservices:\n dev:\n build: \n context: ./\n dockerfile: Dockerfile\n volumes:\n - ./:/app\n ports:\n - '3000:3000'\n```\n\nI am starting it using docker up --build\nApp seems to be started and ported because docker ps shows:\nf5e840a7fec3 leoapp/leo \"docker-entrypoint.s…\" 4 minutes ago Up 4 minutes 0.0.0.0:3000->3000/tcp sad_gates\n\nBut I am unable to access port 3000 on my browser. What am I doing wrong here.\nVite uses esbuild internally. We need to rebuild esbuild for container architecture during the startup to make it function without errors.\n\n```\nContents of: entrypoint.sh\n\n#!/bin/sh\n\nnpm rebuild esbuild\n\nexec \"$@\"\nDockerfile\n\n# ...\n\nCOPY entrypoint.sh /entrypoint.sh\nRUN chmod +x /entrypoint.sh\n\nENTRYPOINT [\"/entrypoint.sh\"]\n\n# ...\n```\n\nWhen I access port 3000 I get this site cant be reached, however I am able to run the app if run normally i.e `npm run dev`\n\n========================================\n\nTop Answer:\nTry to make your ost publicly available in vite.confi.ts\n\nThis worked for me.\n\n\r\n\r\n\n```\nexport default defineConfig({\n plugins: [react()],\n server: {\n host: \"0.0.0.0\", // publicly available\n port: 5173\n },\n });\n```\n\n========================================\n\nCode:\n```text\nFROM node:15.12.0\n\nWORKDIR /app\n\nCOPY entrypoint.sh /entrypoint.sh\nRUN chmod +x /entrypoint.sh\n\nENTRYPOINT [\"/entrypoint.sh\"]\n\nADD . .\n\nRUN npm install\nEXPOSE 3000\nCMD [\"npm\", \"run\", \"dev\"]\n```\n\n```text\nversion: '3.8'\n\nservices:\n  dev:\n    build: \n      context: ./\n      dockerfile: Dockerfile\n    volumes:\n      - ./:/app\n    ports:\n      - '3000:3000'\n```\n\n```text\nContents of: entrypoint.sh\n\n#!/bin/sh\n\nnpm rebuild esbuild\n\nexec \"$@\"\nDockerfile\n\n# ...\n\nCOPY entrypoint.sh /entrypoint.sh\nRUN chmod +x /entrypoint.sh\n\nENTRYPOINT [\"/entrypoint.sh\"]\n\n# ...\n```\n\n```text\nnpm run dev\n```\n\n```js\nexport default defineConfig({\n  plugins: [react()],\n  server: {\n    watch: {\n      usePolling: true,\n    },\n    host: true, // needed for the Docker Container port mapping to work\n    strictPort: true,\n    port: 3000, // replace this port with any number you want\n  }, \n})\n```\n\n```text\nhost: true\n```\n\n```js\nexport default defineConfig({\n     plugins: [react()],\n     server: {\n      host: \"0.0.0.0\",  // publicly available\n      port: 5173\n     },\n    });\n```\n\n========================================\n\nComments:\n- What goes wrong? What's actually in the `entrypoint.sh` script? Are you trying to connect to some URL and getting some error?\n- cannt conect to website from my browser. The entrypoint.sh is here github.com/vitejs/vite/issues/2671#issuecomment-829535806\n- Please edit the question to include all of the required details in the question itself. I can't tell what URL you're trying to get to, what error you're getting, or what the main container process is. Based on what you've shown, port 3000 on the host should forward to port 3000 in the container, but that still leaves a pretty broad space of potential issues.\n- @DavidMaze I have updated the question. I have added the contents of entrypoint shell file too.","metadata":{"transformedAt":"2026-08-18T18:33:46.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":182,"estimatedTokens":858}}285{"id":"stack-73944060","source":"stackoverflow","questionId":73944060,"title":"Laravel artisan serve and npm run dev single command","tags":["php","node.js","laravel","npm","vite"],"text":"Title: Laravel artisan serve and npm run dev single command\nTags: php, node.js, laravel, npm, vite\nSource: Stack Overflow\n\nQuestion:\nIs there a way to run terminal commands simultaneously\n\nLike\n`php artisan serve`\n\nAnd\n`npm run dev` (for laravel vite)\n\nRun it in a comment or terminal with a shortcut\n\n========================================\n\nTop Answer:\nThere is another solution using `concurrently` npm package\n\nfirst install `concurrently` (you can install it globally)\n\n```\nnpm i concurrently -g\n```\n\nthen run\n\n```\nconcurrently \"php artisan serve\" \"npm run dev\"\n```\n\nor you can use it as package.json script\n\n1 : update you package json like this\n\n```\n\"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build \",\n \"start\": \"concurrently \\\"php artisan config:cache\\\" \\\"php artisan serve\\\" \\\"npm run dev \\\" \"\n },\n```\n\n2 : in terminal run `npm start`\n\n========================================\n\nCode:\n```text\nphp artisan serve\n```\n\n```text\nnpm run dev\n```\n\n```text\nexport part=\"php $PWD/artisan serve\"\n```\n\n```text\npart\n```\n\n```text\n.bash\n```\n\n```text\n.profile\n```\n\n```text\nnpm i concurrently -g\n```\n\n```text\nconcurrently \"php artisan serve\" \"npm run dev\"\n```\n\n```text\n\"scripts\": {\n        \"dev\": \"vite\",\n        \"build\": \"vite build \",\n        \"start\": \"concurrently  \\\"php artisan config:cache\\\" \\\"php artisan serve\\\" \\\"npm run dev \\\"  \"\n    },\n```\n\n```text\nconcurrently\n```\n\n```text\nconcurrently\n```\n\n```text\nnpm start\n```\n\n```text\ncomposer run dev\n```\n\n========================================\n\nComments:\n- You can define a composer script that do both : `\"serve\": [\"npm run dev\", \"php artisan serve\"]` and then `composer serve` it will run both commands one after another. You can also use npm scripts instead, it's the same thing, like `npm run serve`, the only difference is that it's a string not an array ; `\"serve\": \"npm run dev && php artisan serve\"`\n- Does this answer your question? How can I run multiple npm scripts in parallel?\n- @Lk77 unless the first is a long running process, then the second won't run until the first exits cleanly.\n- @Matt that's intended, because we need to wait for build to finish before serving, if we do the other way around, we will have an error on laravel side stating that build files are missing\n- `run dev` is often a long running/server process that doesn't exit, more so in the `webpack`/`vite` case. I was just noting that for that case, the problem requires a different solution.","metadata":{"transformedAt":"2026-08-18T18:33:46.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":113,"estimatedTokens":607}}286{"id":"stack-73348389","source":"stackoverflow","questionId":73348389,"title":"How to import file as text into vite.config.js?","tags":["javascript","vue.js","vite"],"text":"Title: How to import file as text into vite.config.js?\nTags: javascript, vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI have simple scss file in my project directory and I wanna get it's content on the compiling stage so I could transform in on vite.config.js\nbut how can I get it's content?\nI mean I'm able to get content using\n\n```\nimport test from \"./src/extensions/sites/noscript/test.css\";\nconsole.log(test);\n```\n\nin App.vue\nbut that doesn't work in vite.config.js (that works with webpack)\nIs there any ways to get file content?\ntest == {} when I'm debugging... vite.config.js\nand works well in App.vue\n\n========================================\n\nCode:\n```js\nimport test from \"./src/extensions/sites/noscript/test.css\";\nconsole.log(test);\n```\n\n```js\n// vite.config.js\nimport fs from 'fs'\n\nconst styleRaw = fs.readFileSync('./src/extensions/sites/noscript/test.css', 'utf-8')\nconsole.log(styleRaw)\n```\n\n```text\nvite.config.js\n```\n\n```text\nfs.readFileSync()\n```\n\n========================================\n\nComments:\n- HI @tony19, I am facing an obstacle about that: in React Vite, if 1) I try to read on a Windows machine through browser a text file putting just `c:\\\\test.txt` then it reads it perfectly and I can show the content; 2) if I try to read `&#47;home&#47;myuser&#47;test.txt` on Android's browser then it threats like an URL so I can't read the file... how I can tell to read that path just like absolute pat as like on Windows? I tried different ways: fs, vite-plugin-fs, vite-fs but.... thanks in advance\n- Please ask a new question with steps to reproduce so that someone familiar with the topic can help you. I'll chime in if I can.","metadata":{"transformedAt":"2026-08-18T18:33:46.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":49,"estimatedTokens":414}}287{"id":"stack-70970397","source":"stackoverflow","questionId":70970397,"title":"Slow button response time with Capacitor x Svelte on Ios","tags":["ionic-framework","tailwind-css","svelte","capacitor","vite"],"text":"Title: Slow button response time with Capacitor x Svelte on Ios\nTags: ionic-framework, tailwind-css, svelte, capacitor, vite\nSource: Stack Overflow\n\nQuestion:\nI try to create a starter app with Capacitor and Svelte. Everything works fine except one thing, when I use native html anchor ( with svelte-routing) for navigate the there is a slow respond time to user interaction, maybe 400ms before app react on my Iphone 13 pro (real device) Ios 15. Same issue for native html buttons across my starter.\n\ncan you tell me if i did something wrong please ?\n\nthe starter repos -> https://github.com/flameapp-io/svelte-capacitor-tailwind-starter\n\nMy navigation component :\n\n```\n\n import ThemeSwitch from '$lib/ThemeSwitch.svelte';\n import { Link } from 'svelte-routing';\n\n type NavLink = {\n name: string;\n url: string;\n };\n\n const navLinks: Array = [\n {\n name: 'Home',\n url: '/'\n },\n {\n name: 'Example',\n url: 'example'\n }\n ];\n\n {#each navLinks as link}\n {link.name}\n {/each}\n\n \n\n```\n\n========================================\n\nCode:\n```js\n<script lang=\"ts\">\n    import ThemeSwitch from '$lib/ThemeSwitch.svelte';\n    import { Link } from 'svelte-routing';\n\n    type NavLink = {\n        name: string;\n        url: string;\n    };\n\n    const navLinks: Array<NavLink> = [\n        {\n            name: 'Home',\n            url: '/'\n        },\n        {\n            name: 'Example',\n            url: 'example'\n        }\n    ];\n</script>\n\n<nav class=\"flex items-center\">\n    {#each navLinks as link}\n        <Link to={link.url} class=\"mx-5\">{link.name}</Link>\n    {/each}\n\n    <ThemeSwitch />\n</nav>\n```\n\n```html\n<meta name=\"viewport\" content=\"viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"/>\n```\n\n```html\n<meta name=\"viewport\" content=\"viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"/>\n```\n\n========================================\n\nComments:\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:46.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":88,"estimatedTokens":561}}288{"id":"stack-76436006","source":"stackoverflow","questionId":76436006,"title":"v-overlay gets disabled when I click anywhere on the screen","tags":["vue.js","vuejs3","vuetify.js","vite"],"text":"Title: v-overlay gets disabled when I click anywhere on the screen\nTags: vue.js, vuejs3, vuetify.js, vite\nSource: Stack Overflow\n\nQuestion:\nI have an app.vue that comprises of multiple components. One of the components has an overlay on it with a button that should disable the overlay and make the contents visible once clicked. However instead of the button the overlay gets disable once I click anywhere on the screen.\n\n```\ntemplate>\n \n \n \n \n No Automation\n \n \n\n \n \n Active Strategies\n \n \n \n \n \n \n Assetpair\n Strategy\n Actions\n \n \n \n \n {{ row.assetpair }}\n {{ row.strategy }}\n \n \n \n mdi-server-plusStop Strategy\n \n \n \n \n \n \n \n\n```\n\nIf I remove my overlay prop from the data section no overlay gets displayed:\n\n```\nimport axios from 'axios'\n// import StrategyProvider from \"../lib/strategy.js\";\nimport { ref } from 'vue'\n\nconst strategies = ref([{}, {}])\nconst overlay = ref(true)\nconst setOverlay = v => (overlay.value = v)\n\nexport default {\n // props: [\"strategies\"],\n data: function() {\n return {\n overlay: true,\n strategies: []\n };\n },\n```\n\n========================================\n\nCode:\n```text\ntemplate>\n <v-card>\n    <v-row>\n  \n      <v-overlay opacity=\"0.88\" :absolute=\"true\" :model-value=\"overlay\" contained>\n        <v-btn color=\"warning\" @click=\"disenable(false)\">No Automation</v-btn>\n      </v-overlay>\n    </v-row>\n\n    <v-toolbar flat dense color=\"indigo\" style=\"height: 80px;\">\n      <v-toolbar-title style=\"padding-top: 40px;\">\n        Active Strategies\n      </v-toolbar-title>\n    </v-toolbar>\n    <v-divider class=\"mx-4\"></v-divider>\n    <v-table fixed-header height=\"auto\">\n      <thead>\n        <tr>\n          <th class=\"text-left\">Assetpair</th>\n          <th class=\"text-left\">Strategy</th>\n          <th class=\"text-left\">Actions</th>\n        </tr>\n      </thead>\n      <tbody>\n        <tr v-for=\"row in strategies\" v-bind:key=\"row.ticker\">\n          <td>{{ row.assetpair }}</td>\n          <td>{{ row.strategy }}</td>\n          <td>\n            <div class=\"text-left\">\n              <v-chip class=\"ma-2\" color=\"red\" dark @click=\"stopStrategy(127)\">\n                <v-icon left>mdi-server-plus</v-icon>Stop  Strategy\n              </v-chip>\n            </div>\n          </td>\n        </tr>\n      </tbody>\n    </v-table>\n  </v-card>\n</template>\n<script>\n```\n\n```text\nimport axios from 'axios'\n// import StrategyProvider from \"../lib/strategy.js\";\nimport { ref } from 'vue'\n\nconst strategies = ref([{}, {}])\nconst overlay = ref(true)\nconst setOverlay = v => (overlay.value = v)\n\nexport default {\n  // props: [\"strategies\"],\n  data: function() {\n    return {\n      overlay: true,\n      strategies: []\n    };\n  },\n```\n\n```text\n:persistent\n```\n\n========================================\n\nComments:\n- It works fine mate, However, it does not get disabled now even on the button click. I have updated the part of my script section in my question\n- Oh, it looks like you are using options API and define the `overlay` variable in the `data` section. In this case, you have to declare the `setOverlay()` method in the `methods` section and assign to `this.overlay` instead of `overlay.value`, i.e. `methods: { setOverlay(v){ this.overlay = v}}`\n- Works perfectly fine now mate, thank you very very much. One thing How can I centralize the disable buttons to be in perfectly middle of the overlay window covering my component.\n- Easiest is probably to add `class=\"align-center justify-center\"` to the v-overlay. I added it to the playground link","metadata":{"transformedAt":"2026-08-18T18:33:46.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":146,"estimatedTokens":866}}289{"id":"stack-78354831","source":"stackoverflow","questionId":78354831,"title":"How to include attribute value while building XML using fast-xml-parser?","tags":["javascript","reactjs","node.js","npm","vite"],"text":"Title: How to include attribute value while building XML using fast-xml-parser?\nTags: javascript, reactjs, node.js, npm, vite\nSource: Stack Overflow\n\nQuestion:\nfast-xml-parser version 4.3.6\n\n### Description\n\nI need to include xml attribute (tokenized=\"true\"), like this : `test test &gt; 14`\n\n### Input\n\n### Code\n\n```\nvar defaultXmlOptions = {\n ignoreAttributes: false,\n attributeNamePrefix: \"@_\",\n indentBy: \" \",\n textNodeName: \"#text\",\n format: true,\n },\nvar testJson = { component: {\n \"custom-tag\": {\n \"#text\": \"test test > 14\",\n \"@_tokenized\": true\n }\n }}\n```\n\nHere is the code that converts:\n\n```\nvar parser = new XMLBuilder(defaultXmlOptions);\nvar xml = parser.build(testJson);\n```\n\n### Output\n\n```\n\n test test &gt; 14\n\n```\n\nThat attribute should have =\"true\"\n\n### Expected Output\n\n```\n\n test test &gt; 14\n\n```\n\n### Old Code that used to work\n\n```\nvar Parser = require(\"fast-xml-parser\").j2xParser;\nvar parser = new Parser(defaultXmlOptions);\nvar xml = parser.parse(testJson);\n```\n\nNow converting my Project from CRA to Vite can't use require.\n\n========================================\n\nTop Answer:\nWhat you are missing is the option `suppressBooleanAttributes` in the XMLBuilder. By default, boolean attributes like `true` will have its value omitted in the built XML.\n\n\r\n\r\n\n```\nfunction demo() {\n var defaultXmlOptions = {\n ignoreAttributes: false,\n attributeNamePrefix: \"@_\",\n indentBy: \" \",\n textNodeName: \"#text\",\n format: true,\n // You need this to preserve boolean values!\n suppressBooleanAttributes: false,\n };\n var testJson = {\n component: {\n \"custom-tag\": {\n \"#text\": \"test test > 14\",\n \"@_tokenized\": true\n }\n }\n };\n\n var parser = new XMLBuilder(defaultXmlOptions);\n var xml = parser.build(testJson);\n console.log(xml);\n}\n\ndocument.addEventListener(\"readystatechange\", () => document.readyState === \"complete\" && demo());\n```\n\n\r\n\n```\n\n import { XMLBuilder } from 'https://cdn.jsdelivr.net/npm/fast-xml-parser@4.3.6/+esm';\n window.XMLBuilder = XMLBuilder;\n\n```\n\n========================================\n\nCode:\n```js\nvar defaultXmlOptions = {\n      ignoreAttributes: false,\n      attributeNamePrefix: \"@_\",\n      indentBy: \"  \",\n      textNodeName: \"#text\",\n      format: true,\n  },\nvar testJson = { component: {\n      \"custom-tag\": {\n          \"#text\": \"test test > 14\",\n          \"@_tokenized\": true\n      }\n  }}\n```\n\n```js\nvar parser = new XMLBuilder(defaultXmlOptions);\nvar xml = parser.build(testJson);\n```\n\n```text\n<component>\n  <custom-tag tokenized>test test &gt; 14</custom-tag>\n</component>\n```\n\n```text\n<component>\n  <custom-tag tokenized=\"true\">test test &gt; 14</custom-tag>\n</component>\n```\n\n```text\nvar Parser = require(\"fast-xml-parser\").j2xParser;\nvar parser = new Parser(defaultXmlOptions);\nvar xml = parser.parse(testJson);\n```\n\n```text\n<custom-tag tokenized=\"true\">test test &gt; 14</custom-tag>\n```\n\n```js\nattributeValueProcessor: (attrName, attrValue) => {\n  return attrValue;\n}\n```\n\n```text\nsuppressBooleanAttributes\n```\n\n```text\nfalse\n```\n\n```text\nattributeValueProcessor\n```\n\n```text\nsuppressBooleanAttributes\n```\n\n```js\nfunction demo() {\n  var defaultXmlOptions = {\n    ignoreAttributes: false,\n    attributeNamePrefix: \"@_\",\n    indentBy: \"  \",\n    textNodeName: \"#text\",\n    format: true,\n    // You need this to preserve boolean values!\n    suppressBooleanAttributes: false,\n  };\n  var testJson = {\n    component: {\n      \"custom-tag\": {\n        \"#text\": \"test test > 14\",\n        \"@_tokenized\": true\n      }\n    }\n  };\n\n  var parser = new XMLBuilder(defaultXmlOptions);\n  var xml = parser.build(testJson);\n  console.log(xml);\n}\n\ndocument.addEventListener(\"readystatechange\", () => document.readyState === \"complete\" && demo());\n```\n\n```html\n<script type=\"module\">\n  import { XMLBuilder } from 'https://cdn.jsdelivr.net/npm/fast-xml-parser@4.3.6/+esm';\n  window.XMLBuilder = XMLBuilder;\n</script>\n```\n\n```text\nsuppressBooleanAttributes\n```\n\n```text\ntrue\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.416Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":221,"estimatedTokens":976}}290{"id":"stack-73937668","source":"stackoverflow","questionId":73937668,"title":"Vite + Vue3 in Electron: how to import and use Material Design Icons @mdi/font (or any other icon font)","tags":["vue.js","vuejs3","vite","material-design-icons"],"text":"Title: Vite + Vue3 in Electron: how to import and use Material Design Icons @mdi/font (or any other icon font)\nTags: vue.js, vuejs3, vite, material-design-icons\nSource: Stack Overflow\n\nQuestion:\nI want to bundle @mdi/font icons into my application (it's an Electron app).\n\nI installed `npm i @mdi/font --save-dev`:\n\n```\n\"devDependencies\": {\n \"@mdi/font\": \"^7.0.96\",\n }\n```\n\nThen I imported css/scss, I tried several different ways:\n\n- import in `main.ts`: `import '@mdi/font/css/materialdesignicons.css';`\n\n- import as scss in `main.scss`: `@import './node_modules/@mdi/font/scss/materialdesignicons.scss';`\n\n- import as css in `base.css`: `@import './node_modules/@mdi/font/css/materialdesignicons.css';`\n\nThen I used mdi-* css classes in my markup:\n\nSideMenu.vue:\n\n```\n\n \n \n \n \n **\n \n \n \n \n **\n \n \n \n \n **\n \n \n \n \n\n```\n\nThe app starts and working but I see the same icon.\n\nhttps://i.sstatic.net/5zyM5.png\n\nThings to consider:\n\n- I don't want to use component-per-icon approach (don;t see the point), that's because I don't use 'vue-material-design-icons' and the like\n\n- I don't want to use external links to CDN\n\n========================================\n\nCode:\n```json\n\"devDependencies\": {\n    \"@mdi/font\": \"^7.0.96\",\n  }\n```\n\n```html\n<template>\n  <aside class=\"menu\">\n    <ul class=\"action-bar\">\n      <li class=\"action-item active\">\n        <a class=\"action-label icon\">\n          <i class=\"mdi-cog\"></i>\n        </a>\n      </li>\n      <li class=\"action-item\">\n        <a class=\"action-label icon\">\n          <i class=\"mdi-home\"></i>\n        </a>\n      </li>\n      <li class=\"action-item\">\n        <a class=\"action-label icon\">\n          <i class=\"mdi-content-copy\"></i>\n        </a>\n      </li>\n    </ul>\n  </aside>\n</template>\n```\n\n```text\nnpm i @mdi/font --save-dev\n```\n\n```text\nmain.ts\n```\n\n```text\nimport '@mdi/font/css/materialdesignicons.css';\n```\n\n```text\nmain.scss\n```\n\n```text\n@import './node_modules/@mdi/font/scss/materialdesignicons.scss';\n```\n\n```text\nbase.css\n```\n\n```text\n@import './node_modules/@mdi/font/css/materialdesignicons.css';\n```\n\n```html\n<a class=\"action-label icon\">\n  <i class=\"mdi mdi-cog\"></i>\n</a>\n```\n\n```text\nmdi\n```\n\n========================================\n\nComments:\n- I would recommend giving a try to that one: stackoverflow.com/a/72055404/8816585\n- The class should be `mdi mdi-cog`","metadata":{"transformedAt":"2026-08-18T18:33:46.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":137,"estimatedTokens":582}}291{"id":"stack-69601626","source":"stackoverflow","questionId":69601626,"title":"Windi CSS HMR not working for Svelte + vite app","tags":["yarnpkg","svelte","vite","windicss"],"text":"Title: Windi CSS HMR not working for Svelte + vite app\nTags: yarnpkg, svelte, vite, windicss\nSource: Stack Overflow\n\nQuestion:\nI created a Svelte project with Vite and added windicss. I am using Yarn as build tool. I added WindiCSS to vite using https://windicss.org/integrations/vite.html#install. It works fine when I start the project using,\n\n```\nyarn dev\n```\n\nBut HMR (Hot Module Reload) for Windi CSS does not work. But when I kill the server and restart it picks up the Windi CSS changes. Even the Devtool changes are working fine, only HMR is not working.\n\n`package.json` file,\n\n```\n{\n \"name\": \"svelte-in\",\n \"version\": \"0.0.0\",\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"serve\": \"vite preview\"\n },\n \"devDependencies\": {\n \"@sveltejs/vite-plugin-svelte\": \"^1.0.0-next.11\",\n \"svelte\": \"^3.37.0\",\n \"vite\": \"^2.6.4\",\n \"vite-plugin-windicss\": \"^1.4.11\",\n \"windicss\": \"^3.1.9\"\n }\n}\n```\n\n`vite.config.js` file,\n\n```\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\nimport WindiCSS from 'vite-plugin-windicss'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n svelte(), \n WindiCSS()\n ]\n})\n```\n\nAnd `main.js` is,\n\n```\nimport App from './App.svelte'\nimport 'virtual:windi.css'\nimport 'virtual:windi-devtools' // To enable windi in dev tools\n\nconst app = new App({\n target: document.getElementById('app')\n})\n\nexport default app\n```\n\nNot sure if I am missing anything else.\n\n========================================\n\nCode:\n```text\nyarn dev\n```\n\n```text\n{\n  \"name\": \"svelte-in\",\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"serve\": \"vite preview\"\n  },\n  \"devDependencies\": {\n    \"@sveltejs/vite-plugin-svelte\": \"^1.0.0-next.11\",\n    \"svelte\": \"^3.37.0\",\n    \"vite\": \"^2.6.4\",\n    \"vite-plugin-windicss\": \"^1.4.11\",\n    \"windicss\": \"^3.1.9\"\n  }\n}\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\nimport WindiCSS from 'vite-plugin-windicss'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    svelte(), \n    WindiCSS()\n  ]\n})\n```\n\n```text\nimport App from './App.svelte'\nimport 'virtual:windi.css'\nimport 'virtual:windi-devtools'     // To enable windi in dev tools\n\nconst app = new App({\n  target: document.getElementById('app')\n})\n\nexport default app\n```\n\n```text\npackage.json\n```\n\n```text\nvite.config.js\n```\n\n```text\nmain.js\n```\n\n```text\nWindiCSS()\n```\n\n```text\nsvelte()\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":139,"estimatedTokens":627}}292{"id":"stack-79396766","source":"stackoverflow","questionId":79396766,"title":"vite dependency resolving issue: missing ... specifier","tags":["laravel","vite","materialize","npm-scripts"],"text":"Title: vite dependency resolving issue: missing ... specifier\nTags: laravel, vite, materialize, npm-scripts\nSource: Stack Overflow\n\nQuestion:\nI have an old Laravel project where https://materializecss.com is used. Problem is it's old and buggy and it's abandonded in 2018. I decided to switch to popular fork - https://materializeweb.com.\n\nBut I'm having trouble using this dependency with Vite. When I switch to this package\n\n```\nimport '@materializecss/materialize/dist/js/materialize.js'\n```\n\nproject can't be built.\n\n```\n[commonjs--resolver] Missing \"./dist/js/materialize.js\" specifier in \"@materializecss/materialize\" pack...\n```\n\nSame goes for scss imports if I remove js import.\n\n```\n@import \"@materializecss/materialize/sass/components/color-variables\";\n@import \"@materializecss/materialize/sass/materialize\";\n\n//Missing \"./sass/components/color-variables\" specifier\n```\n\nOld package works fine with vite (I migrated from webpack before that, and had no problems with old materializecss package).\n\nLaravel 10.48\nVite 5.4\n@materializecss/materialize 2.2.1\n\nP.S.\nSo far I just found similar problem here, but it helps if it's your internal package, for me it's not.\n\n**UPD:**\n\nvite.config.js trying both solutions from @rozsazoltan\n\n```\nimport path from 'path'\nimport {defineConfig} from 'vite'\nimport laravel from 'laravel-vite-plugin'\nimport vue from '@vitejs/plugin-vue'\n\nexport default defineConfig({\n // optimizeDeps: {\n // include: ['@materializecss/materialize'],\n // },\n resolve: {\n alias: {\n vue: 'vue/dist/vue.esm-bundler.js',\n '@materialize': path.resolve(__dirname, 'node_modules/@materializecss/materialize'),\n }\n },\n build: {\n sourceMap: true,\n },\n plugins: [\n laravel([\n 'resources/styles/app.scss',\n 'resources/js/app.js',\n ]),\n vue({\n template: {\n transformAssetUrls: {\n base: null,\n includeAbsolute: false,\n },\n },\n })\n ],\n});\n```\n\nscripts in package.json\n\n```\n\"scripts\": {\n \"build-dev\": \"vite build --mode development\",\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"serve\": \"vite preview\"\n },\n```\n\n**UPD2.SOLVED:**\nAbove in vite config file there is a typo I got from early version of the answer. @rozsazoltan has fixed it by now. Second solution with path resolving is working!\n\n========================================\n\nCode:\n```text\nimport '@materializecss/materialize/dist/js/materialize.js'\n```\n\n```text\n[commonjs--resolver] Missing \"./dist/js/materialize.js\" specifier in \"@materializecss/materialize\" pack...\n```\n\n```text\n@import \"@materializecss/materialize/sass/components/color-variables\";\n@import \"@materializecss/materialize/sass/materialize\";\n\n//Missing \"./sass/components/color-variables\" specifier\n```\n\n```text\nimport path from 'path'\nimport {defineConfig} from 'vite'\nimport laravel from 'laravel-vite-plugin'\nimport vue from '@vitejs/plugin-vue'\n\nexport default defineConfig({\n    // optimizeDeps: {\n    //     include: ['@materializecss/materialize'],\n    // },\n    resolve: {\n        alias: {\n            vue: 'vue/dist/vue.esm-bundler.js',\n            '@materialize': path.resolve(__dirname, 'node_modules/@materializecss/materialize'),\n        }\n    },\n    build: {\n        sourceMap: true,\n    },\n    plugins: [\n        laravel([\n            'resources/styles/app.scss',\n            'resources/js/app.js',\n        ]),\n        vue({\n            template: {\n                transformAssetUrls: {\n                    base: null,\n                    includeAbsolute: false,\n                },\n            },\n        })\n    ],\n});\n```\n\n```text\n\"scripts\": {\n        \"build-dev\": \"vite build --mode development\",\n        \"dev\": \"vite\",\n        \"build\": \"vite build\",\n        \"serve\": \"vite preview\"\n    },\n```\n\n```js\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  optimizeDeps: {\n    include: ['@materializecss/materialize'],\n  },\n})\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport path from 'path'\n\nexport default defineConfig({\n  resolve: {\n    alias: {\n      '@materialize/materialize': path.resolve(__dirname, 'node_modules/@materializecss/materialize'),\n    },\n  },\n})\n```\n\n```text\noptimizeDeps.include\n```\n\n```text\nvite.config.js\n```\n\n```text\nnode_modules\n```\n\n```text\nresolve.alias\n```\n\n========================================\n\nComments:\n- Since I haven't tested it myself, I'm relying on Barmaxon's feedback: the second solution (resolve.alias) definitely worked. So Vite couldn't access the package at all, making it necessary to declare the full path under a new alias namespace.\n- This answer works, but you don't explain why. The older `materialize-css` package.json doesn't contain an \"exports\" property, but the newer package does. Using a custom alias bypasses vite's attempt to load the specifier from `.&#47;dist&#47;js&#47;materialize.mjs` rather than just using the directory structure.\n- alias: { '@materialize/materialize': path.resolve(__dirname, 'node_modules/@materializecss/materialize'), }, this works","metadata":{"transformedAt":"2026-08-18T18:33:46.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":199,"estimatedTokens":1224}}293{"id":"stack-78180052","source":"stackoverflow","questionId":78180052,"title":"TypeError: _jsxDEV is not a function in React-Vite App Using Docker-Compose","tags":["reactjs","docker","docker-compose","vite"],"text":"Title: TypeError: _jsxDEV is not a function in React-Vite App Using Docker-Compose\nTags: reactjs, docker, docker-compose, vite\nSource: Stack Overflow\n\nQuestion:\n**Introduction**: I'm encountering a runtime error when trying to run my React-Vite application using Docker-Compose. The application works perfectly when I use `npm run dev` directly within Docker, but fails with an error when started with `docker-compose up`.\n\n**Environment/Setup**:\n\n- React (Vite-based project)\n\n- Docker and Docker-Compose\n\n- Node.js 16, 18, 20 (all were tested)\n\nUpon starting my application with `docker-compose up`, the application seems to start without issues. However, when I open the page, the console throws the following error:\n\n```\nTypeError: _jsxDEV is not a function. (In '_jsxDEV(App, {}, void 0, false, {\n fileName: \"/app/src/main.tsx\",\n lineNumber: 8,\n columnNumber: 5\n }, this)', '_jsxDEV' is undefined)\n```\n\n- This error does not occur when using `docker run -p 5173:5173 my-react-app`, it occurs only when using `docker-compose up frontend`\n\n**What You've Tried**:\n\n- I've made sure all dependencies are correctly installed.\n\n- I've checked for any possible misconfigurations in my Dockerfile and docker-compose.yml, but everything seems in order.\n\n**Expected vs. Actual Behavior**: I expected the application to run without errors, as it does when started with `docker run` command. However, running it with Docker-Compose results in the mentioned TypeError.\n\n**Code Samples**:\n\n- Dockerfile configuration\n\n```\n# Use a Node.js image\nFROM node:16\n\n# Set the working directory\nWORKDIR /app\n\n# Copy everything to the container\nCOPY package*.json .\n\n# Install dependencies\nRUN npm install\n\n# Copy everything to the container\nCOPY . .\n\n# Expose port\nEXPOSE 5173\n\n# Start the app from entrypoint\nENTRYPOINT [\"./entrypoint.sh\"]\n```\n\n- docker-compose.yml configuration\n\n```\nfrontend:\n build: ./frontend\n ports:\n - \"5173:5173\"\n volumes:\n - ./frontend:/app\n - /app/node_modules\n - frontend_build:/app/dist\n - type: bind\n source: ./.env\n target: /app/.env\n env_file:\n - .env\n```\n\n- entrypoint.sh\n\n```\n#!/bin/bash\n\nif [ \"$ENVIRONMENT\" = \"development\" ]; then\n npm run dev\nelse\n npm run build\nfi\n```\n\n- vite.config.ts\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n server: {\n watch: {\n usePolling: true,\n },\n host: true, \n strictPort: true,\n port: 5173,\n },\n})\n```\n\n**Additional Context**\n\nSteps to reproduce the error:\n\n- Intialize React App: `npm create vite@latest frontend -- --template react-swc-ts`\n\n- `Dockerfile` should go in `frontend` folder\n\n- `docker-compose.yml` is found in the `parent` folder\n\n**Document Tree**:\n\n```\n- parent\n| - docker-compose.yml\n| - frontend\n| | - Dockerfile\n| | - vite.config.ts\n| | - rest of the app\n```\n\n========================================\n\nTop Answer:\nAdding\n\n```\nesbuild: {\n jsx: \"automatic\",\n jsxDev: false,\n },\n```\n\nin vite.config.Ts fixed it for me.\n\n========================================\n\nCode:\n```text\nTypeError: _jsxDEV is not a function. (In '_jsxDEV(App, {}, void 0, false, {\n        fileName: \"/app/src/main.tsx\",\n        lineNumber: 8,\n        columnNumber: 5\n    }, this)', '_jsxDEV' is undefined)\n```\n\n```text\n# Use a Node.js image\nFROM node:16\n\n# Set the working directory\nWORKDIR /app\n\n# Copy everything to the container\nCOPY package*.json .\n\n# Install dependencies\nRUN npm install\n\n# Copy everything to the container\nCOPY . .\n\n# Expose port\nEXPOSE 5173\n\n# Start the app from entrypoint\nENTRYPOINT [\"./entrypoint.sh\"]\n```\n\n```text\nfrontend:\n    build: ./frontend\n    ports:\n      - \"5173:5173\"\n    volumes:\n      - ./frontend:/app\n      - /app/node_modules\n      - frontend_build:/app/dist\n      - type: bind\n        source: ./.env\n        target: /app/.env\n    env_file:\n      - .env\n```\n\n```text\n#!/bin/bash\n\nif [ \"$ENVIRONMENT\" = \"development\" ]; then\n  npm run dev\nelse\n  npm run build\nfi\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  server: {\n    watch: {\n      usePolling: true,\n    },\n    host: true, \n    strictPort: true,\n    port: 5173,\n  },\n})\n```\n\n```text\n- parent\n| - docker-compose.yml\n| - frontend\n| | - Dockerfile\n| | - vite.config.ts\n| | - rest of the app\n```\n\n```text\nnpm run dev\n```\n\n```text\ndocker-compose up\n```\n\n```text\ndocker-compose up\n```\n\n```text\ndocker run -p 5173:5173 my-react-app\n```\n\n```text\ndocker-compose up frontend\n```\n\n```text\ndocker run\n```\n\n```text\nnpm create vite@latest frontend -- --template react-swc-ts\n```\n\n```text\nDockerfile\n```\n\n```text\nfrontend\n```\n\n```text\ndocker-compose.yml\n```\n\n```text\nparent\n```\n\n```text\n.env\n```\n\n```text\nNODE_ENV\n```\n\n```text\nproduction\n```\n\n```text\nNODE_ENV\n```\n\n```text\ndevelopment\n```\n\n```text\nesbuild: {\n    jsx: \"automatic\",\n    jsxDev: false,\n  },\n```\n\n========================================\n\nComments:\n- so how one can distinguish running environment in debug and production ? it common do have different logging, db connection etc depending on the running environment","metadata":{"transformedAt":"2026-08-18T18:33:46.416Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":309,"estimatedTokens":1289}}294{"id":"stack-79425012","source":"stackoverflow","questionId":79425012,"title":"How to override TailwindCSS v4 default design using React and Vite","tags":["reactjs","tailwind-css","vite","tailwind-css-4"],"text":"Title: How to override TailwindCSS v4 default design using React and Vite\nTags: reactjs, tailwind-css, vite, tailwind-css-4\nSource: Stack Overflow\n\nQuestion:\nI have just installed my react project with Vite and TaiwindCSS v4 (latest version), but I don't find the `tailwind.config.js`.\n\nDoes anyone has an idea how to to override TailwindCSS v4 default design please? If I have to add `tailwind.config.js`, have you any idea how to configure it in the project? Thanks.\n\n========================================\n\nCode:\n```text\ntailwind.config.js\n```\n\n```text\ntailwind.config.js\n```\n\n```css\n@import \"tailwindcss\";\n\n@theme {\n  --color-primary: red;\n}\n```\n\n```html\n<div class=\"text-primary\">I will be red</div>\n```\n\n```css\n/* Path relative to this CSS file. */\n@config \"../../tailwindcss.config.js\";\n```\n\n```text\n@theme\n```\n\n```text\ntailwind.config.js\n```\n\n```text\n@config\n```\n\n========================================\n\nComments:\n- Maybe related: How to setting Tailwind CSS v4 global class?\n- many thanks man.\n- @Wongin did you mean to use `text-primary` instead of `text-red`?\n- Fruedian slip, fixed. Thanks.","metadata":{"transformedAt":"2026-08-18T18:33:46.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":56,"estimatedTokens":277}}295{"id":"stack-72487135","source":"stackoverflow","questionId":72487135,"title":"How to use enviroment variables in Svelte @ index.html","tags":["svelte","vite","sveltekit"],"text":"Title: How to use enviroment variables in Svelte @ index.html\nTags: svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI would like to use a environmental variable in `svelte-kit` project but unfornutaely I'm not being able to.\n\nI have tried to:\n\n*app.html*\n\n```\n\n\">\n\">\n```\n\nIn my `.env` I have the variable defined:\n\n```\nVITE_GOOGLE_TAG=xxxxx\n```\n\nBut the substitution doesn't happen when I re-start my server.\n\nI'm looking to have a different `Google tag manager id` for each enviroment. Something like\n\n```\nstaging -> xxxxx\nproduction -> yyyyy\n```\n\nHow can I access enviromental variables in `svelte-kit` in my `app.html`?\n\n========================================\n\nCode:\n```html\n<meta name=\"TESTING\" value=\"%VITE_GOOGLE_TAG%\">\n<meta name=\"TESTING\" value=\"<% VITE_GOOGLE_TAG %>\">\n<meta name=\"TESTING\" value=\"<% process.env.VITE_GOOGLE_TAG %>\">\n```\n\n```text\nVITE_GOOGLE_TAG=xxxxx\n```\n\n```text\nstaging -> xxxxx\nproduction -> yyyyy\n```\n\n```text\nsvelte-kit\n```\n\n```text\n.env\n```\n\n```text\nGoogle tag manager id\n```\n\n```text\nsvelte-kit\n```\n\n```text\napp.html\n```\n\n```html\n<!-- src/routes/__layout.svelte -->\n<svelte:head>\n  <meta name=\"TESTING\" value={import.meta.env.VITE_GOOGLE_TAG}>\n</svelte:head>\n```\n\n```text\n<meta>\n```\n\n```text\n<head>\n```\n\n```text\n<svelte:head>\n```\n\n```text\n<meta>\n```\n\n```text\nsrc/routes/__layout.svelte\n```\n\n```text\nimport.meta.env.VARNAME\n```\n\n```text\n<meta>.value\n```\n\n========================================\n\nComments:\n- Did you tried to just use the svelte's `` component that makes it possible to insert elements into `document.head`? Read more about it here svelte.dev/docs#template-syntax-svelte-head\n- @johannchopin yeah. I was overly complicating things. Thank you","metadata":{"transformedAt":"2026-08-18T18:33:46.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":112,"estimatedTokens":426}}296{"id":"stack-69490057","source":"stackoverflow","questionId":69490057,"title":"Vite: img src alias not working when passing as component props","tags":["vue.js","vuejs3","vite"],"text":"Title: Vite: img src alias not working when passing as component props\nTags: vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI have configured Vite with an alias `\"@\"` as `\"./src\"`.\n\nUsing the alias directly as `.src` is ok:\n\n```\n\n```\n\nbut passing the `src` as a prop is not working:\n\n```\n\n \n\n```\n\nIs there any solution to use file path alias when passing props?\n\n========================================\n\nTop Answer:\n@tony19 Answer was what works for me. Using Vue 3 with Vite + TypeScript (Js should work too!) The only difference, is that if aren't using a script with the \"setup\" attribute: **You need to import the image, and return it inside the export default**. See:\n\n\r\n\r\n\n```\n\nimport { defineComponent } from 'vue'\n//Import the images:\nimport feedImg from './assets/img/feed.png'\n\nexport default defineComponent({\n setup() {\n //Return the imgs:\n return {\n feedImg\n }\n }\n})\n\n```\n\n\r\n\r\n\r\n\nAfter that, you just need to bind the image to the prop on the component usage:\n\n\r\n\r\n\n```\n\n```\n\n\r\n\r\n\r\n\nAnd load it on the component itself, binding the src on the img tag:\n\n\r\n\r\n\n```\n\n \n\nimport { defineComponent } from 'vue'\n\nexport default defineComponent({\n props: {\n imgSrc: {\n type: String,\n required: true\n },\n alt: {\n type: String,\n required: true\n }\n }\n})\n\n```\n\n========================================\n\nCode:\n```html\n<!-- this is ok -->\n<img src=\"@/assets/icon-1.svg\">\n```\n\n```html\n<!-- ComponentA -->\n<template>\n  <img :src=\"imgSrc\">\n</template>\n\n<!-- Parent Component: alias not resolved as expected; imgSrcWithAlias is \"@/assets/icon-1.svg\"  -->\n<component-a :img-src=\"imgSrcWithAlias\" />\n```\n\n```text\n\"@\"\n```\n\n```text\n\"./src\"\n```\n\n```text\n<img>.src\n```\n\n```text\nsrc\n```\n\n```html\n<script setup>\nimport imgSrcWithAlias from '@/assets/icon-1.svg'\n</script>\n\n<template>\n  <component-a :img-src=\"imgSrcWithAlias\" />\n</template>\n```\n\n```text\nimport\n```\n\n```js\n<script lang=\"ts\">\nimport { defineComponent } from 'vue'\n//Import the images:\nimport feedImg from './assets/img/feed.png'\n\nexport default defineComponent({\n  setup() {\n    //Return the imgs:\n    return {\n      feedImg\n    }\n  }\n})\n</script>\n```\n\n```html\n<ImageComponent\n   :imgSrc=\"feedImg\"\n   alt=\"Videos on homepage\"\n />\n```\n\n```js\n<template>\n  <img :alt=\"alt\" :src=\"imgSrc\" />\n</template>\n\n<script lang=\"ts\">\nimport { defineComponent } from 'vue'\n\nexport default defineComponent({\n  props: {\n    imgSrc: {\n      type: String,\n      required: true\n    },\n    alt: {\n      type: String,\n      required: true\n    }\n  }\n})\n</script>\n```\n\n========================================\n\nComments:\n- Thanks! I also had to add the `resolve` config from your StackBlitz demo to my `nuxt.config.js` to get it working.\n- this will mark all images as `prefetch` to read them on page load. don't do this if you are using responsive images for various resolutions. Then they will be all loaded at the beginning.","metadata":{"transformedAt":"2026-08-18T18:33:46.416Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":191,"estimatedTokens":716}}297{"id":"stack-79544832","source":"stackoverflow","questionId":79544832,"title":"Cannot find module 'better-sqlite3' after building Electron Forge Vite app (on Linux)","tags":["linux","electron","vite","electron-forge","better-sqlite3"],"text":"Title: Cannot find module 'better-sqlite3' after building Electron Forge Vite app (on Linux)\nTags: linux, electron, vite, electron-forge, better-sqlite3\nSource: Stack Overflow\n\nQuestion:\nI'm trying to develop an Electron Forge Vite app that uses `better-sqlite3` as database. It works fine in development environment but after I build a .deb package to test it outside development (I'm on Ubuntu) I get following error:\n\n```\nA JavaScript error occurred in the main process\nUncaught Exception:\nError: Cannot find module 'better-sqlite3'\nRequire stack:\n- /usr/lib/babel-gate/resources/app.asar/.vite/build/main.js\n- \n at Module._resolveFilename (node:internal/modules/cjs/loader:1232:15)\n at s._resolveFilename (node:electron/js2c/browser_init:2:124485)\n at Module._load (node:internal/modules/cjs/loader:1058:27)\n at c._load (node:electron/js2c/node_init:2:16955)\n at Module.require (node:internal/modules/cjs/loader:1318:19)\n at require (node:internal/modules/helpers:179:18)\n at Object. (/usr/lib/babel-gate/resources/app.asar/.vite/build/main.js:30:61788)\n at Module._compile (node:internal/modules/cjs/loader:1484:14)\n at Module._extensions..js (node:internal/modules/cjs/loader:1564:10)\n at Module.load (node:internal/modules/cjs/loader:1295:32)\n```\n\nMy `forge.config.js`:\n\n```\nconst { FusesPlugin } = require(\"@electron-forge/plugin-fuses\");\nconst { FuseV1Options, FuseVersion } = require(\"@electron/fuses\");\n\nmodule.exports = {\n packagerConfig: {\n asar: true,\n executableName: \"babel-gate\",\n },\n rebuildConfig: {\n buildOnly: true,\n force: true,\n },\n makers: [\n {\n name: \"@electron-forge/maker-squirrel\",\n config: {},\n },\n {\n name: \"@electron-forge/maker-zip\",\n platforms: [\"darwin\"],\n },\n {\n name: \"@electron-forge/maker-deb\",\n config: {},\n },\n {\n name: \"@electron-forge/maker-rpm\",\n config: {},\n },\n ],\n plugins: [\n {\n name: \"@electron-forge/plugin-auto-unpack-natives\",\n config: {},\n },\n {\n name: \"@electron-forge/plugin-vite\",\n config: {\n // `build` can specify multiple entry builds, which can be Main process, Preload scripts, Worker process, etc.\n // If you are familiar with Vite configuration, it will look really familiar.\n build: [\n {\n // `entry` is just an alias for `build.lib.entry` in the corresponding file of `config`.\n entry: \"src/main.js\",\n config: \"vite_configs/vite.main.config.mjs\",\n target: \"main\",\n },\n {\n entry: \"src/preload.js\",\n config: \"vite_configs/vite.preload.config.mjs\",\n target: \"preload\",\n },\n {\n entry: \"src/overlay/overlay_preload.js\",\n config: \"vite_configs/vite.overlay_preload.config.mjs\",\n target: \"preload\",\n },\n ],\n renderer: [\n {\n name: \"main_window\",\n config: \"vite_configs/vite.renderer.config.mjs\",\n },\n ],\n },\n },\n // Fuses are used to enable/disable various Electron functionality\n // at package time, before code signing the application\n new FusesPlugin({\n version: FuseVersion.V1,\n [FuseV1Options.RunAsNode]: false,\n [FuseV1Options.EnableCookieEncryption]: true,\n [FuseV1Options.EnableNodeOptionsEnvironmentVariable]: false,\n [FuseV1Options.EnableNodeCliInspectArguments]: false,\n [FuseV1Options.EnableEmbeddedAsarIntegrityValidation]: true,\n [FuseV1Options.OnlyLoadAppFromAsar]: true,\n }),\n ],\n};\n```\n\nMy `package.json`:\n\n```\n{\n \"name\": \"babel-gate\",\n \"productName\": \"BabelGate\",\n \"version\": \"1.0.0\",\n \"description\": \"My Electron application description\",\n \"main\": \".vite/build/main.js\",\n \"scripts\": {\n \"start\": \"electron-forge start\",\n \"package\": \"electron-forge package\",\n \"make\": \"electron-forge make\",\n \"publish\": \"electron-forge publish\",\n \"lint\": \"echo \\\"No linting configured\\\"\"\n },\n \"keywords\": [],\n \"author\": {\n \"name\": \"fa1ryJack\",\n \"email\": \"mymail@gmail.com\"\n },\n \"license\": \"MIT\",\n \"devDependencies\": {\n \"@electron-forge/cli\": \"^7.8.0\",\n \"@electron-forge/maker-deb\": \"^7.7.0\",\n \"@electron-forge/maker-rpm\": \"^7.8.0\",\n \"@electron-forge/maker-squirrel\": \"^7.7.0\",\n \"@electron-forge/maker-zip\": \"^7.7.0\",\n \"@electron-forge/plugin-auto-unpack-natives\": \"^7.8.0\",\n \"@electron-forge/plugin-fuses\": \"^7.7.0\",\n \"@electron-forge/plugin-vite\": \"^7.7.0\",\n \"@electron/fuses\": \"^1.8.0\",\n \"@electron/rebuild\": \"^3.7.1\",\n \"@rollup/plugin-commonjs\": \"^28.0.3\",\n \"@vitejs/plugin-vue\": \"^5.2.1\",\n \"electron\": \"34.3.0\",\n \"electron-forge-maker-appimage\": \"^26.0.12\",\n \"vite\": \"^6.2.2\"\n },\n \"dependencies\": {\n \"better-sqlite3\": \"^11.9.1\",\n \"deepl-node\": \"^1.17.3\",\n \"dotenv\": \"^16.4.7\",\n \"electron-squirrel-startup\": \"^1.0.1\",\n \"p-queue\": \"^8.1.0\",\n \"tesseract.js\": \"^6.0.0\",\n \"vue\": \"^3.5.13\",\n \"vue-router\": \"^4.5.0\"\n }\n}\n```\n\nIn my `database.js` I call `better-sqlite3` as:\n\n```\nconst Database = require(\"better-sqlite3\");\n```\n\n### What I've tried:\n\n- Explicitly rebuilding native modules with `electron-rebuild`\n\n- Adding `asarUnpack` and `extraResource` for `better-sqlite3` in `forge.config.js` like this:\n\n```\npackagerConfig: {\n asar: true,\n executableName: \"babel-gate\",\n extraResource: [\"./node_modules/better-sqlite3\"],\n asarUnpack: [\"**/node_modules/better-sqlite3/**\"]\n}\n```\n\n- Setting `FuseV1Options.OnlyLoadAppFromAsar` to `false`\n\n- This solution https://stackoverflow.com/a/79445715/22621183 but I needed to add even more dependencies to the hook and at some point building process just crashed every time on `Packaging for x64 on Linux` without producing error.\n\n========================================\n\nTop Answer:\nAdding this line actually worked\n\nconfig :\n\n```\nasar: {\n unpack: \"*.{node,dll}\",\n },\n ignore: [/node_modules\\/(?!(better-sqlite3|bindings|file-uri-to-path)\\/)/],\n },\n```\n\n========================================\n\nCode:\n```bash\nA JavaScript error occurred in the main process\nUncaught Exception:\nError: Cannot find module 'better-sqlite3'\nRequire stack:\n- /usr/lib/babel-gate/resources/app.asar/.vite/build/main.js\n- \n    at Module._resolveFilename (node:internal/modules/cjs/loader:1232:15)\n    at s._resolveFilename (node:electron/js2c/browser_init:2:124485)\n    at Module._load (node:internal/modules/cjs/loader:1058:27)\n    at c._load (node:electron/js2c/node_init:2:16955)\n    at Module.require (node:internal/modules/cjs/loader:1318:19)\n    at require (node:internal/modules/helpers:179:18)\n    at Object.<anonymous> (/usr/lib/babel-gate/resources/app.asar/.vite/build/main.js:30:61788)\n    at Module._compile (node:internal/modules/cjs/loader:1484:14)\n    at Module._extensions..js (node:internal/modules/cjs/loader:1564:10)\n    at Module.load (node:internal/modules/cjs/loader:1295:32)\n```\n\n```js\nconst { FusesPlugin } = require(\"@electron-forge/plugin-fuses\");\nconst { FuseV1Options, FuseVersion } = require(\"@electron/fuses\");\n\nmodule.exports = {\n  packagerConfig: {\n    asar: true,\n    executableName: \"babel-gate\",\n  },\n  rebuildConfig: {\n    buildOnly: true,\n    force: true,\n  },\n  makers: [\n    {\n      name: \"@electron-forge/maker-squirrel\",\n      config: {},\n    },\n    {\n      name: \"@electron-forge/maker-zip\",\n      platforms: [\"darwin\"],\n    },\n    {\n      name: \"@electron-forge/maker-deb\",\n      config: {},\n    },\n    {\n      name: \"@electron-forge/maker-rpm\",\n      config: {},\n    },\n  ],\n  plugins: [\n    {\n      name: \"@electron-forge/plugin-auto-unpack-natives\",\n      config: {},\n    },\n    {\n      name: \"@electron-forge/plugin-vite\",\n      config: {\n        // `build` can specify multiple entry builds, which can be Main process, Preload scripts, Worker process, etc.\n        // If you are familiar with Vite configuration, it will look really familiar.\n        build: [\n          {\n            // `entry` is just an alias for `build.lib.entry` in the corresponding file of `config`.\n            entry: \"src/main.js\",\n            config: \"vite_configs/vite.main.config.mjs\",\n            target: \"main\",\n          },\n          {\n            entry: \"src/preload.js\",\n            config: \"vite_configs/vite.preload.config.mjs\",\n            target: \"preload\",\n          },\n          {\n            entry: \"src/overlay/overlay_preload.js\",\n            config: \"vite_configs/vite.overlay_preload.config.mjs\",\n            target: \"preload\",\n          },\n        ],\n        renderer: [\n          {\n            name: \"main_window\",\n            config: \"vite_configs/vite.renderer.config.mjs\",\n          },\n        ],\n      },\n    },\n    // Fuses are used to enable/disable various Electron functionality\n    // at package time, before code signing the application\n    new FusesPlugin({\n      version: FuseVersion.V1,\n      [FuseV1Options.RunAsNode]: false,\n      [FuseV1Options.EnableCookieEncryption]: true,\n      [FuseV1Options.EnableNodeOptionsEnvironmentVariable]: false,\n      [FuseV1Options.EnableNodeCliInspectArguments]: false,\n      [FuseV1Options.EnableEmbeddedAsarIntegrityValidation]: true,\n      [FuseV1Options.OnlyLoadAppFromAsar]: true,\n    }),\n  ],\n};\n```\n\n```json\n{\n  \"name\": \"babel-gate\",\n  \"productName\": \"BabelGate\",\n  \"version\": \"1.0.0\",\n  \"description\": \"My Electron application description\",\n  \"main\": \".vite/build/main.js\",\n  \"scripts\": {\n    \"start\": \"electron-forge start\",\n    \"package\": \"electron-forge package\",\n    \"make\": \"electron-forge make\",\n    \"publish\": \"electron-forge publish\",\n    \"lint\": \"echo \\\"No linting configured\\\"\"\n  },\n  \"keywords\": [],\n  \"author\": {\n    \"name\": \"fa1ryJack\",\n    \"email\": \"mymail@gmail.com\"\n  },\n  \"license\": \"MIT\",\n  \"devDependencies\": {\n    \"@electron-forge/cli\": \"^7.8.0\",\n    \"@electron-forge/maker-deb\": \"^7.7.0\",\n    \"@electron-forge/maker-rpm\": \"^7.8.0\",\n    \"@electron-forge/maker-squirrel\": \"^7.7.0\",\n    \"@electron-forge/maker-zip\": \"^7.7.0\",\n    \"@electron-forge/plugin-auto-unpack-natives\": \"^7.8.0\",\n    \"@electron-forge/plugin-fuses\": \"^7.7.0\",\n    \"@electron-forge/plugin-vite\": \"^7.7.0\",\n    \"@electron/fuses\": \"^1.8.0\",\n    \"@electron/rebuild\": \"^3.7.1\",\n    \"@rollup/plugin-commonjs\": \"^28.0.3\",\n    \"@vitejs/plugin-vue\": \"^5.2.1\",\n    \"electron\": \"34.3.0\",\n    \"electron-forge-maker-appimage\": \"^26.0.12\",\n    \"vite\": \"^6.2.2\"\n  },\n  \"dependencies\": {\n    \"better-sqlite3\": \"^11.9.1\",\n    \"deepl-node\": \"^1.17.3\",\n    \"dotenv\": \"^16.4.7\",\n    \"electron-squirrel-startup\": \"^1.0.1\",\n    \"p-queue\": \"^8.1.0\",\n    \"tesseract.js\": \"^6.0.0\",\n    \"vue\": \"^3.5.13\",\n    \"vue-router\": \"^4.5.0\"\n  }\n}\n```\n\n```js\nconst Database = require(\"better-sqlite3\");\n```\n\n```js\npackagerConfig: {\n  asar: true,\n  executableName: \"babel-gate\",\n  extraResource: [\"./node_modules/better-sqlite3\"],\n  asarUnpack: [\"**/node_modules/better-sqlite3/**\"]\n}\n```\n\n```text\nbetter-sqlite3\n```\n\n```text\nforge.config.js\n```\n\n```text\npackage.json\n```\n\n```text\ndatabase.js\n```\n\n```text\nbetter-sqlite3\n```\n\n```text\nelectron-rebuild\n```\n\n```text\nasarUnpack\n```\n\n```text\nextraResource\n```\n\n```text\nbetter-sqlite3\n```\n\n```text\nforge.config.js\n```\n\n```text\nFuseV1Options.OnlyLoadAppFromAsar\n```\n\n```text\nfalse\n```\n\n```text\nPackaging for x64 on Linux\n```\n\n```js\nignore:[ /node_modules\\/(?!(better-sqlite3|bindings|file-uri-to-path)\\/)/, ],\n```\n\n```text\nforge.config.js\n```\n\n```text\nplugin-auto-unpack-natives\n```\n\n```text\nplugins\n```\n\n```text\nignore\n```\n\n```text\npackagerConfig\n```\n\n```text\nasar: {\n      unpack: \"*.{node,dll}\",\n    },\n    ignore: [/node_modules\\/(?!(better-sqlite3|bindings|file-uri-to-path)\\/)/],\n  },\n```\n\n========================================\n\nComments:\n- since this is (well) known issue with better-sqlite3 and electron,vite, why not just use sqlite3 and avoid the headeaches. BTW, if you think posting a link to your git repo will get you help you'll be disappointed - people are not here to run through reams of code , do all the legwork to build/test , read minimal reproducible example guidelines about posting - following those will get you much further.\n- @ticktalk Thanks for feedback. I did consider switching to sqlite3 and will most likely do just that. As for link to GitHub repo - I think you're right, it was unnecessary.\n- Well, hopefully you'll be able to progress , your experience back when able. good luck!\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:46.416Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":460,"estimatedTokens":3019}}298{"id":"stack-72723543","source":"stackoverflow","questionId":72723543,"title":"Vite Vue3 place multiple \".env\" files in a folder","tags":["vue.js","vuejs3","vite","dotenv"],"text":"Title: Vite Vue3 place multiple \".env\" files in a folder\nTags: vue.js, vuejs3, vite, dotenv\nSource: Stack Overflow\n\nQuestion:\nI have 11 .env files for testing and other reasons.\n\nIs there way I can put them in a folder and use them from there?\n\nSuch as:\n\n/root\n\nenv-container\n\n- .env-test1\n\n- .env-test2\n\n- .env-test3\n\n========================================\n\nCode:\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  envDir: './root/env-container',\n})\n```\n\n```text\n.env\n```\n\n```text\nenvDir\n```\n\n========================================\n\nComments:\n- You can just put them in the same folder. Whenever you want to use one, copy and paste the content of it to the `.env` file\n- @Duannx Thanks. I am using them all the time so I need to import them somehow.\n- You can also utilise the modes in which the servers run, such as `staging` or `production` by creating files such as `.env.staging`, `.env.production` to map to the modes automaticaaly.","metadata":{"transformedAt":"2026-08-18T18:33:46.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":47,"estimatedTokens":246}}299{"id":"stack-73815590","source":"stackoverflow","questionId":73815590,"title":"quasar vuejs amplify Error: 'request' is not exported by __vite-browser-external,","tags":["aws-sdk","aws-amplify","vite","quasar"],"text":"Title: quasar vuejs amplify Error: 'request' is not exported by __vite-browser-external,\nTags: aws-sdk, aws-amplify, vite, quasar\nSource: Stack Overflow\n\nQuestion:\n**Purpose**: Upload images from quasar project to aws amplify storage.\n\n**Installations** : aws-amplify library for quasar and vuejs.\n\n=> aws-amplify uses **@aws-sdk** for built in.\n\nOnce this code is added :\n\n`import { Amplify, Storage } from 'aws-amplify';`\n\n`Amplify.configure(config);`\n\nI try to build my project: quasar -m build pwa/android/ios throws this error :\n\n`'request' is not exported by __vite-browser-external, imported by node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js`\n\nI saw on github for @aws-sdk this is a common error with vite.\n\nI'm using quasar 2.6.0, aws-amplify 4.3.35\n\nAny suggestions or workaround ?\n\n========================================\n\nCode:\n```text\nimport { Amplify, Storage } from 'aws-amplify';\n```\n\n```text\nAmplify.configure(config);\n```\n\n```text\n'request' is not exported by __vite-browser-external, imported by node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js\n```\n\n```text\nextendViteConf(viteConf, { isClient, isServer }) {\n    Object.assign(viteConf.resolve.alias, {\n      './runtimeConfig': './runtimeConfig.browser',\n    });\n  },\n```\n\n========================================\n\nComments:\n- Not a 1:1 issue relation, but I found this when getting a different `aws-sdk` error ui.docs.amplify.aws/react/getting-started/troubleshooting#vi&zwnj;&#8203;te","metadata":{"transformedAt":"2026-08-18T18:33:46.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":54,"estimatedTokens":383}}300{"id":"stack-72384854","source":"stackoverflow","questionId":72384854,"title":"Detect HMR event with ViteJS React/SolidJS","tags":["reactjs","vite","webpack-hmr","solid-js"],"text":"Title: Detect HMR event with ViteJS React/SolidJS\nTags: reactjs, vite, webpack-hmr, solid-js\nSource: Stack Overflow\n\nQuestion:\nUsing ViteJS starter for React / SolidJS,\n\nHow can I detect (using some sort of js callback) before HMR reload is triggered by code changes? (to do some cleanup)\n\nTo be clear, I'm not asking how to use HMR, just how to do some cleanup before that happens.\n\nI have tried using `window.onbeforeunload` to no avail.\n\nThanks.\n\n========================================\n\nCode:\n```text\nwindow.onbeforeunload\n```\n\n```js\nif (import.meta.hot) {\n  import.meta.hot.accept((newModule) => {\n    console.log(`Receving new module...`, newModule);\n  });\n}\n```\n\n```js\nif (import.meta.hot) {\n  import.meta.hot.on('vite:beforeUpdate', () => {\n    console.log('Running before update!!');\n  });\n}\n```\n\n```js\n// sw.js\nself.addEventListener('fetch', function(event) {\n  console.log(event);\n});\n```\n\n```js\nnavigator.serviceWorker.register('/sw.js');\n```\n\n```text\nwindow.onbeforeunload\n```\n\n```text\naccept\n```\n\n========================================\n\nComments:\n- Have you tried `hot.on`?","metadata":{"transformedAt":"2026-08-18T18:33:46.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":61,"estimatedTokens":273}}301{"id":"stack-75921660","source":"stackoverflow","questionId":75921660,"title":"Vite react glob import not working on production build","tags":["reactjs","typescript","markdown","vite","rollup"],"text":"Title: Vite react glob import not working on production build\nTags: reactjs, typescript, markdown, vite, rollup\nSource: Stack Overflow\n\nQuestion:\nI am loading all markdown files within a directory using a glob import:\n\n```\nconst useGetChangelogs = () => {\n const [changelogs, setChangelogs] = useState([]);\n\n useEffect(() => {\n const arr: string[] = [];\n Promise.all(Object.keys(import.meta.glob(\"~/changelogs/*.md\")).sort((a, b) => b.localeCompare(a))\n .map(async (file) => fetch(file)\n .then((res) => res.text())\n .then((str) => arr.push(str))\n )\n ).then(() => setChangelogs(arr)).catch((err) => console.error(err));\n }, []);\n\n return changelogs;\n};\n```\n\nIt works perfectly when running a development build, but on production it displays the following:\n\n```\n Error Cannot GET /changelogs/v0.8.4-alpha.md \n```\n\nVite config:\n\n```\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport eslint from \"vite-plugin-eslint\";\nimport svgr from \"vite-plugin-svgr\";\nimport path from \"path\";\nimport autoprefixer from \"autoprefixer\";\n\nconst output = {\n manualChunks: (id: string) => {\n if (id.includes(\"node_modules\")) return id.toString().split(\"node_modules/\")[1].split(\"/\")[0].toString();\n }\n};\n\nexport default defineConfig({\n server: { host: \"0.0.0.0\", port: 3000 },\n resolve: { alias: { \"~\": path.resolve(__dirname, \"src\") } },\n css: { postcss: { plugins: [autoprefixer()] }, modules: { localsConvention: \"camelCase\" } },\n plugins: [react(), eslint(), svgr()],\n assetsInclude: [\"**/*.md\"],\n build: { rollupOptions: { output } }\n});\n```\n\nI tried adding the following to my rollupOptions as suggested from Vue + Vite + Rollup: Dynamic import not working on production build, but it did not seem to work\n\n```\nexport default defineConfig({\n build: {\n rollupOptions: {\n external: [\n \"/path/to/external/module.es.js\"\n ]\n }\n }\n})\n```\n\nAny help would be very much appreciated.\n\n========================================\n\nCode:\n```text\nconst useGetChangelogs = () => {\n  const [changelogs, setChangelogs] = useState<string[]>([]);\n\n  useEffect(() => {\n    const arr: string[] = [];\n    Promise.all(Object.keys(import.meta.glob(\"~/changelogs/*.md\")).sort((a, b) => b.localeCompare(a))\n      .map(async (file) => fetch(file)\n        .then((res) => res.text())\n        .then((str) => arr.push(str))\n      )\n    ).then(() => setChangelogs(arr)).catch((err) => console.error(err));\n  }, []);\n\n  return changelogs;\n};\n```\n\n```text\n<!DOCTYPE html> <html lang=\"en\"> <head> <meta charset=\"utf-8\"> <title>Error</title> </head> <body> <pre>Cannot GET /changelogs/v0.8.4-alpha.md</pre> </body> </html>\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport eslint from \"vite-plugin-eslint\";\nimport svgr from \"vite-plugin-svgr\";\nimport path from \"path\";\nimport autoprefixer from \"autoprefixer\";\n\nconst output = {\n  manualChunks: (id: string) => {\n    if (id.includes(\"node_modules\")) return id.toString().split(\"node_modules/\")[1].split(\"/\")[0].toString();\n  }\n};\n\nexport default defineConfig({\n  server: { host: \"0.0.0.0\", port: 3000 },\n  resolve: { alias: { \"~\": path.resolve(__dirname, \"src\") } },\n  css: { postcss: { plugins: [autoprefixer()] }, modules: { localsConvention: \"camelCase\" } },\n  plugins: [react(), eslint(), svgr()],\n  assetsInclude: [\"**/*.md\"],\n  build: { rollupOptions: { output } }\n});\n```\n\n```text\nexport default defineConfig({\n    build: {\n        rollupOptions: {\n            external: [\n                \"/path/to/external/module.es.js\"\n            ]\n        }\n    }\n})\n```\n\n```text\nconst changelogs = Object.values(import.meta.glob(\"~/changelogs/*.md\", { eager: true, as: \"raw\" }));\n```\n\n```text\nassetsInclude: [\"**/*.md\"]\n```\n\n========================================\n\nComments:\n- thats great for \"text\" files, but how about importing javascript classes or components?\n- @MladenOršolić The Vite docs will tell you vite.dev/guide/features.html#glob-import","metadata":{"transformedAt":"2026-08-18T18:33:46.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":147,"estimatedTokens":982}}302{"id":"stack-70883763","source":"stackoverflow","questionId":70883763,"title":"Vitejs is loading the whole bundle size instead of the selected ones","tags":["javascript","vue.js","vuejs3","vite"],"text":"Title: Vitejs is loading the whole bundle size instead of the selected ones\nTags: javascript, vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI am using vue 3 with vite. I noticed something strage. Oh vue icons is loading something like 108 MB of bundle size and it takes a lot of time to load even in vitejs.\nHere's my setup\n\n```\nimport { addIcons, OhVueIcon } from 'oh-vue-icons'\nimport {\n FaFacebookSquare,\n FaInstagram,\n FaLinkedin,\n FaQuora,\n FaTwitter,\n FaYoutube,\n} from 'oh-vue-icons/icons'\n\n// register the icons\naddIcons(\n FaFacebookSquare,\n FaInstagram,\n FaLinkedin,\n FaQuora,\n FaTwitter,\n FaYoutube\n)\n\nconst app = createApp(App)\napp.component('VIcon', OhVueIcon)\napp.mount('#app')\n```\n\nThen in my component:\n\n```\n\n```\n\nYou can see the problem below. I am conditionally controlling these six icons. That's why there are only one or two icons per card.\n\nWhy is it loading 108 MB of javascript? That doesn't make any sense. Also I am using vite with vue3. Do I need to add any extra configuration?\n\nThanks in Advance.\n\n========================================\n\nTop Answer:\nWhat partially helped was refactoring `import`ing code in the `main.ts` file.\n\nPreviously I had this:\n\n```\nimport {\n HiLocationMarker,\n BiBriefcase,\n OiX,\n BiCheckLg,\n FaComments,\n MdViewcarouselRound,\n MdAccountcircleRound,\n RiHeartFill\n} from \"oh-vue-icons/icons\";\n```\n\nNow I have this:\n\n```\nimport { HiLocationMarker } from 'oh-vue-icons/icons/hi';\nimport { BiBriefcase, BiCheckLg } from 'oh-vue-icons/icons/bi';\nimport { OiX } from 'oh-vue-icons/icons/oi';\nimport { FaComments } from 'oh-vue-icons/icons/fa';\nimport { MdViewcarouselRound, MdAccountcircleRound } from 'oh-vue-icons/icons/md';\nimport { RiHeartFill } from 'oh-vue-icons/icons/ri';\n```\n\nNow it loads only the specified `oh-vue-icons/icons/*` files, instead of loading the whole bundle.\n\nIt made a 10x improvement in loading time over the original, which is enough in my case.\n\n========================================\n\nCode:\n```text\nimport { addIcons, OhVueIcon } from 'oh-vue-icons'\nimport {\n  FaFacebookSquare,\n  FaInstagram,\n  FaLinkedin,\n  FaQuora,\n  FaTwitter,\n  FaYoutube,\n} from 'oh-vue-icons/icons'\n\n// register the icons\naddIcons(\n  FaFacebookSquare,\n  FaInstagram,\n  FaLinkedin,\n  FaQuora,\n  FaTwitter,\n  FaYoutube\n)\n\nconst app = createApp(App)\napp.component('VIcon', OhVueIcon)\napp.mount('#app')\n```\n\n```html\n<VIcon name=\"fa-facebook-square\" />\n<VIcon name=\"fa-youtube\" />\n<VIcon name=\"fa-instagram\" />\n<VIcon name=\"fa-quora\" />\n<VIcon name=\"fa-linkedin\" />\n<VIcon name=\"fa-twitter\" />\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  ⋮\n  optimizeDeps: {\n    exclude: ['oh-vue-icons/icons']\n  }\n})\n```\n\n```text\nlodash-es\n```\n\n```text\nimport { debounce } from 'lodash-es'\n```\n\n```text\nlodash-es\n```\n\n```text\noh-vue-icons/icons\n```\n\n```text\noptimizeDeps.exclude\n```\n\n```text\nimport {\n    HiLocationMarker,\n    BiBriefcase,\n    OiX,\n    BiCheckLg,\n    FaComments,\n    MdViewcarouselRound,\n    MdAccountcircleRound,\n    RiHeartFill\n} from \"oh-vue-icons/icons\";\n```\n\n```text\nimport { HiLocationMarker } from 'oh-vue-icons/icons/hi';\nimport { BiBriefcase, BiCheckLg } from 'oh-vue-icons/icons/bi';\nimport { OiX } from 'oh-vue-icons/icons/oi';\nimport { FaComments } from 'oh-vue-icons/icons/fa';\nimport { MdViewcarouselRound, MdAccountcircleRound } from 'oh-vue-icons/icons/md';\nimport { RiHeartFill } from 'oh-vue-icons/icons/ri';\n```\n\n```text\nimport\n```\n\n```text\nmain.ts\n```\n\n```text\noh-vue-icons/icons/*\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.416Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":184,"estimatedTokens":880}}303{"id":"stack-73041614","source":"stackoverflow","questionId":73041614,"title":"How to compile Cypress e2e tests/files using Vite?","tags":["vue.js","cypress","vite"],"text":"Title: How to compile Cypress e2e tests/files using Vite?\nTags: vue.js, cypress, vite\nSource: Stack Overflow\n\nQuestion:\nBy default, Cypress compiles e2e tests with a built-in webpack config, which used to be fine because Vue-CLI also used Webpack; however, now that I've upgraded to Vue 3 and Vite, no webpack.\n\nI have two options:\n\n- Revive the old webpack config for my Vue 2 project and update it for Vue 3 just to run Cypress' e2e tests.\n\n- Figure out how to tell Cypress to compile the app with Vite and not Webpack\n\nI can't figure out #2, and I don't want to do #1 because having two different compilation methods sounds like a really bad future headache.\n\nSo far, I have this for my Cypress config:\n\n```\nimport { devServer } from '@cypress/vite-dev-server'\nimport { defineConfig } from 'cypress'\nimport * as path from 'path'\n\nexport default defineConfig({\n chromeWebSecurity: false,\n projectId: '5kusbh',\n requestTimeout: 10000,\n responseTimeout: 60000,\n viewportHeight: 1080,\n viewportWidth: 1920,\n\n e2e: {\n baseUrl: 'http://localhost:8080',\n setupNodeEvents (on, config) {\n on('dev-server:start', (options) => {\n return devServer({\n ...options,\n viteConfig: {\n configFile: path.resolve(__dirname, 'vite.config.ts'),\n },\n })\n })\n\n return config\n },\n specPattern: 'cypress/e2e/**/**.spec.js',\n },\n})\n```\n\nHowever, when I run Cypress, I get a webpack compilation error, which is telling me Vite is not compiling the application for Cypress.\n\n**Note** Otherwise, my application is working great - I just can't run Cypress, and we have hundreds of unit, integration, and e2e tests written in Cypress.\n\n**TL;DR;** I need help configuring Cypress to use my app's Vite config to compile its e2e tests and run it's dev server.\n\n**EDIT:**\nI removed my config to see how it'd run just hitting localhost, but Cypress must be trying to compile my code, because it's struggling with the Vite env variable syntax, `import.meta.env.[insert key name here]` in non-Cypress JavaScript files because it's not `process.env`...\n\n========================================\n\nCode:\n```text\nimport { devServer } from '@cypress/vite-dev-server'\nimport { defineConfig } from 'cypress'\nimport * as path from 'path'\n\nexport default defineConfig({\n  chromeWebSecurity: false,\n  projectId: '5kusbh',\n  requestTimeout: 10000,\n  responseTimeout: 60000,\n  viewportHeight: 1080,\n  viewportWidth: 1920,\n\n  e2e: {\n    baseUrl: 'http://localhost:8080',\n    setupNodeEvents (on, config) {\n      on('dev-server:start', (options) => {\n        return devServer({\n          ...options,\n          viteConfig: {\n            configFile: path.resolve(__dirname, 'vite.config.ts'),\n          },\n        })\n      })\n\n      return config\n    },\n    specPattern: 'cypress/e2e/**/**.spec.js',\n  },\n})\n```\n\n```text\nimport.meta.env.[insert key name here]\n```\n\n```text\nprocess.env\n```\n\n```text\ncy.visit()\n```\n\n```text\n@cypress/vite-dev-server\n```\n\n========================================\n\nComments:\n- You don't need any compilation for e2e tests on Vue/Vite. Cypress just loads the page, it does not care how it is served. `@cypress&#47;vite-dev-server` was for component tests, now you don't even need it for that.\n- @SuchAnIgnorantThingToDo-UKR I'll remove some of the config and see how it goes... Maybe it's an issue with the local dev server and script I have for Cypress.","metadata":{"transformedAt":"2026-08-18T18:33:46.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":114,"estimatedTokens":833}}304{"id":"stack-75003997","source":"stackoverflow","questionId":75003997,"title":"How to copy files from node_modules with Vite / SvelteKit?","tags":["vite","sveltekit"],"text":"Title: How to copy files from node_modules with Vite / SvelteKit?\nTags: vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a node module dependency for theming content at `node_modules/foo-styles`.\n\nFor most css that I want to pull in, I can simply use an `import 'foo-styles/dist/controls/button.css'` in the page/component and vite does its magic, shoving the css where it fits best.\n\nFor theming however, I need to switch the included css variables file based on active theme in my `` , e.g. reference `foo-styles/dist/themes/{$theme}/color-variables.css` in the markup.\nTo do so, I assume that vite must copy those files from `node_modules/foo-styles` to my apps asset directory without import magic, renaming of files etc.\n\nI can only find examples for doing this with webpack or rollup using copy plugins ... is this something that vite can do out of the box? Is there a plugin available? How do you copy assets from node_module dependencies to the bundle?\n\n========================================\n\nCode:\n```text\nnode_modules/foo-styles\n```\n\n```text\nimport 'foo-styles/dist/controls/button.css'\n```\n\n```text\n<svelte:head>\n```\n\n```text\nfoo-styles/dist/themes/{$theme}/color-variables.css\n```\n\n```text\nnode_modules/foo-styles\n```\n\n```js\nimport themeUrl from 'some-module/css/theme.css?url'\n\nonMount(() => {\n    const link = document.createElement('link');\n    link.rel = 'stylesheet';\n    link.href = themeUrl;\n    document.head.appendChild(link);\n\n    return () => link.remove();\n});\n```\n\n```js\nconst styles = import.meta.glob(\n    '/node_modules/some-module/css/*.css',\n    { query: 'url', eager: true },\n);\n\nlet selectValue = 'some-theme';\n$: selectedStyle = `/node_modules/some-module/css/${selectedValue}.css`;\nlet link = null;\n\nonMount(() => {\n    link = document.createElement('link');\n    link.rel = 'stylesheet';\n    document.head.appendChild(link);\n\n    return () => link?.remove();\n});\n\n$: if (link) {\n    const { default: href } = styles[selectedStyle];\n    link.href = href;\n}\n```\n\n```html\n<script>\n    const styles = import.meta.glob(\n        '/node_modules/some-module/css/*.css',\n        { query: 'url', eager: true },\n    );\n    \n    let selectValue = 'some-theme';\n    $: href = styles[`/node_modules/some-module/css/${selectedValue}.css`].default;\n</script>\n\n<svelte:head>\n    <link rel=\"stylesheet\" {href} />\n</svelte:head>\n```\n\n```text\n?url\n```\n\n```text\nlink\n```\n\n```text\n<head>\n```\n\n```text\n/\n```\n\n```text\n./\n```\n\n```text\nsvelte:head\n```\n\n========================================\n\nComments:\n- Can you switch the whole file e.g. in the style of light theme and dark theme? Then it should be as easy as dynamically write `` tag in `` and make sure the relevant CSS files are in the static assets folder. Not sure if any plugin is needed.\n- Yes, that is exactly the approach I am taking. The challenging bit is making sure that \"the relevant CSS files are in the static assets folder\", since these files reside in node_modules. I have pretty much solved it now (thanks to a maintainer who helped out on their discord) and will post the answer shortly.","metadata":{"transformedAt":"2026-08-18T18:33:46.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":119,"estimatedTokens":771}}305{"id":"stack-75980211","source":"stackoverflow","questionId":75980211,"title":".env variables not being accessed in deployment in GitHub pages (Vite + react app)","tags":["github","vite","github-pages",".env"],"text":"Title: .env variables not being accessed in deployment in GitHub pages (Vite + react app)\nTags: github, vite, github-pages, .env\nSource: Stack Overflow\n\nQuestion:\nRepo:https://github.com/SyntaxWarrior30/Java-Docs-Generator\n\nI deployed the site as a gh-pages of the main branch using the dist folder.\n\nThe GitHub pages site doesn’t work since the API key, stored in the .env file, which was ignored with .gitignore, is not being accessed. I created a secret variable in my GitHub pages environment yet it is still not working. How do I add .env variables to my GitHub pages so my fetch function works properly.\n\nWhat my .env.production file looks like:\n\n```\nVITE_API_KEY={My API Key}\n```\n\nI tried adding a new repository secret by navigating to Settings > Secrets > New repository secret. Naming the secret the same as the variable name I defined in .env, without the `VITE_` prefix. However, this did not fix the problem.\n\nI also tried the solution where I include the `VITE_` prefix for the Secret variable name in Github.\n\nHere is the static.yml that i used to deploy the project, if needed:\n\n```\n# Simple workflow for deploying static content to GitHub Pages\nname: Deploy static content to Pages\n\non:\n # Runs on pushes targeting the default branch\n push:\n branches: ['main']\n\n # Allows you to run this workflow manually from the Actions tab\n workflow_dispatch:\n\n# Sets the GITHUB_TOKEN permissions to allow deployment to GitHub Pages\npermissions:\n contents: read\n pages: write\n id-token: write\n\n# Allow one concurrent deployment\nconcurrency:\n group: 'pages'\n cancel-in-progress: true\n\njobs:\n # Single deploy job since we're just deploying\n deploy:\n environment:\n name: github-pages\n url: ${{ steps.deployment.outputs.page_url }}\n runs-on: ubuntu-latest\n steps:\n - name: Checkout\n uses: actions/checkout@v3\n - name: Set up Node\n uses: actions/setup-node@v3\n with:\n node-version: 18\n cache: 'npm'\n - name: Install dependencies\n run: npm install\n - name: Setup Pages\n uses: actions/configure-pages@v3\n - name: Upload artifact\n uses: actions/upload-pages-artifact@v1\n with:\n # Upload dist repository\n path: './dist'\n - name: Deploy to GitHub Pages\n id: deployment\n uses: actions/deploy-pages@v1\n```\n\nEvidence of error:\n\n========================================\n\nTop Answer:\nVite needs to be built and deployed with `vite build` (or your package manager's equivalent). During `vite build`, the values are injected into the new code. They'd have to be since this is client code run on the browser. They can come from either `.env`, or a special `.env.production`, or environment variables. See .env files in the Vite docs and Deploying For Production.\n\nMake sure this is done before deploying to Github.\n\nIf you want to build and deploy with Github actions, see vite-deploy-demo and the Vite docs for Github Pages.\n\nYour VITE values must be available as environment variables during the `vite build` step.\n\n- Add your production VITE values as Github Secrets.\n\n- Make them available to the build step.\n\n```\n- name: Build project\n run: vite build\n env:\n VITE_API_KEY: ${{ secrets.VITE_API_KEY }}\n```\n\n========================================\n\nCode:\n```text\nVITE_API_KEY={My API Key}\n```\n\n```text\n# Simple workflow for deploying static content to GitHub Pages\nname: Deploy static content to Pages\n\non:\n  # Runs on pushes targeting the default branch\n  push:\n    branches: ['main']\n\n  # Allows you to run this workflow manually from the Actions tab\n  workflow_dispatch:\n\n# Sets the GITHUB_TOKEN permissions to allow deployment to GitHub Pages\npermissions:\n  contents: read\n  pages: write\n  id-token: write\n\n# Allow one concurrent deployment\nconcurrency:\n  group: 'pages'\n  cancel-in-progress: true\n\njobs:\n  # Single deploy job since we're just deploying\n  deploy:\n    environment:\n      name: github-pages\n      url: ${{ steps.deployment.outputs.page_url }}\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v3\n      - name: Set up Node\n        uses: actions/setup-node@v3\n        with:\n          node-version: 18\n          cache: 'npm'\n      - name: Install dependencies\n        run: npm install\n      - name: Setup Pages\n        uses: actions/configure-pages@v3\n      - name: Upload artifact\n        uses: actions/upload-pages-artifact@v1\n        with:\n          # Upload dist repository\n          path: './dist'\n      - name: Deploy to GitHub Pages\n        id: deployment\n        uses: actions/deploy-pages@v1\n```\n\n```text\nVITE_\n```\n\n```text\nVITE_\n```\n\n```text\n# Simple workflow for deploying static content to GitHub Pages\nname: Deploy static content to Pages\n\non:\n  # Runs on pushes targeting the default branch\n  push:\n    branches: ['main']\n\n  # Allows you to run this workflow manually from the Actions tab\n  workflow_dispatch:\n\n# Sets the GITHUB_TOKEN permissions to allow deployment to GitHub Pages\npermissions:\n  contents: read\n  pages: write\n  id-token: write\n\n# Allow one concurrent deployment\nconcurrency:\n  group: 'pages'\n  cancel-in-progress: true\n\njobs:\n  # Single deploy job since we're just deploying\n  deploy:\n    environment:\n      name: github-pages\n      url: ${{ steps.deployment.outputs.page_url }}\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v3\n      - name: Set up Node\n        uses: actions/setup-node@v3\n        with:\n          node-version: 18\n          cache: 'npm'\n      - name: Install dependencies\n        run: npm install\n      - name: Build\n        run: npm run build\n        env:\n          VITE_API_KEY: ${{ secrets.VITE_API_KEY }}\n      - name: Setup Pages\n        uses: actions/configure-pages@v3\n      - name: Upload artifact\n        uses: actions/upload-pages-artifact@v1\n        with:\n          # Upload dist repository\n          path: './dist'\n      - name: Deploy to GitHub Pages\n        id: deployment\n        uses: actions/deploy-pages@v1\n```\n\n```text\n- name: Build project\n        run: vite build\n        env:\n          VITE_API_KEY: ${{ secrets.VITE_API_KEY }}\n```\n\n```text\nvite build\n```\n\n```text\nvite build\n```\n\n```text\n.env\n```\n\n```text\n.env.production\n```\n\n```text\nvite build\n```\n\n```yaml\n- name: Build project\n    run: npm run build\n    env:\n      REACT_APP_FIREBASE_API_KEY: ${{ secrets.REACT_APP_FIREBASE_API_KEY }}\n```\n\n```yaml\nname: Deploy to GitHub Pages\non:\n  push:\n    branches:\n      - main\n  workflow_dispatch:\npermissions:\n  contents: read\n  pages: write\n  id-token: write\nconcurrency:\n  group: \"pages\"\n  cancel-in-progress: false\njobs:\n  build:\n    environment:\n        name: github-pages\n        url: ${{ steps.deployment.outputs.page_url }}\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout Repository\n        uses: actions/checkout@v4\n      - name: Setup Node\n        uses: actions/setup-node@v4\n        with:\n          node-version: \"21\"\n          cache: 'npm'\n      - name: Install dependencies\n        run: npm install\n      - name: Build project\n        run: npm run build\n        env:\n          REACT_APP_FIREBASE_API_KEY: ${{ secrets.REACT_APP_FIREBASE_API_KEY }}\n      - name: Setup Pages\n        uses: actions/configure-pages@v3\n      - name: Upload artifact\n        uses: actions/upload-pages-artifact@v2\n        with:\n          path: ./build\n      - name: Deploy to GitHub Pages\n        id: deployment\n        uses: actions/deploy-pages@v3\n```\n\n```text\nname: Deploy to GitHub Pages\non:\n  push:\n    branches:\n      - main\n  workflow_dispatch:\npermissions:\n  contents: read\n  pages: write\n  id-token: write\nconcurrency:\n  group: \"pages\"\n  cancel-in-progress: false\njobs:\n  build:\n    environment:\n        name: github-pages\n        url: ${{ steps.deployment.outputs.page_url }}\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout Repository\n        uses: actions/checkout@v4\n      - name: Setup Node\n        uses: actions/setup-node@v4\n        with:\n          node-version: \"21\"\n          cache: 'npm'\n      - name: Install dependencies\n        run: npm install\n      - name: Build project\n        run: npm run build\n        env:\n          VITE_SOME_API_KEY: ${{ secrets.VITE_SOME_API_KEY }}\n      - name: Setup Pages\n        uses: actions/configure-pages@v4\n      - name: Upload artifact\n        uses: actions/upload-pages-artifact@v3\n        with:\n          path: ./dist\n      - name: Deploy to GitHub Pages\n        id: deployment\n        uses: actions/deploy-pages@v4\n```\n\n========================================\n\nComments:\n- Github Secrets and .env both present values to your app as environment variables. If your app is looking for VITE_API_KEY then use VITE_API_KEY in both Github Secrets and .env.\n- @Schwern I tried that but it still dosen't work, any other ideas? Right now, my Secret variable name is VITE_API_KEY, along with its corresponding api key.\n- @Schwern I have updated the question with new information, if needed.\n- How did you build it?\n- Note that \"subtree\" has a special meaning in Git. Did you mean the \"gh-pages\" branch?\n- yes, i used gh-pages\n- You're passing the env to the checkout step which doesn't use it. Pass it to the build step.\n- @Schwern I updated the .yml file, it still doesn’t work. I don't know what seems to be the problem. Should I try to host the site on a diffrent platform but keep the source code in github?\n- There's nothing wrong with GitHub for this. Your build step no longer does anything, the build command is missing. Your build step needs to run the build command with the env set, like in my answer. I would recommend getting it working on the command line before trying to implement it in an action.\n- @Schwern Sorry, but I don't know what you mean by getting it working in command line. My program is working when I run \"npm run build\" & \"npm run preview\" in VS code.\n- Never mind, I got it to work by updating the static.yml. I updated the question's .yml file to what worked for me. Thank you for your help.\n- @GiridharNair I'm glad you got it working. For the future, don't update the question with what worked. Then the discussion and answers don't make any sense. Instead, if you're not satisfied with the existing answers, self-answer like you did.\n- @Schwern I realized my mistake in putting the answer in the question itself, i reverted it back to the original post. Thanks for the help.\n- When you mean by the build step, you mean when I create a .yml file for deployment in workflows?\n- @GiridharNair I mean `vite build`. Doesn't matter if it's in a Github Action or manually on the command line.\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. **Would you kindly edit your answer to include additional details for the benefit of the community?**","metadata":{"transformedAt":"2026-08-18T18:33:46.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":366,"estimatedTokens":2782}}306{"id":"stack-74469661","source":"stackoverflow","questionId":74469661,"title":"SvelteKit PageLoad module not found","tags":["typescript","svelte","vite","sveltekit"],"text":"Title: SvelteKit PageLoad module not found\nTags: typescript, svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a SvelteKit project and for some reason, `./$types` doesn't have the module PageLoad (which other projects do. I'm not sure what I did/didn't do to not have it. This is the error I'm getting:\n\n```\nModule '\"./$types\"' has no exported member 'PageLoad'.ts(2305)\n```\n\nThis is how I'm using it (for testing):\n\n```\nimport { error } from '@sveltejs/kit';\nimport type { PageLoad } from './$types';\n\nexport const load: PageLoad = async ({ params, fetch }) => {\n console.log('props from +page.ts: ', params.db_item)\n // We fetch the post here using a Worker/Lambda\n return params.db_item\n}\n```\n\nHere is my package.json file:\n\n```\n{\n \"name\": \"test\",\n \"version\": \"0.0.1\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"vite dev\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\",\n \"test\": \"playwright test\",\n \"check\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json\",\n \"check:watch\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch\",\n \"lint\": \"prettier --check .\",\n \"format\": \"prettier --write .\",\n \"surge deploy\": \"rollup -c; surge public\"\n },\n \"devDependencies\": {\n \"@playwright/test\": \"^1.25.0\",\n \"@sveltejs/adapter-auto\": \"next\",\n \"@sveltejs/kit\": \"next\",\n \"node-sass\": \"^7.0.3\",\n \"prettier\": \"^2.6.2\",\n \"prettier-plugin-svelte\": \"^2.7.0\",\n \"svelte\": \"^3.44.0\",\n \"svelte-check\": \"^2.7.1\",\n \"svelte-preprocess\": \"^4.10.6\",\n \"tslib\": \"^2.3.1\",\n \"typescript\": \"^4.7.4\",\n \"vite\": \"^3.1.0\"\n },\n \"type\": \"module\",\n \"dependencies\": {\n \"svelte--buttons-component\": \"^1.5.0\"\n }\n}\n```\n\nHere is my svelte.config file:\n\n```\nimport adapter from '@sveltejs/adapter-cloudflare';\nimport preprocess from 'svelte-preprocess';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: preprocess(),\n\n kit: {\n adapter: adapter()\n }\n};\n\nexport default config;\n```\n\n========================================\n\nTop Answer:\nPer the Svelte Blog: Zero-effort type safety\n\nSvelteKit creates a hidden file `$types.d.ts` in every route directory. This file contains route specific types. Because of this, it's no longer even necessary to annotate Svelte-specific file exports (`+page`, `+layout`, `+server`, `hooks`, `params`, etc.).\n\nHowever, when the name of a `.ts/.js` file in a particular route changes, the route's `$types.d.ts` file may loose integrity.\n\nYou can fix the problem by restarting the Svelte language server.\n\nIn VSCode:\n\n- `ctrl+p`\n\n- Enter `>`\n\n- Select \"Svelte: Restart Language Server\"\n\n========================================\n\nCode:\n```text\nModule '\"./$types\"' has no exported member 'PageLoad'.ts(2305)\n```\n\n```text\nimport { error } from '@sveltejs/kit';\nimport type { PageLoad } from './$types';\n\nexport const load: PageLoad = async ({ params, fetch }) => {\n  console.log('props from +page.ts: ', params.db_item)\n  // We fetch the post here using a Worker/Lambda\n  return params.db_item\n}\n```\n\n```text\n{\n    \"name\": \"test\",\n    \"version\": \"0.0.1\",\n    \"private\": true,\n    \"scripts\": {\n        \"dev\": \"vite dev\",\n        \"build\": \"vite build\",\n        \"preview\": \"vite preview\",\n        \"test\": \"playwright test\",\n        \"check\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json\",\n        \"check:watch\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch\",\n        \"lint\": \"prettier --check .\",\n        \"format\": \"prettier --write .\",\n        \"surge deploy\": \"rollup -c; surge public\"\n    },\n    \"devDependencies\": {\n        \"@playwright/test\": \"^1.25.0\",\n        \"@sveltejs/adapter-auto\": \"next\",\n        \"@sveltejs/kit\": \"next\",\n        \"node-sass\": \"^7.0.3\",\n        \"prettier\": \"^2.6.2\",\n        \"prettier-plugin-svelte\": \"^2.7.0\",\n        \"svelte\": \"^3.44.0\",\n        \"svelte-check\": \"^2.7.1\",\n        \"svelte-preprocess\": \"^4.10.6\",\n        \"tslib\": \"^2.3.1\",\n        \"typescript\": \"^4.7.4\",\n        \"vite\": \"^3.1.0\"\n    },\n    \"type\": \"module\",\n    \"dependencies\": {\n        \"svelte-share-buttons-component\": \"^1.5.0\"\n    }\n}\n```\n\n```text\nimport adapter from '@sveltejs/adapter-cloudflare';\nimport preprocess from 'svelte-preprocess';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n    // Consult https://github.com/sveltejs/svelte-preprocess\n    // for more information about preprocessors\n    preprocess: preprocess(),\n\n    kit: {\n        adapter: adapter()\n    }\n};\n\nexport default config;\n```\n\n```text\n./$types\n```\n\n```text\n+page.js\n```\n\n```text\n.ts\n```\n\n```text\n$types\n```\n\n```text\n$types.d.ts\n```\n\n```text\n+page\n```\n\n```text\n+layout\n```\n\n```text\n+server\n```\n\n```text\nhooks\n```\n\n```text\nparams\n```\n\n```text\n.ts/.js\n```\n\n```text\n$types.d.ts\n```\n\n```text\nctrl+p\n```\n\n```text\n>\n```\n\n```text\n$types.d.ts\n```\n\n```js\nmodule.exports = {\n    // ...\n    extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'prettier'],\n    plugins: ['svelte3', '@typescript-eslint'],\n    ignorePatterns: ['*.cjs'],\n    overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }],\n    settings: {\n        'svelte3/typescript': () => require('typescript'),\n    },\n    // ...\n}\n```\n\n```js\nmodule.exports = {\n    root: true,\n    extends: [\n        'eslint:recommended',\n        'plugin:@typescript-eslint/recommended',\n        'plugin:svelte/recommended',\n        'prettier',\n    ],\n    parser: '@typescript-eslint/parser',\n    plugins: ['@typescript-eslint'],\n    parserOptions: {\n        sourceType: 'module',\n        ecmaVersion: 2020,\n        extraFileExtensions: ['.svelte'],\n    },\n    env: {\n        browser: true,\n        es2017: true,\n        node: true,\n    },\n    overrides: [\n        {\n            files: ['*.svelte'],\n            parser: 'svelte-eslint-parser',\n            parserOptions: {\n                parser: '@typescript-eslint/parser',\n            },\n        },\n    ],\n};\n```\n\n```text\n.eslintrc.cjs\n```\n\n```text\nsvelte3\n```\n\n```text\n.eslintrc.js\n```\n\n```text\nnpm create svelte@latest my-app\n```\n\n```text\n.svelte-kit\n```\n\n```text\nnpx svelte-kit sync\n```\n\n========================================\n\nComments:\n- Does this answer your question? SvelteKit, import type LayoutServerLoad/PageLoad\n- You should tell the sveltekit team about this. Thanks for the finding.\n- I did. That's where I found the fix. :)\n- For future googlers, I just found out that I was trying to call `PageLoad` inside a `+layout.ts` file, which is a wrong thing to do. We can only call `PageLoad` if we have a `+page.ts` and `ServerLoad` for `+layout.ts`.\n- @JoelHager - would you mind linking to the GitHub issue or wherever else you found the fix? I have been looking for it but unable to find it\n- There wasn't a specific 'fix' for it. It's some common knowledge thing about how Svelte builds types. You either have to force a type rebuild (I think npm run check would do it) but I ended up deleting the file after copying, and just creating a new file with the .ts extension. I wish I could be of more help. :/\n- I tried restarting the language server, and it did not work for me. I had to delete the file and create it under .ts extension rather than rename it from .js to .ts. Maybe it was a one-off bug, but recreating the file is what fixed it for me.\n- `Yup, that was it!","metadata":{"transformedAt":"2026-08-18T18:33:46.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":317,"estimatedTokens":1823}}307{"id":"stack-75451487","source":"stackoverflow","questionId":75451487,"title":"How do I use Vite with Yarn Workspaces?","tags":["vite","yarn-workspaces","yarnpkg-v2"],"text":"Title: How do I use Vite with Yarn Workspaces?\nTags: vite, yarn-workspaces, yarnpkg-v2\nSource: Stack Overflow\n\nQuestion:\nAt my workplace we were trying to get Vite working with Yarn Workspaces (in yarn v2).\n\nWe wanted to create a test environment where we consumed one of the packages we were publishing from the same repository but a different workspace. To illustrate:\n\n```\npackages\n package-a\n package-b\n```\n\nThe packages are referred to in the main `package.json` like so:\n\n```\n{\n ...\n \"workspaces\" : [\n \"packages/package-a\",\n \"packages/package-b\"\n ]\n ...\n \"packageManager\": \"yarn@3.3.1\"\n}\n```\n\nWhere `package-b` refers to `package-a` in `package-b`'s `package.json` like so:\n\n```\n{\n ...\n \"dependencies\" : {\n ...\n \"package-a-name-in-npm\": \"workspace:packages/package-a\"\n ...\n }\n ...\n}\n```\n\nWhat we found though, was that when it came to running the application in Vite, the **package was not being loaded into the browser**. This resulted in errors like:\n\n```\nUncaught SyntaxError: The requested module ... does not provide an export named ...\n```\n\nAt runtime only, but TypeScript and ESLint were perfectly happy with our imports.\n\nSee my answer below to find out our solution.\n\n========================================\n\nCode:\n```text\npackages\n   package-a\n   package-b\n```\n\n```json\n{\n  ...\n  \"workspaces\" : [\n    \"packages/package-a\",\n    \"packages/package-b\"\n  ]\n  ...\n  \"packageManager\": \"yarn@3.3.1\"\n}\n```\n\n```json\n{\n  ...\n  \"dependencies\" : {\n    ...\n    \"package-a-name-in-npm\": \"workspace:packages/package-a\"\n    ...\n  }\n  ...\n}\n```\n\n```text\nUncaught SyntaxError: The requested module ... does not provide an export named ...\n```\n\n```text\npackage.json\n```\n\n```text\npackage-b\n```\n\n```text\npackage-a\n```\n\n```text\npackage-b\n```\n\n```text\npackage.json\n```\n\n```typescript\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  resolve: {\n    preserveSymlinks: true // this is the fix!\n  }\n});\n```\n\n```text\nvite.config.ts\n```\n\n========================================\n\nComments:\n- Setting this option will prevent vite from being able to load hoisted packages from node_modules (in parent folders). It will break your entire app. How can this be a fix?\n- @bennidi are you speculating or has this broken things for you? Because for us this solution has worked without issue and we have node modules folders at multiple levels.\n- It broke my project entirely. was having issues with unresolved dependencies that just went away after removing this setting. What OS are you on? I use MacOS.\n- We use all of them. I use Windows, tow of my colleagues use MacOS and we build these projects in Docker containers (so Linux). All of them work without issue. Well, none related to this anyway.\n- I am running out of ideas then. I tried removing my downvote but can not. Sorry.\n- No worries mate. Best of luck with your technical issues.\n- Although this does make vite able to find the local package, I'm still running into issues when updating my local dependencies. These are not picked up by vite.\n- @wvdz If you are using typescript, make sure that the changes to your local dependency are being recompiled as you make them. One way to do this is to run `tsc --watch` instead of just `tsc` in your dependency when in development.\n- Yes, I have this running, but the changes don't get picked up, only after I restart with `yarn dev --force`\n- Thank you @wvdz ! I'm also having this issue. Clearing `node_modules` also \"works\".\n- @HendyIrawan I solved this by moving to pnpm workspaces. Works like a charm. You don't even need to compile your typescript packages.","metadata":{"transformedAt":"2026-08-18T18:33:46.417Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":141,"estimatedTokens":917}}308{"id":"stack-68975837","source":"stackoverflow","questionId":68975837,"title":"Web3js fails to import in Vue3 composition api project","tags":["vue.js","vuejs3","web3js","vite"],"text":"Title: Web3js fails to import in Vue3 composition api project\nTags: vue.js, vuejs3, web3js, vite\nSource: Stack Overflow\n\nQuestion:\nI've created a brand new project with `npm init vite bar -- --template vue`. I've done an `npm install web3` and I can see my `package-lock.json` includes this package. My `node_modules` directory also includes the `web3` modules.\n\nSo then I added this line to `main.js`:\n\n```\nimport { createApp } from 'vue'\nimport App from './App.vue'\nimport Web3 from 'web3' And I get the following error:\nhttps://i.sstatic.net/pD1wI.png\n\nI don't understand what is going on here. I'm fairly new to using `npm` so I'm not super sure what to Google. The errors are coming from `node_modules/web3/lib/index.js`, `node_modules/web3-core/lib/index.js`, `node_modules/web3-core-requestmanager/lib/index.js`, and finally `node_modules/util/util.js`. I suspect it has to do with one of these:\n\n- I'm using Vue 3\n\n- I'm using Vue 3 Composition API\n\n- I'm using Vue 3 Composition API SFC `` tag (but I imported it in `main.js` so I don't think it is this one)\n\n- `web3js` is in Typescript and my Vue3 project is not configured for Typescript\n\nBut as I am fairly new to JavaScript and Vue and Web3 I am not sure how to focus my Googling on this error. My background is Python, Go, Terraform. Basically the back end of the back end. Front end JavaScript is new to me.\n\n**How do I go about resolving this issue?**\n\n========================================\n\nTop Answer:\nYou can avoid the `Uncaught ReferenceError: process is not defined` error by adding this in your vite config\n\n```\nexport default defineConfig({\n // ...\n define: {\n 'process.env': process.env\n }\n})\n```\n\n========================================\n\nCode:\n```js\nimport { createApp } from 'vue'\nimport App from './App.vue'\nimport Web3 from 'web3'   <-- This line\n\n\ncreateApp(App).mount('#app')\n```\n\n```text\nnpm init vite bar -- --template vue\n```\n\n```text\nnpm install web3\n```\n\n```text\npackage-lock.json\n```\n\n```text\nnode_modules\n```\n\n```text\nweb3\n```\n\n```text\nmain.js\n```\n\n```text\nnpm\n```\n\n```text\nnode_modules/web3/lib/index.js\n```\n\n```text\nnode_modules/web3-core/lib/index.js\n```\n\n```text\nnode_modules/web3-core-requestmanager/lib/index.js\n```\n\n```text\nnode_modules/util/util.js\n```\n\n```text\n<script setup>\n```\n\n```text\nmain.js\n```\n\n```text\nweb3js\n```\n\n```bash\nnpm i -D @esbuild-plugins/node-globals-polyfill\nnpm i -D @esbuild-plugins/node-modules-polyfill\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport GlobalsPolyfills from '@esbuild-plugins/node-globals-polyfill'\nimport NodeModulesPolyfills from '@esbuild-plugins/node-modules-polyfill'\n\nexport default defineConfig({\n  ⋮\n  optimizeDeps: {\n    esbuildOptions: {\n      2️⃣\n      plugins: [\n        NodeModulesPolyfills(),\n        GlobalsPolyfills({\n          process: true,\n          buffer: true,\n        }),\n      ],\n      3️⃣\n      define: {\n        global: 'globalThis',\n      },\n    },\n  },\n})\n```\n\n```js\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  ⋮\n  resolve: {\n    alias: {\n      web3: 'web3/dist/web3.min.js',\n    },\n\n    // or\n    alias: [\n      {\n        find: 'web3',\n        replacement: 'web3/dist/web3.min.js',\n      },\n    ],\n  },\n})\n```\n\n```text\nweb3\n```\n\n```text\noptimizeDeps.esbuildOptions\n```\n\n```text\ndefine\n```\n\n```text\nglobal\n```\n\n```text\nglobalThis\n```\n\n```text\nweb3\n```\n\n```text\nweb3/dist/web3.min.js\n```\n\n```text\nresolve.alias\n```\n\n```js\nexport default defineConfig({\n  // ...\n  define: {\n    'process.env': process.env\n  }\n})\n```\n\n```text\nUncaught ReferenceError: process is not defined\n```\n\n```text\nwindow.process = {\n  ...window.process,\n};\n```\n\n```text\nwindow.process\n```\n\n========================================\n\nComments:\n- Wow ok, so I found this comment: github.com/vitejs/vite/issues/1973#issuecomment-787571499\n- But then I get `Uncaught ReferenceError: global is not defined` with a similar chain of errors...\n- You saved my day here! I went with option 1 and it works like a charm. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:46.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":224,"estimatedTokens":997}}309{"id":"stack-77647463","source":"stackoverflow","questionId":77647463,"title":"SvelteKit WebApp to PWA (Progressive Web App), How to do it in the most simple way possible?","tags":["progressive-web-apps","vite","sveltekit"],"text":"Title: SvelteKit WebApp to PWA (Progressive Web App), How to do it in the most simple way possible?\nTags: progressive-web-apps, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\n**Introduction**:\n\nI am developing a webapp using the `SvelteKit` framework,\n\nI implemented some basic functionality for making accessible even to mobile devices:\n\n- I made it responsive\n\n- implemented light/dark themes\n\n- refactored the code\n\nSo basically I think I have a ready-to-use website\n\nthat can easily be usable on mobile devices.\n\n**What I want?**:\n\nI want that my website to be downloaded as a apk\n\nto make it working also Offline\n\nand hopefully even be publishable on Google Play Store.\n\n**My research**:\n\nI did some research before asking,\n\nand I found that we can use a concept called `PWA`, a acronym for Progressive Web App.\n\n**What is the problem?**\n\nIt's seems easy, but in reality,\n\nIt turn out to be very difficult to implement using framework like 'SvelteKit'\n\n**Question?**:\n\nIs there any simpler way than these before,\n\nto transform a vite sveltekit webapp to a PWA?\n\nI want also to be simple because I want to\n\nfocus more on Business/App logic than implementing PWA logic.\n\n**What things, the answer should solve?**\n\n- No need to recreate the app from scratch, using native technologies\n\n- No need to complex the code using new components, beside the DOM original ones (NO Condova/Capacitor Approach)\n\n- One source code for Android and IOS\n\n- Offline / Caching Ability\n\n- Download Ability\n\n- easy to implement on new, and even on more old/complex projects.\n\n- it should work with SvelteKit/ViteJS (even with TypeScript and Libraries such as TailwindCSS)\n\n- No need to disactivate SSR.\n\n- The configuration should be done one time, or the least times possible.\n\n**What I tried, if interest you but these are failed tryies** *(you can skip this part)*:\n\n - First and obvious way, code it by yourself from scratch everytime \nbut 'SvelteKit' has a lot of scenarios that you need to consider since it leverage 'SSR'. \nBut as you know is time consuming \nto focus on making PWA functionality to work \nthan using that time to make the app even more better or solving some bugs. \n\n - use a PWA library called Workbox create by Google itself, \nhere their github https://github.com/GoogleChrome/workbox \nand even with this library this process is still difficult, especially using SvelteKit framework. \n\n - using a PWA library, based on top of Workbox, called Vite PWA. \nThe landing page of this library use as marketing phrase \"*Zero-config and framework-agnostic PWA Plugin for Vite*\". \nTheoretically, it should be true, At the start seems to do his job, \nbut in my experience it contains some bugs that you definitely doesn't want to deal with... \nfor example one of them is this: https://github.com/vite-pwa/vite-plugin-pwa/issues/40 \nIt creates bugs that don't make sense, basically making your app over-complex for nothing. \n\n - and much more...\n\nall of these are failed examples,\n\nI hope you will find a better way than these\n\n========================================\n\nCode:\n```text\nSvelteKit\n```\n\n```text\nPWA\n```\n\n```js\n/// <reference types=\"@sveltejs/kit\" />\n\n// @ts-nocheck\nimport { build, files, version } from '$service-worker';\n\n// Create a unique cache name for this deployment\nconst CACHE = `cache-${version}`;\n\nconst ASSETS = [\n    ...build, // the app itself\n    ...files  // everything in `static`\n];\n\nself.addEventListener('install', (event) => {\n    // Create a new cache and add all files to it\n    async function addFilesToCache() {\n        const cache = await caches.open(CACHE);\n        await cache.addAll(ASSETS);\n    }\n\n    event.waitUntil(addFilesToCache());\n});\n\nself.addEventListener('activate', (event) => {\n    // Remove previous cached data from disk\n    async function deleteOldCaches() {\n        for (const key of await caches.keys()) {\n            if (key !== CACHE) await caches.delete(key);\n        }\n    }\n\n    event.waitUntil(deleteOldCaches());\n});\n\nself.addEventListener('fetch', (event) => {\n    // ignore POST requests etc\n    if (event.request.method !== 'GET') return;\n\n    async function respond() {\n        const url = new URL(event.request.url);\n        const cache = await caches.open(CACHE);\n\n        // `build`/`files` can always be served from the cache\n        if (ASSETS.includes(url.pathname)) {\n            return cache.match(url.pathname);\n        }\n\n        // for everything else, try the network first, but\n        // fall back to the cache if we're offline\n        try {\n            const response = await fetch(event.request);\n\n            if (response.status === 200) {\n                cache.put(event.request, response.clone());\n            }\n\n            return response;\n        } catch {\n            return cache.match(event.request);\n        }\n    }\n\n    event.respondWith(respond());\n});\n```\n\n```json\n{\n  \"name\": \"APP NAME\",\n  \"description\": \"YOUR DESCRIPTION\",\n  \"display\": \"standalone\",\n  \"start_url\": \"/\",\n  \"icons\": [\n    {\n      \"src\": \"icons/myIcon512.png\",\n      \"sizes\": \"512x512\",\n      \"type\": \"image/png\",\n      \"purpose\": \"any maskable\"\n    }\n  ]\n}\n```\n\n```html\n<link rel=\"manifest\" href=\"/manifest.json\">\n```\n\n```text\nservice-worker\n```\n\n```text\n/src\n```\n\n```text\n/service-worker\n```\n\n```text\nindex.ts\n```\n\n```text\nindex.js\n```\n\n```text\nmanifest.json\n```\n\n```text\nstatic\n```\n\n```text\nicons\n```\n\n```text\nname\n```\n\n```text\n\"display\": \"standalone\"\n```\n\n```text\nmanifest.json\n```\n\n```text\napp.html\n```\n\n========================================\n\nComments:\n- Why don't you take the `prerended` page to put them in the cache like below? `js import { build, files, prerendered, version } from '$service-worker'; const ASSETS = [ ...build, &#47;&#47; the app itself ...files, &#47;&#47; everything in `static` ...prerendered &#47;&#47; prerendered pages ];`\n- That is a very nice suggestion, thanks. however, to simplify it, I don't want to change the available code here because I got this code here: kit.svelte.dev/docs/service-workers#inside-the-service-worke&zwnj;&#8203;r . thanks! @Big_Boulard\n- apple devices want a link rel for pwa in the html file. just store the image in your static folder and use this in your main html file","metadata":{"transformedAt":"2026-08-18T18:33:46.417Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":249,"estimatedTokens":1551}}310{"id":"stack-75346495","source":"stackoverflow","questionId":75346495,"title":"Error in vite@4.x + ant@3.x + react@16 : Unknown theme type: undefined, name: undefined","tags":["reactjs","antd","vite"],"text":"Title: Error in vite@4.x + ant@3.x + react@16 : Unknown theme type: undefined, name: undefined\nTags: reactjs, antd, vite\nSource: Stack Overflow\n\nQuestion:\nI am trying to migrate an old project into vite and I'm very close to success. There is just one bug which occurs in one of the javascript files of ant design when I deploy the app on server.\n\nbug.\n\nThis is happening in the following function exported by antd@3.x\n\n```\nexport function withSuffix(name, theme) {\n switch (theme) {\n case \"fill\":\n return name + \"-fill\";\n case \"outline\":\n return name + \"-o\";\n case \"twotone\":\n return name + \"-twotone\";\n default:\n throw new TypeError(\"Unknown theme type: \" + theme + \", name: \" + name);\n }\n}\n```\n\n```\nicons.forEach(function (icon) {\n _this2.definitions.set(withSuffix(icon.name, icon.theme), icon);\n});\n```\n\nI think this forEach loop is running on an array of undefined ([undefined, undefined..]) but I can't figure out why. I suspect it is due to some configuration I'm missing in my vite file or some other configuration.\n\nIf I change the code to this,\n\n```\nexport function withSuffix(name, theme) {\n switch (theme) {\n case \"fill\":\n return name + \"-fill\";\n default:\n case \"outline\":\n return name + \"-o\";\n case \"twotone\":\n return name + \"-twotone\";\n }\n}\n```\n\nMy project runs perfectly on local as well as on server. Here are my package.json and vite.config.ts\n\n```\n`{\n \"name\": \"ta\",\n \"private\": true,\n \"version\": \"0.0.0\",\n \"type\": \"module\",\n \"scripts\": {\n \"start\": \"vite --mode local\",\n \"start:dev\": \"vite --mode local-development\",\n \"start:qa\": \"vite --mode local-qa\",\n \"build:dev\": \"tsc && vite build --base=/ta-admin --mode development\",\n \"build:qa\": \"tsc && vite build --base=/ta-admin --mode qa\",\n \"build:staging\": \"tsc && vite build --base=/admin --mode staging\",\n \"build:prod\": \"tsc && vite build --base=/admin --mode production\",\n \"preview\": \"vite preview\"\n },\n \"dependencies\": {\n \"@ant-design/plots\": \"^1.2.4\",\n \"@material-ui/core\": \"^4.4.0\",\n \"@material-ui/icons\": \"^4.2.1\",\n \"@reduxjs/toolkit\": \"^1.9.2\",\n \"antd\": \"^3.19.3\",\n \"antd-virtual-select\": \"^1.1.2\",\n \"axios\": \"^1.3.0\",\n \"file-saver\": \"^2.0.5\",\n \"history\": \"^4.10.1\",\n \"html2canvas\": \"^1.4.1\",\n \"immutability-helper\": \"^3.0.1\",\n \"jquery\": \"^3.6.3\",\n \"jspdf\": \"^2.5.1\",\n \"keycloak-js\": \"^20.0.3\",\n \"less\": \"^4.1.3\",\n \"loadable-components\": \"^2.2.3\",\n \"lodash-decorators\": \"^6.0.1\",\n \"lodash.difference\": \"^4.5.0\",\n \"moment\": \"^2.29.4\",\n \"popper.js\": \"^1.16.1\",\n \"react\": \"^16.8.6\",\n \"react-dnd\": \"^9.4.0\",\n \"react-dnd-html5-backend\": \"^9.4.0\",\n \"react-dom\": \"^16.8.6\",\n \"react-html-parser\": \"^2.0.2\",\n \"react-intl\": \"^2.9.0\",\n \"react-intl-universal\": \"^2.6.11\",\n \"react-monaco-editor\": \"^0.31.0\",\n \"react-redux\": \"^8.0.5\",\n \"react-router-dom\": \"^5.3.4\",\n \"styled-components\": \"^5.3.6\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^18.11.18\",\n \"@types/react\": \"^16.8.6\",\n \"@types/react-dom\": \"^18.0.10\",\n \"@types/react-router-dom\": \"^5.3.3\",\n \"@vitejs/plugin-react\": \"^3.0.0\",\n \"typescript\": \"^4.9.5\",\n \"vite\": \"^4.0.0\"\n }\n}\n```\n\n```\nimport { defineConfig, loadEnv } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\nconst getApiHost = (npm_lifecycle_event: string) => {\n switch (npm_lifecycle_event) {\n default:\n case \"start\":\n return \"http://localhost:8080\";\n }\n};\n```\n\n```\nexport default defineConfig(({ mode }) => {\n const env = loadEnv(mode, process.cwd(), \"\");\n const scriptArray = env?.npm_lifecycle_script?.split(\" \") || [];\n const basePortion = scriptArray.find((scriptPortion) => {\n return scriptPortion.includes(\"--base\");\n });\n let outDir = basePortion ? basePortion.split(\"/\")[1] : \"build\";\n const target = getApiHost(env.npm_lifecycle_event);\n const runningLocally = mode.includes(\"local\");\n\n return {\n plugins: [react()],\n ...(runningLocally\n ? {\n define: {\n global: {},\n },\n }\n : {}),\n server: {\n port: 3000,\n open: true,\n proxy: {\n \"/api\": {\n target,\n changeOrigin: true,\n secure: false,\n },\n },\n },\n css: {\n preprocessorOptions: {\n less: {\n javascriptEnabled: true,\n additionalData: \"@root-entry-name: default;\",\n },\n },\n },\n build: {\n outDir,\n commonjsOptions: {\n transformMixedEsModules: true,\n },\n },\n };\n});\n```\n\n========================================\n\nTop Answer:\nThanks @andres-castellanos for the plugin function, it did work but I noted some problems with my setup:\n\n- I had strictRequires option set to `true` which seems confused the replace lookup. I had to change the value to `['auto', /someRegexPattern/]` to filter by specific packages.\n\n- When `sourcemap` is set to `true` the plugin breaks the sourcemap generation with this error:\n\nSourcemap is likely to be incorrect: a plugin (@ant-design-icons-fix) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help\n\nBasically the transform function should return the map as null in order to get sourcemap to work:\n\n```\ntransform(code: string, id: string): TransformResult {\n if (id.includes('@ant-design/icons/lib/dist.js')) {\n return {\n code: code.replace(', dist as default', ''),\n map: null\n }\n }\n return {\n code,\n map: null\n };\n},\n```\n\n========================================\n\nCode:\n```text\nexport function withSuffix(name, theme) {\n  switch (theme) {\n    case \"fill\":\n      return name + \"-fill\";\n    case \"outline\":\n      return name + \"-o\";\n    case \"twotone\":\n      return name + \"-twotone\";\n    default:\n      throw new TypeError(\"Unknown theme type: \" + theme + \", name: \" + name);\n  }\n}\n```\n\n```text\nicons.forEach(function (icon) {\n  _this2.definitions.set(withSuffix(icon.name, icon.theme), icon);\n});\n```\n\n```text\nexport function withSuffix(name, theme) {\n  switch (theme) {\n    case \"fill\":\n      return name + \"-fill\";\n    default:\n    case \"outline\":\n      return name + \"-o\";\n    case \"twotone\":\n      return name + \"-twotone\";\n  }\n}\n```\n\n```text\n`{\n  \"name\": \"ta\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"start\": \"vite --mode local\",\n    \"start:dev\": \"vite --mode local-development\",\n    \"start:qa\": \"vite --mode local-qa\",\n    \"build:dev\": \"tsc && vite build --base=/ta-admin --mode development\",\n    \"build:qa\": \"tsc && vite build --base=/ta-admin --mode qa\",\n    \"build:staging\": \"tsc && vite build --base=/admin --mode staging\",\n    \"build:prod\": \"tsc && vite build --base=/admin --mode production\",\n    \"preview\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"@ant-design/plots\": \"^1.2.4\",\n    \"@material-ui/core\": \"^4.4.0\",\n    \"@material-ui/icons\": \"^4.2.1\",\n    \"@reduxjs/toolkit\": \"^1.9.2\",\n    \"antd\": \"^3.19.3\",\n    \"antd-virtual-select\": \"^1.1.2\",\n    \"axios\": \"^1.3.0\",\n    \"file-saver\": \"^2.0.5\",\n    \"history\": \"^4.10.1\",\n    \"html2canvas\": \"^1.4.1\",\n    \"immutability-helper\": \"^3.0.1\",\n    \"jquery\": \"^3.6.3\",\n    \"jspdf\": \"^2.5.1\",\n    \"keycloak-js\": \"^20.0.3\",\n    \"less\": \"^4.1.3\",\n    \"loadable-components\": \"^2.2.3\",\n    \"lodash-decorators\": \"^6.0.1\",\n    \"lodash.difference\": \"^4.5.0\",\n    \"moment\": \"^2.29.4\",\n    \"popper.js\": \"^1.16.1\",\n    \"react\": \"^16.8.6\",\n    \"react-dnd\": \"^9.4.0\",\n    \"react-dnd-html5-backend\": \"^9.4.0\",\n    \"react-dom\": \"^16.8.6\",\n    \"react-html-parser\": \"^2.0.2\",\n    \"react-intl\": \"^2.9.0\",\n    \"react-intl-universal\": \"^2.6.11\",\n    \"react-monaco-editor\": \"^0.31.0\",\n    \"react-redux\": \"^8.0.5\",\n    \"react-router-dom\": \"^5.3.4\",\n    \"styled-components\": \"^5.3.6\"\n  },\n  \"devDependencies\": {\n    \"@types/node\": \"^18.11.18\",\n    \"@types/react\": \"^16.8.6\",\n    \"@types/react-dom\": \"^18.0.10\",\n    \"@types/react-router-dom\": \"^5.3.3\",\n    \"@vitejs/plugin-react\": \"^3.0.0\",\n    \"typescript\": \"^4.9.5\",\n    \"vite\": \"^4.0.0\"\n  }\n}\n```\n\n```text\nimport { defineConfig, loadEnv } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\nconst getApiHost = (npm_lifecycle_event: string) => {\n  switch (npm_lifecycle_event) {\n    default:\n    case \"start\":\n      return \"http://localhost:8080\";\n  }\n};\n```\n\n```text\nexport default defineConfig(({ mode }) => {\n  const env = loadEnv(mode, process.cwd(), \"\");\n  const scriptArray = env?.npm_lifecycle_script?.split(\" \") || [];\n  const basePortion = scriptArray.find((scriptPortion) => {\n    return scriptPortion.includes(\"--base\");\n  });\n  let outDir = basePortion ? basePortion.split(\"/\")[1] : \"build\";\n  const target = getApiHost(env.npm_lifecycle_event);\n  const runningLocally = mode.includes(\"local\");\n\n  return {\n    plugins: [react()],\n    ...(runningLocally\n      ? {\n          define: {\n            global: {},\n          },\n        }\n      : {}),\n    server: {\n      port: 3000,\n      open: true,\n      proxy: {\n        \"/api\": {\n          target,\n          changeOrigin: true,\n          secure: false,\n        },\n      },\n    },\n    css: {\n      preprocessorOptions: {\n        less: {\n          javascriptEnabled: true,\n          additionalData: \"@root-entry-name: default;\",\n        },\n      },\n    },\n    build: {\n      outDir,\n      commonjsOptions: {\n        transformMixedEsModules: true,\n      },\n    },\n  };\n});\n```\n\n```js\nimport * as allIcons from '@ant-design/icons/lib/dist';\n```\n\n```js\nconst allIcons = /*#__PURE__*/ _mergeNamespaces(\n  {\n    WindowsFill,\n    WindowsOutline,\n    WomanOutline,\n    YahooFill,\n    YahooOutline,\n    YoutubeFill,\n    YoutubeOutline,\n    YuqueFill,\n    YuqueOutline,\n    ZhihuCircleFill,\n    ZhihuOutline,\n    ZhihuSquareFill,\n    ZoomInOutline,\n    ZoomOutOutline,\n    default: dist$4,\n  },\n  [dist$4]\n);\n```\n\n```js\nfunction antDesignIconsFix() {\n  return {\n    name: '@ant-design-icons-fix',\n    transform(code, id) {\n      if (id.includes('@ant-design/icons/lib/dist.js'))\n        return code.replace(', dist as default', '')\n      return code\n    },\n  }\n}\n\nexport default defineConfig({\n    ...,\n    build: {\n      rollupOptions: {\n        plugins: [antDesignIconsFix()],\n      },\n    }\n})\n```\n\n```text\ntransform(code: string, id: string): TransformResult {\n    if (id.includes('@ant-design/icons/lib/dist.js')) {\n        return {\n            code: code.replace(', dist as default', ''),\n            map: null\n        }\n    }\n    return {\n        code,\n        map: null\n    };\n},\n```\n\n```text\ntrue\n```\n\n```text\n['auto', /someRegexPattern/]\n```\n\n```text\nsourcemap\n```\n\n```text\ntrue\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":443,"estimatedTokens":2529}}311{"id":"stack-74845363","source":"stackoverflow","questionId":74845363,"title":"vue3 with vite can't import CommonJS module","tags":["javascript","import","vuejs3","es6-modules","vite"],"text":"Title: vue3 with vite can't import CommonJS module\nTags: javascript, import, vuejs3, es6-modules, vite\nSource: Stack Overflow\n\nQuestion:\n### What is happning\n\nOn **vue2.6** + **webpack**, an application as is working well.\n\n```\n\n \n \n \n\nimport QR from 'qrcode-of-this-site'\nexport default {\n components: {QR},\n}\n\n```\n\nWhere qrcode-of-this-site imported at line#10 is my **ES6** module and using another external **CommonJS** module qrcode.\n\nHowever, on **vue3.2** + **vite**, this application reports an error as follows:\n\n```\nUncaught SyntaxError: The requested module '/node_modules/qrcode/lib/browser.js?v=0df8a00b' does not provide an export named 'default' (at QRcode.vue:11:8)\n```\n\n### watching files\n\nThe file **/node_modules/qrcode/lib/browser.js** is as follows:\n\n```\n...\n\nexports.create = QRCode.create\nexports.toCanvas = renderCanvas.bind(null, CanvasRenderer.render)\nexports.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL)\n\n// only svg for now.\nexports.toString = renderCanvas.bind(null, function (data, _, opts) {\n return SvgRenderer.render(data, opts)\n})\n```\n\n**QRcode.vue** is as follows:\n\n```\n\n \n \n \n \n QR code for this App\n \n\nimport QRCode from 'qrcode';\nexport default {\n mounted: function(){\n var currentUrl = window.location.origin;\n console.log(currentUrl);\n QRCode.toCanvas(document.getElementById('qr'),\n currentUrl, { toSJISFunc: QRCode.toSJIS }, function (error) {\n if (error) console.error(error)\n console.log('success!')\n })\n }\n}\n\n```\n\nAlso, I've tried `import {toCanvas} from 'qrcode';` at line #11 of QRcode.vue, and the error is reported as follows:\n\n```\nUncaught SyntaxError: The requested module '/node_modules/qrcode/lib/browser.js?v=0df8a00b' does not provide an export named 'toCanvas' (at QRcode.vue:11:9)\n```\n\neven **toCanvas** is certainly exported by **/node_modules/qrcode/lib/browser.js**\n\n### My question\n\nCan't the pair of **vue3** and **vite** import the **CommonJS** module as a default?\nAre there any necessary settings to run this app?\n\n### Reproducing environment\n\nThe full environment for reproducing is available as follows:\n\n- Vue2 env (working well) https://github.com/UedaTakeyuki/QRcodeVue2\n\n- Vue3 env (import error) https://github.com/UedaTakeyuki/QRcodeVue3\n\n========================================\n\nCode:\n```text\n<template>\n<v-app>\n  <QR/>\n  <v-main>\n  </v-main>\n</v-app>\n</template>\n\n<script>\nimport QR from 'qrcode-of-this-site'\nexport default {\n  components: {QR},\n}\n</script>\n```\n\n```text\nUncaught SyntaxError: The requested module '/node_modules/qrcode/lib/browser.js?v=0df8a00b' does not provide an export named 'default' (at QRcode.vue:11:8)\n```\n\n```text\n...\n\nexports.create = QRCode.create\nexports.toCanvas = renderCanvas.bind(null, CanvasRenderer.render)\nexports.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL)\n\n// only svg for now.\nexports.toString = renderCanvas.bind(null, function (data, _, opts) {\n  return SvgRenderer.render(data, opts)\n})\n```\n\n```text\n<template>\n  <v-layout column align-center class=\"white--text\">\n    <v-flex>\n      <canvas id=\"qr\"></canvas>\n    </v-flex>\n    QR code for this App\n  </v-layout>\n</template>\n\n<script>\nimport QRCode from 'qrcode';\nexport default {\n  mounted: function(){\n    var currentUrl = window.location.origin;\n    console.log(currentUrl);\n    QRCode.toCanvas(document.getElementById('qr'),\n      currentUrl, { toSJISFunc: QRCode.toSJIS }, function (error) {\n      if (error) console.error(error)\n      console.log('success!')\n    })\n  }\n}\n</script>\n```\n\n```text\nUncaught SyntaxError: The requested module '/node_modules/qrcode/lib/browser.js?v=0df8a00b' does not provide an export named 'toCanvas' (at QRcode.vue:11:9)\n```\n\n```text\nimport {toCanvas} from 'qrcode';\n```\n\n```text\n// vite.config.js\n\nexport default defineConfig({\n  ...\n  optimizeDeps: {\n    include: [\"qrcode\"],\n  },\n});\n```\n\n```text\nqrcode-of-this-site\n```\n\n```text\nqrcode-of-this-site\n```\n\n========================================\n\nComments:\n- You second point here is gold, I could have saved myself hours if I found it sooner.\n- thanks for the answer, i was able to fix the error on local dev server but on build it shows RollupError: module is not exported by package/dist/index.js, any idea on this issue?\n- If you navigate to the link in my post you'll see how to make it work for the production build. Here is it too: vitejs.dev/guide/&hellip;\n- do you know the difference between optimizedep transpiling VS using commonjsOptions config?\n- Why do you say that Vite can't work with CommonJS? Is this still true in 2024? The Vite docs here state that \"*CommonJS and UMD compatibility: During development, Vite's dev serves all code as native ESM. Therefore, Vite must convert dependencies that are shipped as CommonJS or UMD into ESM first.*\"\n- I meant that the package wasn't seen during smart analysis. I don't think I looked into it extensively so I don't exactly know why. I linked to the same page as your quote btw.\n- This doesn't seem to work in 2024 on latest versions.","metadata":{"transformedAt":"2026-08-18T18:33:46.417Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":194,"estimatedTokens":1251}}312{"id":"stack-76905898","source":"stackoverflow","questionId":76905898,"title":"Unknown Issue with Vitepress","tags":["javascript","vue.js","vite","vitepress"],"text":"Title: Unknown Issue with Vitepress\nTags: javascript, vue.js, vite, vitepress\nSource: Stack Overflow\n\nQuestion:\nAfter I use pnpm initialize my vitepress project with latest vitepress version, I use `pnpm run docs:dev` to try running it. And it appears such errors:\n\n```\n✘ [ERROR] \"vitepress\" resolved to an ESM file. ESM file cannot be loaded by `require`. See http://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only for more details. [plugin externalize-deps]\n\n node_modules/.pnpm/esbuild@0.18.20/node_modules/esbuild/lib/main.js:1373:27:\n 1373 │ let result = await callback({\n ╵ ^\n\n at file:///C:/Users/CoolPlayLin/Project/ChatGPT-Wiki/node_modules/.pnpm/vite@4.4.9/node_modules/vite/dist/node/chunks/dep-df561101.js:66190:35\n at requestCallbacks.on-resolve (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:1373:28)\n at handleRequest (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:729:19)\n at handleIncomingPacket (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:755:7)\n at Socket.readFromStdout (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:679:7)\n at Socket.emit (node:events:514:28)\n at addChunk (node:internal/streams/readable:343:12)\n at readableAddChunk (node:internal/streams/readable:316:9)\n at Readable.push (node:internal/streams/readable:253:10)\n at Pipe.onStreamRead (node:internal/stream_base_commons:190:23)\n\n This error came from the \"onResolve\" callback registered here:\n\n node_modules/.pnpm/esbuild@0.18.20/node_modules/esbuild/lib/main.js:1292:20:\n 1292 │ let promise = setup({\n ╵ ^\n\n at setup (file:///C:/Users/CoolPlayLin/Project/ChatGPT-Wiki/node_modules/.pnpm/vite@4.4.9/node_modules/vite/dist/node/chunks/dep-df561101.js:66158:27)\n at handlePlugins (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:1292:21)\n at buildOrContextImpl (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:978:5)\n at Object.buildOrContext (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:786:5)\n at C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:2177:15\n at new Promise ()\n at Object.build (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:2176:25)\n at build (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:2025:51)\n at bundleConfigFile (file:///C:/Users/CoolPlayLin/Project/ChatGPT-Wiki/node_modules/.pnpm/vite@4.4.9/node_modules/vite/dist/node/chunks/dep-df561101.js:66109:26)\n\n The plugin \"externalize-deps\" was triggered by this import\n\n docs/.vitepress/config.js:1:382:\n 1 │ ...olPlayLin/Project/ChatGPT-Wiki/docs/.vitepress/config.js\";import { defineConfig } from 'vitepress' \n ╵ ~~~~~~~~~~~ \n\nfailed to load config from C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\docs\\.vitepress\\config.js\nfailed to start server. error:\nError: Build failed with 1 error:\nnode_modules/.pnpm/esbuild@0.18.20/node_modules/esbuild/lib/main.js:1373:27: ERROR: [plugin: externalize-deps] \"vitepress\" resolved to an ESM file. ESM file cannot be loaded by `require`. See http://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only for more details.\n at failureErrorWithLog (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:1649:15)\n at C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:1058:25\n at runOnEndCallbacks (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:1484:45)\n at buildResponseToResult (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:1056:7)\n at C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:1085:16\n at responseCallbacks. (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:703:9)\n at handleIncomingPacket (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:762:9)\n at Socket.readFromStdout (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:679:7)\n at Socket.emit (node:events:514:28)\n at addChunk (node:internal/streams/readable:343:12)\n ELIFECYCLE  Command failed with exit code 1.\n```\n\nWhat should I do to resolve it?\n\nI try running it with `pnpm run docs:dev`. I expect it would be run successfully\n\n========================================\n\nCode:\n```text\n✘ [ERROR] \"vitepress\" resolved to an ESM file. ESM file cannot be loaded by `require`. See http://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only for more details. [plugin externalize-deps]\n\n    node_modules/.pnpm/esbuild@0.18.20/node_modules/esbuild/lib/main.js:1373:27:\n      1373 │         let result = await callback({\n           ╵                            ^\n\n    at file:///C:/Users/CoolPlayLin/Project/ChatGPT-Wiki/node_modules/.pnpm/vite@4.4.9/node_modules/vite/dist/node/chunks/dep-df561101.js:66190:35\n    at requestCallbacks.on-resolve (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:1373:28)\n    at handleRequest (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:729:19)\n    at handleIncomingPacket (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:755:7)\n    at Socket.readFromStdout (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:679:7)\n    at Socket.emit (node:events:514:28)\n    at addChunk (node:internal/streams/readable:343:12)\n    at readableAddChunk (node:internal/streams/readable:316:9)\n    at Readable.push (node:internal/streams/readable:253:10)\n    at Pipe.onStreamRead (node:internal/stream_base_commons:190:23)\n\n  This error came from the \"onResolve\" callback registered here:\n\n    node_modules/.pnpm/esbuild@0.18.20/node_modules/esbuild/lib/main.js:1292:20:\n      1292 │       let promise = setup({\n           ╵                     ^\n\n    at setup (file:///C:/Users/CoolPlayLin/Project/ChatGPT-Wiki/node_modules/.pnpm/vite@4.4.9/node_modules/vite/dist/node/chunks/dep-df561101.js:66158:27)\n    at handlePlugins (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:1292:21)\n    at buildOrContextImpl (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:978:5)\n    at Object.buildOrContext (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:786:5)\n    at C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:2177:15\n    at new Promise (<anonymous>)\n    at Object.build (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:2176:25)\n    at build (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:2025:51)\n    at bundleConfigFile (file:///C:/Users/CoolPlayLin/Project/ChatGPT-Wiki/node_modules/.pnpm/vite@4.4.9/node_modules/vite/dist/node/chunks/dep-df561101.js:66109:26)\n\n  The plugin \"externalize-deps\" was triggered by this import\n\n    docs/.vitepress/config.js:1:382:\n      1 │ ...olPlayLin/Project/ChatGPT-Wiki/docs/.vitepress/config.js\";import { defineConfig } from 'vitepress' \n        ╵                                                                                           ~~~~~~~~~~~ \n\nfailed to load config from C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\docs\\.vitepress\\config.js\nfailed to start server. error:\nError: Build failed with 1 error:\nnode_modules/.pnpm/esbuild@0.18.20/node_modules/esbuild/lib/main.js:1373:27: ERROR: [plugin: externalize-deps] \"vitepress\" resolved to an ESM file. ESM file cannot be loaded by `require`. See http://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only for more details.\n    at failureErrorWithLog (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:1649:15)\n    at C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:1058:25\n    at runOnEndCallbacks (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:1484:45)\n    at buildResponseToResult (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:1056:7)\n    at C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:1085:16\n    at responseCallbacks.<computed> (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:703:9)\n    at handleIncomingPacket (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:762:9)\n    at Socket.readFromStdout (C:\\Users\\CoolPlayLin\\Project\\ChatGPT-Wiki\\node_modules\\.pnpm\\esbuild@0.18.20\\node_modules\\esbuild\\lib\\main.js:679:7)\n    at Socket.emit (node:events:514:28)\n    at addChunk (node:internal/streams/readable:343:12)\n ELIFECYCLE  Command failed with exit code 1.\n```\n\n```text\npnpm run docs:dev\n```\n\n```text\npnpm run docs:dev\n```\n\n========================================\n\nComments:\n- You can try to delete node modules and install it again","metadata":{"transformedAt":"2026-08-18T18:33:46.417Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":140,"estimatedTokens":2507}}313{"id":"stack-73044119","source":"stackoverflow","questionId":73044119,"title":"How to use DataTables with Laravel Vite?","tags":["laravel","datatables","vite"],"text":"Title: How to use DataTables with Laravel Vite?\nTags: laravel, datatables, vite\nSource: Stack Overflow\n\nQuestion:\nI'm having trouble adding DataTables to my new Laravel 9.21 instance. But I'm getting an error in the console. What am I missing?\n\nUncaught TypeError: $(...).DataTable is not a function\n\n**bootstrap.js**\n\n```\nimport jquery from 'jquery';\nwindow.jQuery = jquery;\nwindow.$ = jquery;\n\nimport DataTable from 'datatables.net';\nwindow.DataTable = DataTable;\n\n$(document).ready(function() {\n $('#example').DataTable();\n});\n```\n\n========================================\n\nTop Answer:\nHere's the solution to my problem.\n\n**bootstrap.js**\n\n```\nimport _ from 'lodash';\nwindow._ = _;\n\nimport $ from 'jquery';\nwindow.jQuery = window.$ = $\n\nimport DataTable from 'datatables.net';\nwindow.DataTable = DataTable;\nDataTable($);\n\n$(document).ready(function() {\n $('#example').DataTable();\n});\n```\n\n========================================\n\nCode:\n```text\nimport jquery from 'jquery';\nwindow.jQuery = jquery;\nwindow.$ = jquery;\n\nimport DataTable from 'datatables.net';\nwindow.DataTable = DataTable;\n\n$(document).ready(function() {\n    $('#example').DataTable();\n});\n```\n\n```text\nimport \"./bootstrap\";\nimport \"../sass/app.scss\";\n\nimport * as bootstrap from \"bootstrap\";\n\nimport jQuery from \"jquery\";\nwindow.$ = jQuery;\n\nimport DataTable from \"datatables.net-bs5\";\nDataTable(window, window.$);\n```\n\n```text\nDataTable(window, window.$)\n```\n\n```text\nrequire( 'datatables.net-bs5' )( window, $ );\n```\n\n```text\napp.js\n```\n\n```text\nimport _ from 'lodash';\nwindow._ = _;\n\nimport $ from 'jquery';\nwindow.jQuery = window.$ = $\n\nimport DataTable from 'datatables.net';\nwindow.DataTable = DataTable;\nDataTable($);\n\n$(document).ready(function() {\n    $('#example').DataTable();\n});\n```\n\n```text\nimport $ from \"jquery\";\nwindow.$ = $\n\nimport DataTable from 'datatables.net';\nwindow.DataTable = DataTable;\n```\n\n```text\nVite 4.0.4 and Laravel 9\n```\n\n```text\nimport DataTable from 'admin-lte/plugins/datatables/jquery.dataTables.min.js';\nwindow.DataTable = DataTable;\n```\n\n```text\n@push('scripts')\n    <script type=\"module\" >\n      $(document).ready(function() {\n           new DataTable('#table2', {} );\n      });\n     </script>\n    @endpush\n```\n\n========================================\n\nComments:\n- DataTable($); worked\n- Dude, I love you. Hours wasted trying to figure this out but your solution worked.\n- You Rock!!! Thank You! This will help out so many users out there using both these technologies.","metadata":{"transformedAt":"2026-08-18T18:33:46.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":137,"estimatedTokens":621}}314{"id":"stack-75442491","source":"stackoverflow","questionId":75442491,"title":"TypeError: a.then is not a function while compiling in production","tags":["vue.js","vuejs3","vite"],"text":"Title: TypeError: a.then is not a function while compiling in production\nTags: vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to compile my vue app in production with `npm run build` (which is vite build).\n\nAfter that I try to serve my app on my server with the /dist folder and everything seems to be working perfectly, I'm able to send fetch request, click on various links etc.\n\nUnfortunately, after logging in and when I should be redirected, I'm getting the error\n\nTypeError: a.then is not a function while compiling in production\n\nand\n\nUncaught (in promise) TypeError: a.then is not a function\"\n\nEverything just works perfectly fine while I'm in dev mode, it's just not working in production.\n\nIt seems to be linked to the router\n\nThis is the code for my Router :\n\n\r\n\r\n\n```\nconst state = reactive({\n token: localStorage.getItem(\"token\"),\n userAdmin: false,\n userRestaurateur: false,\n userDeliverer: false\n});\n\nif (state.token) {\n const user = JSON.parse(atob(state.token.split('.')[1]))\n state.userAdmin = Object.values(user.roles).includes('ROLE_ADMIN');\n state.userRestaurateur = Object.values(user.roles).includes('ROLE_RESTAURANT');\n state.userDeliverer = Object.values(user.roles).includes('ROLE_DELIVERER');\n}\n\nconst router = createRouter({\n history: createWebHistory('/'),\n routes: [\n {\n path: '/',\n name: 'home',\n component: function () {\n if (state.token && state.userAdmin) {\n return Users\n } else if (state.token && state.userRestaurateur) {\n return HomeRestaurateur\n }else if (state.token && state.userDeliverer) {\n return Commands\n }else {\n return Home\n }\n }\n },\n {\n path: \"/login\",\n name: \"login\",\n component: Login,\n },\n {\n path: \"/forgot-password\",\n name: \"forgot_password\",\n component: ForgotPassword,\n },\n {\n path: \"/reset-password/:token\",\n name: \"reset_password_token\",\n component: ResetPassword,\n },\n {\n path: \"/register\",\n name: \"register\",\n component: Register,\n },\n {\n path: \"/profile\",\n name: \"editProfile\",\n component: editProfile,\n },\n {\n path: \"/Restaurant/:id/Menu\",\n name: \"Meals\",\n component: Meals,\n },\n {\n path: \"/admin/users\",\n name: \"admin_users\",\n component: function () {\n if (state.userAdmin) {\n return Users\n } else {\n return Error403\n }\n }\n },\n {\n path: \"/admin/restaurants\",\n name: \"admin_restaurants\",\n component: function () {\n if (state.userAdmin) {\n return Restaurants\n } else {\n return Error403\n }\n }\n },\n {\n path: \"/admin/restaurants_request\",\n name: \"admin_restaurants_request\",\n component: function () {\n if (state.userAdmin) {\n return RestaurantsRequest\n } else {\n return Error403\n }\n }\n },\n {\n path: \"/restaurants/new\",\n name: \"create_restaurants\",\n component: CreateRestaurant,\n },\n {\n path: \"/admin/reports\",\n name: \"admin_reports\",\n component: function () {\n if (state.userAdmin) {\n return Reports\n } else {\n return Error403\n }\n }\n },\n {\n path: \"/orders\",\n name: \"orders\",\n component: Commands,\n },\n {\n path: \"/:pathMatch(.*)*\",\n name: \"not_found\",\n component: Error404,\n }\n ],\n});\n```\n\n\r\n\r\n\r\n\nI tried checking if other methods were working correctly, tried to change server, nothing just seems to work.\n\n========================================\n\nCode:\n```js\nconst state = reactive({\n    token: localStorage.getItem(\"token\"),\n    userAdmin: false,\n    userRestaurateur: false,\n    userDeliverer: false\n});\n\nif (state.token) {\n    const user = JSON.parse(atob(state.token.split('.')[1]))\n    state.userAdmin = Object.values(user.roles).includes('ROLE_ADMIN');\n    state.userRestaurateur = Object.values(user.roles).includes('ROLE_RESTAURANT');\n    state.userDeliverer = Object.values(user.roles).includes('ROLE_DELIVERER');\n}\n\nconst router = createRouter({\n    history: createWebHistory('/'),\n    routes: [\n        {\n            path: '/',\n            name: 'home',\n            component: function () {\n                if (state.token && state.userAdmin) {\n                    return Users\n                } else if (state.token && state.userRestaurateur) {\n                    return HomeRestaurateur\n                }else if (state.token && state.userDeliverer) {\n                    return Commands\n                }else {\n                    return Home\n                }\n            }\n        },\n        {\n            path: \"/login\",\n            name: \"login\",\n            component: Login,\n        },\n        {\n            path: \"/forgot-password\",\n            name: \"forgot_password\",\n            component: ForgotPassword,\n        },\n        {\n            path: \"/reset-password/:token\",\n            name: \"reset_password_token\",\n            component: ResetPassword,\n        },\n        {\n            path: \"/register\",\n            name: \"register\",\n            component: Register,\n        },\n        {\n            path: \"/profile\",\n            name: \"editProfile\",\n            component: editProfile,\n        },\n        {\n            path: \"/Restaurant/:id/Menu\",\n            name: \"Meals\",\n            component: Meals,\n        },\n        {\n            path: \"/admin/users\",\n            name: \"admin_users\",\n            component: function () {\n                if (state.userAdmin) {\n                    return Users\n                } else {\n                    return Error403\n                }\n            }\n        },\n        {\n            path: \"/admin/restaurants\",\n            name: \"admin_restaurants\",\n            component: function () {\n                if (state.userAdmin) {\n                    return Restaurants\n                } else {\n                    return Error403\n                }\n            }\n        },\n        {\n            path: \"/admin/restaurants_request\",\n            name: \"admin_restaurants_request\",\n            component: function () {\n                if (state.userAdmin) {\n                    return RestaurantsRequest\n                } else {\n                    return Error403\n                }\n            }\n        },\n        {\n            path: \"/restaurants/new\",\n            name: \"create_restaurants\",\n            component: CreateRestaurant,\n        },\n        {\n            path: \"/admin/reports\",\n            name: \"admin_reports\",\n            component: function () {\n                if (state.userAdmin) {\n                    return Reports\n                } else {\n                    return Error403\n                }\n            }\n        },\n        {\n            path: \"/orders\",\n            name: \"orders\",\n            component: Commands,\n        },\n        {\n            path: \"/:pathMatch(.*)*\",\n            name: \"not_found\",\n            component: Error404,\n        }\n    ],\n});\n```\n\n```text\nnpm run build\n```\n\n```text\nUncaught (in promise) TypeError: i.then is not a function\"\n```\n\n```text\n{\n    path: '/profile',\n    name: 'Profile',\n    component: () => Profile, //this was the problem\n  },\n```\n\n```text\n{\n    path: '/profile',\n    name: 'Profile',\n    component: Profile, //this was the fix\n  },\n```\n\n========================================\n\nComments:\n- Did you check if import.meta.env.VITE_API_URL is available for it in production?\n- I think so, just edited my post because I think it's linked to my router, apparently it could be linked more precisely to \"component :\"\n- There is no `a` variable in your snippet. More info would help. Please provide full stack trace or runnable code.\n- Disable minification if you can't debug minified code, you can click on stack trace and check the exact location. Currently only you can do that, there's no `then` in the code you posted, see stackoverflow.com/help/mcve\n- Try doing this, put up some console logs during the login process and also log the import.meta.env.VITE_API_URL. This would give better information to debug even in production.\n- The answer was that you can't pass a function to the component line, I had to do component: Home instead of passing a function\n- Thank you for this! I had no idea where this error came from and I had been modifying the components for a more appropriate code-splitting and immeadiatelly noticed the same non-working pattern\n- THANK YOU after two hours of search your input saved me!\n- I had this same problem after refactoring inline route imports to move them all to the top. My error was `c.then` and I added sourcemap to production to find it was `componentPromise` returned from `rawComponent()` which was not a promise but already resolved to the route object. I wonder why it works fine in local, but not in production? Any ideas?","metadata":{"transformedAt":"2026-08-18T18:33:46.418Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":323,"estimatedTokens":2096}}315{"id":"stack-75537379","source":"stackoverflow","questionId":75537379,"title":"How to debug server-side code in SvelteKit using Visual Studio Code","tags":["javascript","visual-studio-code","debugging","vite","sveltekit"],"text":"Title: How to debug server-side code in SvelteKit using Visual Studio Code\nTags: javascript, visual-studio-code, debugging, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI would like to debug server side code (+server.svelte) code in VS code but cannot work out how.\n\n========================================\n\nTop Answer:\nServer-side debugging is possible, but not fully supported:\n\n- You can trigger the debugger with `debugger` statements.\n\n- Or breakpoints in the *compiled* code.\n\n- Breakpoints in uncompiled Svelte/TS source files will not work because of a Vite issue with sourcemaps.\n\nYou need to attach the VS code debugger to the SvelteKit dev server. This is one way to do this: https://app.arcade.software//RIrEisEk7V36paQmqtNI\n\n========================================\n\nCode:\n```text\ndebugger\n```\n\n```text\nnode-loader\n```\n\n```text\nvavite\n```\n\n```text\ndebugger\n```\n\n```text\n+page.js\n```\n\n```text\n+server.js\n```\n\n```text\nnpx vite dev\n```\n\n```text\nDebug: Attach to node process\n```\n\n```text\nvite\n```\n\n========================================\n\nComments:\n- This is great. I had it working with this but it just suddenly just stopped. It gave me a warning about multiple lock files when I ran the debugger. I found a pnpm one (I use npm). I removed it but same issue, unbound breakpoints. Any pointers to what I could do to get it back working again?\n- A link to an external source shouldn't be voted up. This is just junk baitclick.\n- Don't accept an out link as answer.\n- A link to an external source shouldn't be voted up. This is just junk baitclick.\n- Yes, this is currently the best way to do it in my opinion!","metadata":{"transformedAt":"2026-08-18T18:33:46.418Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":67,"estimatedTokens":407}}316{"id":"stack-76399528","source":"stackoverflow","questionId":76399528,"title":"Importing Select2 & Laravel Vite","tags":["import","jquery-select2","vite"],"text":"Title: Importing Select2 & Laravel Vite\nTags: import, jquery-select2, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use select2 in my Laravel 10 project, which is using Vite. I kept getting the error\n\n```\nUncaught TypeError: $(...).select2 is not a function\n```\n\n**My question:**\n\nWhat is the correct way to import select2 in Vite (without having to\nuse a Vite config alias)? What am I doing wrong?\n\nI've run `npm i select2` (from my package.json)\n\n```\n\"select2\": \"^4.1.0-rc.0\",\n \"vite\": \"^4.0.0\"\n```\n\nI've tried a bunch of different ways of importing but landed on\n\nupdating my vite.config.js file (simplified for example)\n\n```\nimport { defineConfig } from 'vite';\n import laravel from 'laravel-vite-plugin';\n import path from 'path';\n\n export default defineConfig({\n plugins: [\n laravel({\n input: ['resources/sass/app.scss', 'resources/js/app.js'],\n refresh: true,\n }),\n ],\n resolve: {\n alias: {\n 'select2': 'node_modules/select2/dist/js/select2.full.min.js',\n\n }\n },\n });\n```\n\nusing the following in my app.js\n\n```\nimport 'select2';\n import '../../node_modules/select2/dist/css/select2.css';\n```\n\nThe weird thing is\n\n- `select2` is working\n\n- I get a console log error: Failed to load url `/@fs/node_modules/select2/dist/js/select2.full.min.js (resolved id: /node_modules/select2/dist/js/select2.full.min.js? [...]`\n\n========================================\n\nTop Answer:\nHere's a better solution that works with both `vite` on dev and `vite build` for production:\n\n```\nimport jQuery from 'jquery';\nlet $ = window.$ = window.jQuery = jQuery;\n\n// Use the `?raw` suffix to import select2 as a string\nimport src from 'select2?raw';\n\n// Manually invoke Select2's UMD factory with jQuery (Vite 7 Rollup doesn't auto-init)\nnew Function('module', 'require', 'window', 'jQuery', src)(\n {}, ()=>jQuery, window, jQuery\n);\n\n// Now you can use $('#mySelect').select2();\n```\n\n========================================\n\nCode:\n```text\nUncaught TypeError: $(...).select2 is not a function\n```\n\n```text\n\"select2\": \"^4.1.0-rc.0\",\n    \"vite\": \"^4.0.0\"\n```\n\n```text\nimport { defineConfig } from 'vite';\n import laravel from 'laravel-vite-plugin';\n import path from 'path';\n\n export default defineConfig({\n     plugins: [\n         laravel({\n             input: ['resources/sass/app.scss', 'resources/js/app.js'],\n             refresh: true,\n         }),\n     ],\n     resolve: {\n         alias: {\n             'select2': 'node_modules/select2/dist/js/select2.full.min.js',\n\n         }\n     },\n });\n```\n\n```text\nimport 'select2';\n import '../../node_modules/select2/dist/css/select2.css';\n```\n\n```text\nnpm i select2\n```\n\n```text\nselect2\n```\n\n```text\n/@fs/node_modules/select2/dist/js/select2.full.min.js (resolved id: /node_modules/select2/dist/js/select2.full.min.js? [...]\n```\n\n```text\nnpm i jquery select2 --save-dev\n```\n\n```js\n// import jquery and select2\nimport $ from \"jquery\";\nimport select2 from 'select2';\nwindow.$ = $; // <-- jquery must be set\nselect2(); // <-- select2 must be called\n```\n\n```js\n//-- Select2\nimport \"/node_modules/select2/dist/css/select2.css\";\n//--\nimport '../css/app.css';\n// ...\n```\n\n```js\n$('.js-example-basic-single').select2();\n```\n\n```js\nimport jQuery from 'jquery';\nlet $ = window.$ = window.jQuery = jQuery;\n\n// Use the `?raw` suffix to import select2 as a string\nimport src from 'select2?raw';\n\n// Manually invoke Select2's UMD factory with jQuery (Vite 7 Rollup doesn't auto-init)\nnew Function('module', 'require', 'window', 'jQuery', src)(\n  {}, ()=>jQuery, window, jQuery\n);\n\n// Now you can use $('#mySelect').select2();\n```\n\n```text\nvite\n```\n\n```text\nvite build\n```\n\n========================================\n\nComments:\n- works in dev , but when building you will get `resources&#47;js&#47;app.js (6:7): \"default\" is not exported by \"node_modules&#47;select2&#47;dist&#47;js&#47;select2.js\", imported by \"resources&#47;js&#47;app.js\".`\n- @EdmundSulzanok Try my answer for a fix for `vite build` - you must manually invoke Select2's factory. stackoverflow.com/a/79756469/2525465","metadata":{"transformedAt":"2026-08-18T18:33:46.418Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":183,"estimatedTokens":1001}}317{"id":"stack-79473004","source":"stackoverflow","questionId":79473004,"title":"Adding HeroUI after creating a ReactJS application via Vite","tags":["reactjs","next.js","tailwind-css","vite","tailwind-css-4"],"text":"Title: Adding HeroUI after creating a ReactJS application via Vite\nTags: reactjs, next.js, tailwind-css, vite, tailwind-css-4\nSource: Stack Overflow\n\nQuestion:\nI'm following the instruction Here trying to make HeroUI works with React app created via Vite. However, it doesn't seem to be working!\n\nTailwind CSS on the other hand is working perfectly, app running with no errors, but HeroUI components are not applied!!\n\nmy vite.config.js:\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport tailwindcss from '@tailwindcss/vite'\n\n// https://vite.dev/config/\nexport default defineConfig({\n plugins: [\n react(),\n tailwindcss()\n ],\n})\n```\n\nmy tailwind.config.js:\n\n```\nimport { heroui } from \"@heroui/react\";\n\n/** @type {import('tailwindcss').Config} */\nexport default {\n content: [\n \"./index.html\",\n \"./src/**/*.{js,ts,jsx,tsx}\",\n \"./node_modules/@heroui/theme/dist/**/*.{js,ts,jsx,tsx}\"\n ],\n theme: {\n extend: {},\n },\n darkMode: \"class\",\n plugins: [heroui()]\n}\n```\n\nmy main.jsx:\n\n```\nimport { StrictMode } from 'react'\nimport { createRoot } from 'react-dom/client'\n\nimport {HeroUIProvider} from '@heroui/react'\nimport App from './App.jsx'\nimport './index.css'\n\ncreateRoot(document.getElementById('root')).render(\n \n \n \n \n \n \n ,\n)\n```\n\nmy index.css:\n\n```\n@import \"tailwindcss\";\n```\n\nand my App.jsx:\n\n```\nimport {DateInput} from \"@heroui/react\";\nimport {CalendarDate} from \"@internationalized/date\";\nimport {Avatar} from \"@heroui/react\";\n\nexport default function App() {\n return (\n <>\n \n \n\n### Hello, Vite + React!\n\n \n\n \n \n \n\n \n\n \n \n \n \n \n \n \n \n\n \n )\n}\n```\n\nI've tried many different configurations but no use, I couldn't make the HeroUI components work so far. Any suggestion? did I miss something?\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport tailwindcss from '@tailwindcss/vite'\n\n// https://vite.dev/config/\nexport default defineConfig({\n  plugins: [\n    react(),\n    tailwindcss()\n  ],\n})\n```\n\n```text\nimport { heroui } from \"@heroui/react\";\n\n/** @type {import('tailwindcss').Config} */\nexport default {\n    content: [\n        \"./index.html\",\n        \"./src/**/*.{js,ts,jsx,tsx}\",\n        \"./node_modules/@heroui/theme/dist/**/*.{js,ts,jsx,tsx}\"\n    ],\n    theme: {\n        extend: {},\n    },\n    darkMode: \"class\",\n    plugins: [heroui()]\n}\n```\n\n```text\nimport { StrictMode } from 'react'\nimport { createRoot } from 'react-dom/client'\n\nimport {HeroUIProvider} from '@heroui/react'\nimport App from './App.jsx'\nimport './index.css'\n\ncreateRoot(document.getElementById('root')).render(\n  <StrictMode>\n    \n    <HeroUIProvider>\n      <App />\n    </HeroUIProvider>\n    \n  </StrictMode>,\n)\n```\n\n```text\n@import \"tailwindcss\";\n```\n\n```text\nimport {DateInput} from \"@heroui/react\";\nimport {CalendarDate} from \"@internationalized/date\";\nimport {Avatar} from \"@heroui/react\";\n\nexport default function App() {\n  return (\n    <>\n      <div className=\"bg-blue-500 text-white p-4\">\n        <h1>Hello, Vite + React!</h1>\n      </div>\n\n      <div className=\"flex w-full flex-wrap md:flex-nowrap gap-4\">\n        <DateInput\n          className=\"max-w-sm\"\n          label={\"Birth date\"}\n          placeholderValue={new CalendarDate(1995, 11, 6)} />\n      </div>\n\n      \n\n    <div className=\"flex gap-3 items-center\">\n      <Avatar src=\"https://i.pravatar.cc/150?u=a042581f4e29026024d\" />\n      <Avatar name=\"Junior\" />\n      <Avatar src=\"https://i.pravatar.cc/150?u=a042581f4e29026704d\" />\n      <Avatar name=\"Jane\" />\n      <Avatar src=\"https://i.pravatar.cc/150?u=a04258114e29026702d\" />\n      <Avatar name=\"Joe\" />\n    </div>\n\n    </>    \n  )\n}\n```\n\n```none\nnpm install @heroui/react@latest\n```\n\n```js\n// hero.ts\nimport { heroui } from \"@heroui/react\";\n// or import from theme package if you are using individual packages.\n// import { heroui } from \"@heroui/theme\";\nexport default heroui();\n```\n\n```css\n@import \"tailwindcss\";\n\n/* Note: Make sure the relative reference is correct */\n/* I assumed when writing the response that they are in the same folder */\n@plugin './hero.ts';\n/* Note: You may need to change the path to fit your project structure */\n@source '../../node_modules/@heroui/theme/dist/**/*.{js,ts,jsx,tsx}';\n@custom-variant dark (&:is(.dark *));\n```\n\n```none\nnpm install @heroui/react@beta\n```\n\n```js\nimport { heroui } from \"@heroui/react\";\nexport default heroui();\n```\n\n```css\n@import \"tailwindcss\";\n@plugin './hero.ts';\n/* Note: You may need to change the path to fit your project structure */\n@source '../../node_modules/@heroui/theme/dist/**/*.{js,ts,jsx,tsx}';\n@custom-variant dark (&:is(.dark *));\n```\n\n```css\n@import \"tailwindcss\";\n@source \"../../node_modules/@heroui\";\n```\n\n```none\nnpm install tailwindcss@3\n```\n\n```text\nhero.ts\n```\n\n```text\ntailwind.config.js\n```\n\n```text\n@config\n```\n\n```text\n.gitignore\n```\n\n```text\n/node_modules/\n```\n\n```text\nhero-inc/heroui\n```\n\n========================================\n\nComments:\n- saved me a few hours, k&#246;szi!","metadata":{"transformedAt":"2026-08-18T18:33:46.418Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":281,"estimatedTokens":1249}}318{"id":"stack-73917316","source":"stackoverflow","questionId":73917316,"title":"How to add inline SVGs in a nuxt3 vite project","tags":["javascript","vue.js","svg","vite","nuxt3.js"],"text":"Title: How to add inline SVGs in a nuxt3 vite project\nTags: javascript, vue.js, svg, vite, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nHi have been having troubling importing inline svgs into my nuxt3 vite project. Any advice would be much appreciated.\n\ni found this works `` however i need an inline item. so i would do something like this `` and doing something like this(require doesnt work in vite) .\n\n```\nsetup(props) {\n const currentIcon = computed(() => {\n return defineAsyncComponent(() =>\n import(`~/assets/images/icons/push-icon-chatops.svg'?inline`)\n );\n }).value;\n\n return {\n currentIcon,\n };\n },\n```\n\nhowever i found that vite does imports weirdly and the result is either the url string showing in the v-html or a object that doesnt read\n\ni am trying to use this plugin with no success.\n\nhttps://github.com/nuxt-community/svg-module\n\n========================================\n\nTop Answer:\nFor TS Nuxt 3 projects it would be like this.\n\n`nuxt.config.ts` file:\n\n```\nimport svgLoader from 'vite-svg-loader'\n\nexport default defineNuxtConfig({\n // Rest of your config.\n vite: {\n plugins: [\n svgLoader({\n // Your settings.\n }),\n ],\n },\n})\n```\n\nExample for a component:\n\n```\n\n \n \n \n\nimport ArrowLeft from '../assets/svg/arrow-left.svg?component'\n\n```\n\nNote that the `?component` in the end is important, otherwise TS will complain.\n\nPlugin Documentation: vite-svg-loader\n\n========================================\n\nCode:\n```text\nsetup(props) {\n        const currentIcon = computed(() => {\n            return defineAsyncComponent(() =>\n                import(`~/assets/images/icons/push-icon-chatops.svg'?inline`)\n            );\n        }).value;\n\n        return {\n            currentIcon,\n        };\n    },\n```\n\n```text\n<img src=\"~/assets/images/icons/push-icon-chatops.svg\" />\n```\n\n```text\n<div v-html=\"rawNuxtLogo\" />\n```\n\n```text\nvite: {\n    plugins: [\n        svgLoader()\n    ]\n},\n```\n\n```text\n@nuxtjs/svg\n```\n\n```text\nimport svgLoader from 'vite-svg-loader'\n\nexport default defineNuxtConfig({\n  // Rest of your config.\n  vite: {\n    plugins: [\n      svgLoader({\n       // Your settings.\n      }),\n    ],\n  },\n})\n```\n\n```text\n<template>\n  <div>\n    <ArrowLeft />\n  </div>\n</template>\n\n<script setup lang=\"ts\">\nimport ArrowLeft from '../assets/svg/arrow-left.svg?component'\n</script>\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\n?component\n```\n\n```js\n<template>\n        <span v-html=\"icon\" />\n    </template>\n\n    <script lang=\"ts\" setup>\n       import { filename } from 'pathe/utils';\n      \n       const props = defineProps<{\n            icon: string;\n        }>();\n    \n       // Auto-load icons as raw\n       const glob = import.meta.glob('~/assets/*.svg', { as: 'raw' });\n       const images = Object.fromEntries(\n       Object.entries(glob)\n         .map(([key, value]: [string, any]) => [filename(key), value]))\n    \n       // Lazily load the icon\n       const icon = props.icon && (await images?.[props.icon]?.());\n    </script>\n```\n\n```text\nvite-svg-loader\n```\n\n```text\nnuxt-svgo\n```\n\n```text\n<template>\n  <component :is=\"icon\" />\n</template>\n\n<script setup>\nimport { defineAsyncComponent } from 'vue'\n\nconst props = defineProps({\n  name: {\n    type: String,\n    default: 'logo'\n  }\n})\n\nconst icons = import.meta.glob(`@/**/*.svg`)\n\nconst icon = computed(() => {\n  return defineAsyncComponent(() => {\n    return icons[`/assets/images/icons/${props.name}.svg`]()\n  })\n})\n\n</script>\n```\n\n```text\n<script lang=\"ts\" setup>\nimport { onMounted } from 'vue'\n\nconst props = defineProps<{ url: string }>()\nconst svgString = ref('')\n\nonMounted(() => {\n  fetch(props.url)\n    .then(response => response.text())\n    .then((svg) => {\n      const parser = new DOMParser()\n      const doc = parser.parseFromString(svg, 'image/svg+xml')\n      const svgElement = doc.documentElement\n      const svgContainer = document.createElement('div')\n      svgContainer.appendChild(svgElement)\n      svgString.value = svgContainer.innerHTML\n    })\n  })\n</script>\n<template>\n  <div v-html=\"svgString\" />\n</template>\n```\n\n========================================\n\nComments:\n- Does this answer your question? How to include inline .svg in Nuxt application\n- @bitski so that was one of the items i looked at. require doesnt work in vite so i had to do that dynamic import bit, however it doesnt seem to work\n- Could have given a try to nuxt-svgo but overall, a Vite plugin is also what I achieved for a friend few months ago and it works great! Please accept your answer when you will be able to.\n- how change size when using this?\n- @AlauddinAfifCassandra - if you mean the actual size of the SVG on the screen, that is done in the HTML/CSS. This answer only has to do with how you load the SVG file.\n- How would this work for dynamic imports? I have `` in template and then `icon.value = import(`~&#47;assets&#47;icons&#47;${props.name}.svg`)` and I am getting `Uncaught (in promise) TypeError: Failed to resolve module specifier '~&#47;assets&#47;icons&#47;arrow-up.svg'`\n- it's always advisable to put the actual content, instead of a link to the answers(s). A link might not exist sin future.\n- Making a call + using non-sanitized flow tho. Lots of overhead for the client-side for no obvious benefit IMO.\n- Yes, for in-place assets probably the SVG loader is better, but if you need to load the images from a provider and need to use different colors on them you don't have a lot of options. You can use dompurify (or similar node module) for sanitizing\n- Yeah, I tend to use Iconify for any local projects nowadays. If you need to stream and inject those into your projects, that's probably the way indeed. Not optimal for sure but dirty workaround that could make the job.","metadata":{"transformedAt":"2026-08-18T18:33:46.418Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":234,"estimatedTokens":1415}}319{"id":"stack-76190074","source":"stackoverflow","questionId":76190074,"title":"How to add custom service worker to Nuxt 3 with vite-pwa?","tags":["nuxt.js","progressive-web-apps","vite","nuxt3.js"],"text":"Title: How to add custom service worker to Nuxt 3 with vite-pwa?\nTags: nuxt.js, progressive-web-apps, vite, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to glue together a Nuxt 3 PWA with `vite-plugin-pwa`, more specifically `@vite-pwa/nuxt`. I installed the module and set up basic configuration (I basically followed this video)\n\n### What I want\n\nThe first feature I would like to implement is sending Push Notifications to users at fixed time. They should receive the Push Notifications even if they are not in the app. That's why I added the PWA module.\n\n### What I do not understand\n\n**I don't know how to add my custom service worker.** If I understand it correctly, I could write a service worker, that just sends Push Notifications with the Notification API to my app. No need for services like OneSignal (right?).\n\nAs I understand the documentation Vite PWA uses google's workbox under the hood and per default it generates a service worker. If you set `injectRegister: 'script'` it should inject a service worker registration in the head of my app (like described here).\n\nNow when I search the source code via the developer tools I cannot find any serviceWorker script. Strangely enough, when I go to the application tab in the dev tools, I can see that a service worker `dev-sw.js` is registered. **How did this get added?**\n\n​\n\nI think I have to set a mode in the configuration to tell workbox not to generate the service worker registration for me. This mode should be called injectManifest, as described here and here. But again, how do I add this to my code?\n\nAs suggested in the documentation I also had a look at the elk repo. But unfortunately they take a different approach and currently do not use vite-pwa/nuxt.\n\n**How can I add my custom service worker to send push notifications?**\n\n**Does anybody have experience with PWAs in Nuxt 3 and specifically working with service workers and sending Push Notifications?**\n\n========================================\n\nCode:\n```text\nvite-plugin-pwa\n```\n\n```text\n@vite-pwa/nuxt\n```\n\n```text\ninjectRegister: 'script'\n```\n\n```text\ndev-sw.js\n```\n\n```js\nimport { clientsClaim } from 'workbox-core'\nimport { precacheAndRoute, cleanupOutdatedCaches, createHandlerBoundToURL } from 'workbox-precaching';\nimport { registerRoute, NavigationRoute } from 'workbox-routing';\n\nself.skipWaiting();\nclientsClaim();\nprecacheAndRoute(self.__WB_MANIFEST);\ncleanupOutdatedCaches();\n\n//You can remove this code if you aren't precaching anything, or leave it in and live with the warning message\ntry {\n    const handler = createHandlerBoundToURL('/');\n    const route = new NavigationRoute(handler);\n    registerRoute(route);\n} catch (error) {\n    console.warn('Error while registering cache route', { error });\n}\n\n//Your service-worker code here.\n```\n\n```text\nvite-pwa\n```\n\n```text\n@vite-pwa/nuxt\n```\n\n```text\nworkbox-core\n```\n\n```text\nworkbox-precaching\n```\n\n```text\nworkbox-routing\n```\n\n```text\nsw.js\n```\n\n```text\npublic\n```\n\n```text\npwa.strategies\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\ninjectManifest\n```\n\n```text\n@vite-pwa/nuxt\n```\n\n```text\ndev-sw.js\n```\n\n```text\ndev-sw.js\n```\n\n```text\n@vite-pwa/nuxt\n```\n\n```text\npwa\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\n/sw.js\n```\n\n========================================\n\nComments:\n- I have the same question. Did you find a solution for this?\n- Thanks for figuring this out - worked for me!\n- THANK YOU! I just spent all day trying to work this out, stumbling across this post was a small miracle. Many thanks! 🙏","metadata":{"transformedAt":"2026-08-18T18:33:46.418Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":144,"estimatedTokens":879}}320{"id":"stack-77074274","source":"stackoverflow","questionId":77074274,"title":"How to suppress Bootstrap 5.3.1 deprecation warning for global abs() function when compiling scss with Vite?","tags":["npm","sass","bootstrap-5","vite","deprecation-warning"],"text":"Title: How to suppress Bootstrap 5.3.1 deprecation warning for global abs() function when compiling scss with Vite?\nTags: npm, sass, bootstrap-5, vite, deprecation-warning\nSource: Stack Overflow\n\nQuestion:\nI am trying to suppress a `Deprecation Warning` for `global abs() function` when compiling `Bootstrap 5.3.1` scss using `Vite` with npm.\n\n*I am using `node v16.20.2` and `npm 8.19.4` because this is the highest node version which my macOS system will let me install. However, even though I am using an outdated version of node `@16`, I am still able to use the latest npm `sass`, `vite` and `bootstrap` packages.*\n\nSee my full `package.json` config below...\n\n```\n{\n \"private\": true,\n \"scripts\": {\n \"dev\": \"vite\",\n \"watch\": \"npm run dev\",\n \"build\": \"vite build\",\n \"production\": \"vite build\"\n },\n \"devDependencies\": {\n \"laravel-vite-plugin\": \"^0.8.0\",\n \"sass\": \"1.66.1\",\n \"vite\": \"^4.4.9\"\n },\n \"dependencies\": {\n \"bootstrap\": \"^5.3.1\"\n }\n}\n```\n\nHere is my `vite.config.js` if anyone wants to test after installing this npm package above...\n\n```\nimport {defineConfig} from \"vite\";\nimport laravel from 'laravel-vite-plugin';\n\nexport default defineConfig(() => ({\n base: '',\n build: {\n emptyOutDir: true,\n manifest: true,\n outDir: 'build',\n assetsDir: 'assets'\n },\n plugins: [\n laravel({\n publicDirectory: 'build',\n input: [\n 'resources/scss/theme.scss'\n ],\n refresh: [\n '**.php'\n ]\n })\n ],\n resolve: {\n alias: [\n {\n find: /~(.+)/,\n replacement: process.cwd() + '/node_modules/$1'\n },\n ]\n }\n}));\n```\n\nHere is my `theme.scss` code below, which is taken from `Option A` in Bootstrap 5.3 Customize SASS docs...\n\n```\n// Option A: Include all of Bootstrap\n@import \"../node_modules/bootstrap/scss/bootstrap\";\n```\n\n*I also get the same `Deprecated Warning` below when using `Option B` in Bootstrap 5.3 Customize SASS docs.*\n\nOk so when I compile my `theme.scss` using the npm and Vite configuration above, this is the `Deprecation Warning` outputted in the full Vite log...\n\n```\n10:47:58 PM [vite] hmr update /resources/scss/theme.scss?direct (x8)\nDeprecation Warning: Passing percentage units to the global abs() function is deprecated.\nIn the future, this will emit a CSS abs() function to be resolved by the browser.\nTo preserve current behavior: math.abs(100%)\nTo emit a CSS abs() now: abs(#{100%})\nMore info: https://sass-lang.com/d/abs-percent\n\n ╷\n57 │ $dividend: abs($dividend);\n │ ^^^^^^^^^^^^^^\n ╵\n node_modules/bootstrap/scss/vendor/_rfs.scss 57:14 divide()\n node_modules/bootstrap/scss/mixins/_grid.scss 59:12 row-cols()\n node_modules/bootstrap/scss/mixins/_grid.scss 85:13 @content\n node_modules/bootstrap/scss/mixins/_breakpoints.scss 68:5 media-breakpoint-up()\n node_modules/bootstrap/scss/mixins/_grid.scss 72:5 make-grid-columns()\n node_modules/bootstrap/scss/_grid.scss 38:3 @import\n node_modules/bootstrap/scss/bootstrap.scss 20:9 @import\n resources/scss/theme.scss 2:9 root stylesheet\n```\n\nI've tried suppressing the warning using sass variable shown below, placed at the top of my `theme.scss`, but this doesn't suppress `Deprecation Warning`...?\n\n```\n// Suppress Sass deprecation warning\n$deprecation-warning-threshold: false;\n\n// Option A: Include all of Bootstrap\n@import \"../node_modules/bootstrap/scss/bootstrap\";\n```\n\nI've found this related issue posted on the official Bootstrap github repo...\n\n- https://github.com/twbs/bootstrap/issues/39028\n\nBut from what I can make out in this issue page, people are suggesting manually changing code in the `node_modules` directory...\n\n- In `node_modules/bootstrap/scss/vendor/_rfs.scss` file, add to top: `@use 'sass:math';`\n\n- In line error, replace: `$dividend: abs($dividend);` to `$dividend: math.abs($dividend);`\n\nI would rather not do this as I am not committing the `node_modules` directory to my project repo.\n\nIs there any other possible way to suppress this `Deprecation Warning` from my Vite log when compiling `theme.scss` with `npm run build` and `npm run dev` hot replacement module?\n\nAny ideas would be much appreciated, thanks!\n\n========================================\n\nTop Answer:\nFWIW I'm using bootstrap 5.3.3 with vite 5.4.8 and node 20.18. I was getting a bajillion deprecation warnings with recent sass versions.\n\nI tried 1.64 as suggested above but this gave me an error `sass.initAsyncCompiler is not a function` (presumably because I'm using a newer vite version)\n\nlooking in the sass release notes I see this function was introduced in 1.70 so I switched to that version and now I seem to be up and running with no deprecation warnings.\n\n========================================\n\nCode:\n```json\n{\n  \"private\": true,\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"watch\": \"npm run dev\",\n    \"build\": \"vite build\",\n    \"production\": \"vite build\"\n  },\n  \"devDependencies\": {\n    \"laravel-vite-plugin\": \"^0.8.0\",\n    \"sass\": \"1.66.1\",\n    \"vite\": \"^4.4.9\"\n  },\n  \"dependencies\": {\n    \"bootstrap\": \"^5.3.1\"\n  }\n}\n```\n\n```js\nimport {defineConfig} from \"vite\";\nimport laravel from 'laravel-vite-plugin';\n\nexport default defineConfig(() => ({\n    base: '',\n    build: {\n        emptyOutDir: true,\n        manifest: true,\n        outDir: 'build',\n        assetsDir: 'assets'\n    },\n    plugins: [\n        laravel({\n            publicDirectory: 'build',\n            input: [\n                'resources/scss/theme.scss'\n            ],\n            refresh: [\n                '**.php'\n            ]\n        })\n    ],\n    resolve: {\n        alias: [\n            {\n                find: /~(.+)/,\n                replacement: process.cwd() + '/node_modules/$1'\n            },\n        ]\n    }\n}));\n```\n\n```scss\n// Option A: Include all of Bootstrap\n@import \"../node_modules/bootstrap/scss/bootstrap\";\n```\n\n```log\n10:47:58 PM [vite] hmr update /resources/scss/theme.scss?direct (x8)\nDeprecation Warning: Passing percentage units to the global abs() function is deprecated.\nIn the future, this will emit a CSS abs() function to be resolved by the browser.\nTo preserve current behavior: math.abs(100%)\nTo emit a CSS abs() now: abs(#{100%})\nMore info: https://sass-lang.com/d/abs-percent\n\n   ╷\n57 │   $dividend: abs($dividend);\n   │              ^^^^^^^^^^^^^^\n   ╵\n    node_modules/bootstrap/scss/vendor/_rfs.scss 57:14         divide()\n    node_modules/bootstrap/scss/mixins/_grid.scss 59:12        row-cols()\n    node_modules/bootstrap/scss/mixins/_grid.scss 85:13        @content\n    node_modules/bootstrap/scss/mixins/_breakpoints.scss 68:5  media-breakpoint-up()\n    node_modules/bootstrap/scss/mixins/_grid.scss 72:5         make-grid-columns()\n    node_modules/bootstrap/scss/_grid.scss 38:3                @import\n    node_modules/bootstrap/scss/bootstrap.scss 20:9            @import\n    resources/scss/theme.scss 2:9                              root stylesheet\n```\n\n```scss\n// Suppress Sass deprecation warning\n$deprecation-warning-threshold: false;\n\n// Option A: Include all of Bootstrap\n@import \"../node_modules/bootstrap/scss/bootstrap\";\n```\n\n```text\nDeprecation Warning\n```\n\n```text\nglobal abs() function\n```\n\n```text\nBootstrap 5.3.1\n```\n\n```text\nVite\n```\n\n```text\nnode v16.20.2\n```\n\n```text\nnpm 8.19.4\n```\n\n```text\n@16\n```\n\n```text\nsass\n```\n\n```text\nvite\n```\n\n```text\nbootstrap\n```\n\n```text\npackage.json\n```\n\n```text\nvite.config.js\n```\n\n```text\ntheme.scss\n```\n\n```text\nOption A\n```\n\n```text\nDeprecated Warning\n```\n\n```text\nOption B\n```\n\n```text\ntheme.scss\n```\n\n```text\nDeprecation Warning\n```\n\n```text\ntheme.scss\n```\n\n```text\nDeprecation Warning\n```\n\n```text\nnode_modules\n```\n\n```text\nnode_modules/bootstrap/scss/vendor/_rfs.scss\n```\n\n```text\n@use 'sass:math';\n```\n\n```text\n$dividend: abs($dividend);\n```\n\n```text\n$dividend: math.abs($dividend);\n```\n\n```text\nnode_modules\n```\n\n```text\nDeprecation Warning\n```\n\n```text\ntheme.scss\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm run dev\n```\n\n```json\n{\n  \"private\": true,\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"watch\": \"npm run dev\",\n    \"build\": \"vite build\",\n    \"production\": \"vite build\"\n  },\n  \"devDependencies\": {\n    \"laravel-vite-plugin\": \"^0.8.0\",\n    \"sass\": \"~1.64.2\",\n    \"vite\": \"^4.4.9\"\n  },\n  \"dependencies\": {\n    \"bootstrap\": \"^5.3.1\"\n  }\n}\n```\n\n```text\nsass\n```\n\n```text\n~1.64.2\n```\n\n```text\nDeprecation Warning\n```\n\n```text\n~\n```\n\n```text\nnpm update\n```\n\n```text\nsass.initAsyncCompiler is not a function\n```\n\n========================================\n\nComments:\n- I think you should just be patient: github.com/twbs/bootstrap/pull/39030#issuecomment-1705970985","metadata":{"transformedAt":"2026-08-18T18:33:46.418Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":42,"totalLines":395,"estimatedTokens":2100}}321{"id":"stack-72012643","source":"stackoverflow","questionId":72012643,"title":"Why aren't the Tailwind classes taking effect in my Vite React project?","tags":["reactjs","tailwind-css","postcss","vite"],"text":"Title: Why aren't the Tailwind classes taking effect in my Vite React project?\nTags: reactjs, tailwind-css, postcss, vite\nSource: Stack Overflow\n\nQuestion:\nI have a Vite React project that uses Tailwind via PostCSS. However, none of the classes are reflecting the the localhost. Below are the files in the project:\n\n**postcss.config.js:**\n\n```\nmodule.exports = {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n }\n}\n```\n\n**tailwind.config.js:**\n\n```\nmodule.exports = {\n content: [\"./src/**/*.{html,js}\"],\n theme: {\n extend: {},\n },\n plugins: [],\n}\n```\n\n**App.js:**\n\n```\nconst App = () => {\n return (\n \n \n Hello world!\n \n \n )\n}\nexport default App\n```\n\nThis was all done following the instructions in the Tailwind documentation at https://tailwindcss.com/docs/installation/using-postcss.\n\nWhy doesn't it work?\n\n========================================\n\nTop Answer:\nThe reason for the error can be Unknown at rule @tailwindcss\n\nTo solve this you must download this extension\n\n========================================\n\nCode:\n```js\nmodule.exports = {\n    plugins: {\n        tailwindcss: {},\n        autoprefixer: {},\n    }\n}\n```\n\n```js\nmodule.exports = {\n  content: [\"./src/**/*.{html,js}\"],\n  theme: {\n    extend: {},\n  },\n  plugins: [],\n}\n```\n\n```text\nconst App = () => {\n  return (\n    <div className=\"App\">\n      <h1 class=\"text-3xl font-bold underline\">\n        Hello world!\n      </h1>\n    </div>\n  )\n}\nexport default App\n```\n\n```js\nmodule.exports = {\n  content: [\"./src/**/*.{html,js,jsx}\"],\n  theme: {\n    extend: {},\n  },\n  plugins: [],\n}\n```\n\n```text\ntailwind.config.js\n```\n\n```text\n{html,js} => {html,js,jsx}\n```\n\n========================================\n\nComments:\n- The problem is likely your filenames. They contain JSX so they should have the `.jsx` file extension (a new Vite + React scaffolded project would warn about this). Also, the Tailwind `content` config should include `.jsx`. See demo.","metadata":{"transformedAt":"2026-08-18T18:33:46.418Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":113,"estimatedTokens":477}}322{"id":"stack-76545817","source":"stackoverflow","questionId":76545817,"title":"Vite clears the terminal when I run npm run dev","tags":["vite"],"text":"Title: Vite clears the terminal when I run npm run dev\nTags: vite\nSource: Stack Overflow\n\nQuestion:\nI'm using `vite.config.js` to dynamically create some configurations. To debug it I use `console.log` to print some data.\n\nHowever, when I run `npm run dev` vite runs the program very fast, and then clears the entire screen including my logs.\n\nHow can I prevent it from doing that?\n\n========================================\n\nTop Answer:\nAlternatively, in `vite.config.js`:\n\n```\nexport default defineConfig({\n clearScreen: false,\n ...\n```\n\n========================================\n\nCode:\n```text\nvite.config.js\n```\n\n```text\nconsole.log\n```\n\n```text\nnpm run dev\n```\n\n```text\n--clearScreen false\n```\n\n```text\nexport default defineConfig({\n  clearScreen: false,\n  ...\n```\n\n```text\nvite.config.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.418Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":50,"estimatedTokens":199}}323{"id":"stack-69961761","source":"stackoverflow","questionId":69961761,"title":"React.js builds with Vite does not include service-worker.ts","tags":["javascript","reactjs","typescript","vite"],"text":"Title: React.js builds with Vite does not include service-worker.ts\nTags: javascript, reactjs, typescript, vite\nSource: Stack Overflow\n\nQuestion:\nI am using Vite to build an SPA with React (typescript), and I am trying to register a service-worker. I am registering the script as type `module`, and `service-worker.ts` sits at `src/web-worker/service-worker.ts`. There is also a **tsconfig.json** at `src/web-worker`\n\nEverything works in Dev, but when it's built, `src/web-worker/service-worker.ts is not replaced with anything equivalent`.\n\nAny suggestions?\n\n**index.html**\n\n```\n\n \n \n \n \n Vite App\n\n \n \n \n if ('serviceWorker' in navigator) {\n (async () => {\n await navigator.serviceWorker.register(\"src/web-worker/service-worker.ts\", { type: 'module' })\n console.log(\"Service worker registered\")\n })()\n }\n \n\n```\n\n**src/web-worker/service-worker.ts**\n\n```\n// Constants\nconst CACHE_NAME = 'mycache-v1.0.0'\nconst urlsToCache = ['/']\n\ndeclare const self: ServiceWorkerGlobalScope;\n\nself.addEventListener('install', async (event: ExtendableEvent) => {\n try {\n // Create (open) cache\n const cache = await caches.open(CACHE_NAME)\n await cache.addAll(urlsToCache)\n console.log(\"Cache opened\")\n } catch (err: any) {\n console.log(\"Error while installing SW: \", err.message)\n }\n})\n\nself.addEventListener('fetch', (e: FetchEvent) => {\n e.respondWith((async () => {\n // Handling fetch\n console.log(`Handling req for '${e.request.url}'`)\n const cachedRes = await caches.match(e.request, { cacheName: CACHE_NAME })\n if (cachedRes) {\n console.log(`Serving cached response for '${e.request.url}'`)\n }\n return cachedRes || await fetch(e.request)\n })())\n})\n\nexport default null\n```\n\n**src/web-worker/tsconfig.json**\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"ESNext\",\n \"useDefineForClassFields\": true,\n \"lib\": [\"ESNext\", \"WebWorker\"],\n \"allowJs\": false,\n \"skipLibCheck\": false,\n \"esModuleInterop\": false,\n \"allowSyntheticDefaultImports\": true,\n \"strict\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Node\",\n \"resolveJsonModule\": true,\n \"isolatedModules\": true,\n \"noEmit\": true,\n },\n \"include\": [\"*.ts\"]\n}\n```\n\n========================================\n\nCode:\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n  <meta charset=\"UTF-8\" />\n  <link rel=\"icon\" type=\"image/svg+xml\" href=\"/src/favicon.svg\" />\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n  <link rel=\"stylesheet\" href=\"/src/styles/globals.css\">\n  <title>Vite App</title>\n</head>\n\n<body>\n  <div id=\"root\"></div>\n  <script type=\"module\" src=\"/src/main.tsx\"></script>\n  <script type=\"text/javascript\">\n    if ('serviceWorker' in navigator) {\n      (async () => {\n        await navigator.serviceWorker.register(\"src/web-worker/service-worker.ts\", { type: 'module' })\n        console.log(\"Service worker registered\")\n      })()\n    }\n  </script>\n</body>\n\n</html>\n```\n\n```text\n// Constants\nconst CACHE_NAME = 'mycache-v1.0.0'\nconst urlsToCache = ['/']\n\ndeclare const self: ServiceWorkerGlobalScope;\n\nself.addEventListener('install', async (event: ExtendableEvent) => {\n    try {\n        // Create (open) cache\n        const cache = await caches.open(CACHE_NAME)\n        await cache.addAll(urlsToCache)\n        console.log(\"Cache opened\")\n    } catch (err: any) {\n        console.log(\"Error while installing SW: \", err.message)\n    }\n})\n\nself.addEventListener('fetch', (e: FetchEvent) => {\n    e.respondWith((async () => {\n        // Handling fetch\n        console.log(`Handling req for '${e.request.url}'`)\n        const cachedRes = await caches.match(e.request, { cacheName: CACHE_NAME })\n        if (cachedRes) {\n            console.log(`Serving cached response for '${e.request.url}'`)\n        }\n        return cachedRes || await fetch(e.request)\n    })())\n})\n\nexport default null\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"ESNext\", \"WebWorker\"],\n    \"allowJs\": false,\n    \"skipLibCheck\": false,\n    \"esModuleInterop\": false,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n  },\n  \"include\": [\"*.ts\"]\n}\n```\n\n```text\nmodule\n```\n\n```text\nservice-worker.ts\n```\n\n```text\nsrc/web-worker/service-worker.ts\n```\n\n```text\nsrc/web-worker\n```\n\n```text\nsrc/web-worker/service-worker.ts is not replaced with anything equivalent\n```\n\n========================================\n\nComments:\n- You can try to register service worker with .js extension, and build with tsc before (or concurrent) dev and build scripts. There may be a Vite plugin that solves this problem, but I haven't found one yet.","metadata":{"transformedAt":"2026-08-18T18:33:46.418Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":203,"estimatedTokens":1189}}324{"id":"stack-78577207","source":"stackoverflow","questionId":78577207,"title":"TypeScript › Update Imports On File Move: Enabled not working in VS Code","tags":["reactjs","typescript","visual-studio-code","vite"],"text":"Title: TypeScript › Update Imports On File Move: Enabled not working in VS Code\nTags: reactjs, typescript, visual-studio-code, vite\nSource: Stack Overflow\n\nQuestion:\nI've been encountering an issue with Visual Studio Code where the **'TypeScript › Update Imports On File Move: Enabled'** setting seems to no longer work as expected.\n\nPreviously, I could move a file and the import path would automatically update. However, now it doesn't update despite having the setting configured to '**prompt**'. Instead, I have to manually update the file path. After doing so, the filepath is underlined in red and I get the following error:\n\n```\nCannot find module '@example-path-1' or its corresponding type declarations.ts(2307)\n```\n\nTo fix this, I have to restart the TypeScript server for the path to be recognised correctly.\n\nHere's what I've checked so far:\n\n- The settings in both my user and workspace settings don't conflict.\n\n- Changing the settings from **'prompt'** to **'always'**.\n\n- Restarted Visual Studio Code.\n\n- Restarted TypeScript server.\n\n- Cleared TypeScript cache.\n\nI am using Vite, TypeScript, and React.\nI manage absolute paths using **tsconfigPaths** in my **'vite.config.ts'**.\nThe paths are set up in my **'tsconfig.json'** using ./src as the baseUrl:\n\n```\n{\n \"compilerOptions\": {\n \"baseUrl\": \"./src\",\n \"paths\": {\n \"@example-path-1/*\": [\"./features/example-path-1/*\"],\n \"@example-path-2/*\": [\"./features/example-path-2/*\"]\n }\n ...// rest\n }\n}\n```\n\nEverything was working fine until recently and I'm unsure why it has suddenly stopped functioning as expected.\n\nAny suggestions or insights on how to resolve this would be greatly appreciated!\n\nThanks in advance\n\n========================================\n\nTop Answer:\nJust try doing cmd+, for `macOS`, then type update Imports on File Move\nthen update the setting to always, this will allow your VS Code to understand the changes and update without additional prompts. Work through the above flow and this should work.\n\n========================================\n\nCode:\n```text\nCannot find module '@example-path-1' or its corresponding type declarations.ts(2307)\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"baseUrl\": \"./src\",\n    \"paths\": {\n      \"@example-path-1/*\": [\"./features/example-path-1/*\"],\n      \"@example-path-2/*\": [\"./features/example-path-2/*\"]\n    }\n  ...// rest\n  }\n}\n```\n\n```text\nmacOS\n```\n\n========================================\n\nComments:\n- You literally saved my life <3\n- @Elsa, no worries! What version of visual code were you using before you downgraded?\n- I believe that the last one available (VSCode 1.92) in MacOS. My office colleagues were facing the same problem and now grateful :)\n- @Elsa, thanks I've raised it as an issue on GitHub, so hopefully, it will get resolved soon 🤞","metadata":{"transformedAt":"2026-08-18T18:33:46.418Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":87,"estimatedTokens":694}}325{"id":"stack-79391628","source":"stackoverflow","questionId":79391628,"title":"Unable to upgrade Tailwind CSS v3 to v4","tags":["reactjs","migration","tailwind-css","vite","tailwind-css-4"],"text":"Title: Unable to upgrade Tailwind CSS v3 to v4\nTags: reactjs, migration, tailwind-css, vite, tailwind-css-4\nSource: Stack Overflow\n\nQuestion:\nI am unable to upgrade my old vite React project with **Tailwind CSS v3** to **Tailwind CSS v4** by using the below command:\n\n`npx @tailwindcss/upgrade@next`\n\nThe terminal output screenshot:\n\nError Message\n\nAt first I was using the command:\n\n`npx @tailwindcss/upgrade@next`\n\nbut it was showing something related to git cache clear warn message. That's a different thing; thats why I have used `--force` after the command:\n\n`npx @tailwindcss/upgrade@next --force`\n\nAlso, it was running without `--force` itself.\nBut the problem is that it's showing the error:\n\n`↳ Could not load the configuration file: Can't resolve`\n\nas per the above screenshot.\n\nI will really appreciate it if anyone can help me regarding this issue, as I am unable to convert all of my old tailwind css react vite projects.\n\n========================================\n\nCode:\n```text\nnpx @tailwindcss/upgrade@next\n```\n\n```text\nnpx @tailwindcss/upgrade@next\n```\n\n```text\n--force\n```\n\n```text\nnpx @tailwindcss/upgrade@next --force\n```\n\n```text\n--force\n```\n\n```text\n↳ Could not load the configuration file: Can't resolve\n```\n\n```text\npath.relative(…)\n```\n\n```text\n./\n```\n\n```text\nfile.relative(…)\n```\n\n```text\n./\n```\n\n========================================\n\nComments:\n- Did you end up Using Windows Subsystem for Linux to get this working? Or how did you end up resolving it?\n- Now fixed in #15927.","metadata":{"transformedAt":"2026-08-18T18:33:46.418Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":78,"estimatedTokens":377}}326{"id":"stack-70810378","source":"stackoverflow","questionId":70810378,"title":"How to use proxy with vite (vue frontend) and django rest framework","tags":["javascript","django","vue.js","django-rest-framework","vite"],"text":"Title: How to use proxy with vite (vue frontend) and django rest framework\nTags: javascript, django, vue.js, django-rest-framework, vite\nSource: Stack Overflow\n\nQuestion:\nSo, you know when you access a view with django rest api on the browser, you get an html page, and when you send something like an ajax request, you get the json? I'm trying to figure out how to mess with the proxy setting for vite, but I can't find a single decent documentation around it. I want to redirect '/' to 'http://localhost:8000/api', but there's really weird behavior going on.\nIf I have a route on localhost:8000/api, I can do:\n\n```\n//vite.config.js\nexport default defineConfig({\n plugins: [vue()],\n server: {\n proxy: {\n //Focus here\n '/api': {\n target: 'http://localhost:8000',\n changeOrigin: true,\n rewrite: (path) => { console.log(path); return path.replace('/^\\/api/', '') }\n }\n }\n }\n})\n```\n\n```\n//todo-component.vue\nexport default {\n data() {\n return {\n todos: []\n }\n },\n components: {\n TodoElement\n },\n beforeCreate() {\n //Focus here as well \n this.axios.get('/api').then((response) => {\n this.todos = response.data\n })\n .catch((e) => {\n console.error(e)\n })\n }\n\n}\n```\n\nThis will return the json response as expected. However, if I try to make it so that '/' routes to 'localhost:8000/api/', like this:\n\n```\nexport default defineConfig({\n plugins: [vue()],\n server: {\n proxy: {\n //change here\n '/': {\n target: 'http://localhost:8000/api',\n changeOrigin: true,\n rewrite: (path) => { console.log(path); return path.replace('/^\\/api/', '') }\n }\n }\n }\n})\n```\n\n```\nimport TodoElement from \"./todo-element.vue\"\nexport default {\n data() {\n return {\n todos: []\n }\n },\n components: {\n TodoElement\n },\n beforeCreate() {\n //change here\n this.axios.get('/').then((response) => {\n this.todos = response.data\n })\n .catch((e) => {\n console.error(e)\n })\n }\n\n}\n```\n\nIt just spews out the html version of the api view, but with no styling, with a bunch of errors\n\nNo idea what to do. If someone could explain how this proxy works, i'd really love it. I don't want to keep writing \"api/\", and it'd be really valuable if I can manage to understand how this works.\n\n========================================\n\nCode:\n```js\n//vite.config.js\nexport default defineConfig({\n    plugins: [vue()],\n    server: {\n        proxy: {\n            //Focus here\n            '/api': {\n                target: 'http://localhost:8000',\n                changeOrigin: true,\n                rewrite: (path) => { console.log(path); return path.replace('/^\\/api/', '') }\n            }\n        }\n    }\n})\n```\n\n```js\n//todo-component.vue\nexport default {\n    data() {\n        return {\n            todos: []\n        }\n    },\n    components: {\n        TodoElement\n    },\n    beforeCreate() {\n                       //Focus here as well \n        this.axios.get('/api').then((response) => {\n            this.todos = response.data\n        })\n            .catch((e) => {\n                console.error(e)\n            })\n    }\n\n}\n```\n\n```js\nexport default defineConfig({\n    plugins: [vue()],\n    server: {\n        proxy: {\n            //change here\n            '/': {\n                target: 'http://localhost:8000/api',\n                changeOrigin: true,\n                rewrite: (path) => { console.log(path); return path.replace('/^\\/api/', '') }\n            }\n        }\n    }\n})\n```\n\n```js\nimport TodoElement from \"./todo-element.vue\"\nexport default {\n    data() {\n        return {\n            todos: []\n        }\n    },\n    components: {\n        TodoElement\n    },\n    beforeCreate() {\n        //change here\n        this.axios.get('/').then((response) => {\n            this.todos = response.data\n        })\n            .catch((e) => {\n                console.error(e)\n            })\n    }\n\n}\n```\n\n```text\n/\n```\n\n```text\n/api\n```\n\n```text\nhttp://localhost:3000\n```\n\n```text\nhttp://localhost:8000/api\n```\n\n```text\nlocalhost:8000/api\n```\n\n```text\nvite config option (server.proxy)\n```\n\n```text\nfavicon.ico\n```\n\n```text\n/favicon.ico\n```\n\n```text\nhttp://localhost:8000/api/favicon.ico\n```\n\n```text\nhttp://localhost:3000/favicon.ico\n```\n\n```text\n/static/rest_framework\n```\n\n```text\nhttp://localhost:8000/api/\n```\n\n```text\nhttp://localhost:3000/\n```\n\n========================================\n\nComments:\n- Thanks, I understand and i'll give it a look :)","metadata":{"transformedAt":"2026-08-18T18:33:46.418Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":235,"estimatedTokens":1072}}327{"id":"stack-76347160","source":"stackoverflow","questionId":76347160,"title":"How to use vite build use another config file instead of vite.config.js","tags":["vue.js","vite","bundler"],"text":"Title: How to use vite build use another config file instead of vite.config.js\nTags: vue.js, vite, bundler\nSource: Stack Overflow\n\nQuestion:\n`vite build` uses the `vite.config.js` to build the bundle, what if I have a `my.config.js`, how can I tell `vite build` to run this config instead of `vite.config.js`\n\n========================================\n\nCode:\n```text\nvite build\n```\n\n```text\nvite.config.js\n```\n\n```text\nmy.config.js\n```\n\n```text\nvite build\n```\n\n```text\nvite.config.js\n```\n\n```text\nvite build --config my.config.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.418Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":33,"estimatedTokens":133}}328{"id":"stack-77864851","source":"stackoverflow","questionId":77864851,"title":"Why do I get \"npm ERR! code ENOENT\" when trying to install shadcn ui","tags":["reactjs","forms","vite","npm-install","shadcnui"],"text":"Title: Why do I get \"npm ERR! code ENOENT\" when trying to install shadcn ui\nTags: reactjs, forms, vite, npm-install, shadcnui\nSource: Stack Overflow\n\nQuestion:\nI am creating a small project with vite and I keep getting this error when I try to run `npx shadcn-ui@latest init`:\n\n```\nnpm ERR! code ENOENT\nnpm ERR! syscall lstat\nnpm ERR! path C:\\Users\\user\\AppData\\Roaming\\npm\nnpm ERR! errno -4058\nnpm ERR! enoent ENOENT: no such file or directory, lstat 'C:\\Users\\user\\AppData\\Roaming\\npm'\nnpm ERR! enoent This is related to npm not being able to find a file.\nnpm ERR! enoent\n```\n\n========================================\n\nTop Answer:\nCreate a folder `npm` in `C:\\Users\\user-name\\AppData\\Roaming`, and then redo the command.\n\nThis allows the package to be seen in files it runs through.\n\n========================================\n\nCode:\n```text\nnpm ERR! code ENOENT\nnpm ERR! syscall lstat\nnpm ERR! path C:\\Users\\user\\AppData\\Roaming\\npm\nnpm ERR! errno -4058\nnpm ERR! enoent ENOENT: no such file or directory, lstat 'C:\\Users\\user\\AppData\\Roaming\\npm'\nnpm ERR! enoent This is related to npm not being able to find a file.\nnpm ERR! enoent\n```\n\n```text\nnpx shadcn-ui@latest init\n```\n\n```text\nnpx create-next-app@latest my-app --typescript --tailwind --eslint\n```\n\n```text\nnpx shadcn-ui@latest init\n```\n\n```text\nC:\\Users\\user\\AppData\\Roaming\\npm\n```\n\n```text\nnpx shadcn-ui@latest init\n```\n\n```text\nnpm\n```\n\n```text\nC:\\Users\\user-name\\AppData\\Roaming\n```\n\n```text\nnpm install -g npm\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.418Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":68,"estimatedTokens":370}}329{"id":"stack-75006674","source":"stackoverflow","questionId":75006674,"title":"Vitest with element plus unplugin unknown extension for scss","tags":["javascript","vue.js","vuejs3","vite","vitest"],"text":"Title: Vitest with element plus unplugin unknown extension for scss\nTags: javascript, vue.js, vuejs3, vite, vitest\nSource: Stack Overflow\n\nQuestion:\nI'm trying to run tests using Vitest on a Vue.js app that uses Element Plus registered as a plugin.\n\nIf I use `mount` on a component that contains an Element Plus component, I get the following error:\n\n```\nTypeError: Unknown file extension \".scss\" for /home/projects/vitejs-vite-zcdxhn/node_modules/element-plus/theme-chalk/src/button.scss\n```\n\nThe issue can be replicated on this StackBlitz.\n\nMy **vite.config.js** file looks like this:\n\n```\nimport { defineConfig } from 'vite';\nimport vue from '@vitejs/plugin-vue';\nimport ElementPlus from 'unplugin-element-plus/vite';\n\nexport default defineConfig({\n plugins: [vue(), ElementPlus({ useSource: true })],\n});\n```\n\nMy **HelloWorld.vue** component looks like this:\n\n```\n\nimport { ElButton } from 'element-plus';\n\n Hello\n\n```\n\nMy **HelloWorld.spec.js** looks like this:\n\n```\nimport { test, expect } from 'vitest';\nimport HelloWorld from '../HelloWorld.vue';\nimport { mount } from '@vue/test-utils';\n\ntest('hello world test', async () => {\n const wrapper = mount(HelloWorld);\n expect(wrapper.text()).toContain('Hello');\n});\n```\n\nThe seems to be specifically related to the `ElementPlus({ useSource: true })]` \"unplugin\" in `plugins` in **vite.config.js** because when I remove that, the problem goes away.\n\nI've reviewed the docs for the various tools (Element Plus, Vite, Vitest), but I've not been able to find how to get this working.\n\nIs there a custom test config that needs to be applied?\n\n========================================\n\nTop Answer:\nThis issue still happens to me even with vitest 2.1.1 (with error related to css extension)\n\nThe solution is to set the pool option to use vmThreads or vmForks, like this:\n\n```\ntest: {\n pool: \"vmThreads\", \n },\n```\n\nWith this option, the following option `deps.web.transformCss` will be set to true by default, which will resolve the problem\n\n========================================\n\nCode:\n```text\nTypeError: Unknown file extension \".scss\" for /home/projects/vitejs-vite-zcdxhn/node_modules/element-plus/theme-chalk/src/button.scss\n```\n\n```js\nimport { defineConfig } from 'vite';\nimport vue from '@vitejs/plugin-vue';\nimport ElementPlus from 'unplugin-element-plus/vite';\n\nexport default defineConfig({\n  plugins: [vue(), ElementPlus({ useSource: true })],\n});\n```\n\n```html\n<script setup>\nimport { ElButton } from 'element-plus';\n</script>\n\n<template>\n  <el-button type=\"primary\">Hello</el-button>\n</template>\n```\n\n```js\nimport { test, expect } from 'vitest';\nimport HelloWorld from '../HelloWorld.vue';\nimport { mount } from '@vue/test-utils';\n\ntest('hello world test', async () => {\n  const wrapper = mount(HelloWorld);\n  expect(wrapper.text()).toContain('Hello');\n});\n```\n\n```text\nmount\n```\n\n```text\nElementPlus({ useSource: true })]\n```\n\n```text\nplugins\n```\n\n```text\ndeps.inline: ['element-plus']\n```\n\n```json\nvitest: '^0.34.3'\n```\n\n```text\ndeps: {\n        optimizer: {\n          web: {\n            include: ['element-plus']\n          }\n        }\n      }\n```\n\n```text\ntest: {\n    pool: \"vmThreads\",   \n  },\n```\n\n```text\ndeps.web.transformCss\n```\n\n========================================\n\nComments:\n- I came here because I have the same problem with vuetify and get the deprecation warning as well. Unfortunately using `deps.optimizer.web.include: ['vuetify']` throws a `TypeError: Unknown file extension \".css\"`\n- For me only using `server.deps.inline: ['vuetify']` helped.","metadata":{"transformedAt":"2026-08-18T18:33:46.419Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":154,"estimatedTokens":881}}330{"id":"stack-79163239","source":"stackoverflow","questionId":79163239,"title":"Electron Forge + SerialPort native dependency packaging not working","tags":["electron","vite","electron-builder","electron-forge"],"text":"Title: Electron Forge + SerialPort native dependency packaging not working\nTags: electron, vite, electron-builder, electron-forge\nSource: Stack Overflow\n\nQuestion:\nI am working on an open source firmware update app for Meshtastic (https://github.com/medentem/electron-flasher/). The app is a ReactJS/TS app bundled with Vite for Electron. When running locally on OSX (`electron-forge start`), it functions perfectly and the native dependencies (serialport and drivelist) seem to be referenced properly. However, after bundling the OSX app for distribution (`electron-forge make`), the resulting app launches with this error:\n\n```\nUncaught Exception:\nError: Cannot find module 'serialport'\nRequire stack:\n- /Users/medentem/Dev/electron-flasher/out/electron-flasher-darwin-arm64/electron-flasher.app/Contents/Resources/app.asar/.vite/build/main.js\n- \nat Module._resolveFilename (node:internal/modules/cjs/loader:1232:15)\nat s._resolveFilename (node:electron/js2c/browser_init:2:124038)\nat Module._load (node:internal/modules/cjs/loader:1058:27)\nat c._load (node:electron/js2c/node_init:2:17025)\nat Module.require (node:internal/modules/cjs/loader:1318:19)\nat require (node:internal/modules/helpers:179:18)\nat Object. (/Users/medentem/Dev/electron-flasher/out/electron-flasher-darwin-arm64/electron-flasher.app/Contents/Resources/app.asar/.vite/build/main.js:1:214)\nat Module._compile (node:internal/modules/cjs/loader:1484:14)\nat Module._extensions..js (node:internal/modules/cjs/loader:1564:10)\nat Module.load (node:internal/modules/cjs/loader:1295:32)\n```\n\nI confirmed that the `serialport` and `drivelist` packages are configured in vite as external (see https://github.com/medentem/electron-flasher/blob/main/vite.main.config.ts), and that the `electron-forge` configuration `AutoUnpackNativesPlugin` to ensure both packages are rebuilt and included outside of the asar bundle. But that does not seem to work.\n\nI've also tried to use `electron-builder` to generate the OSX app, but in that case, the app will not even launch.\n\nThank you in advance for any help!\n\n========================================\n\nCode:\n```text\nUncaught Exception:\nError: Cannot find module 'serialport'\nRequire stack:\n- /Users/medentem/Dev/electron-flasher/out/electron-flasher-darwin-arm64/electron-flasher.app/Contents/Resources/app.asar/.vite/build/main.js\n- \nat Module._resolveFilename (node:internal/modules/cjs/loader:1232:15)\nat s._resolveFilename (node:electron/js2c/browser_init:2:124038)\nat Module._load (node:internal/modules/cjs/loader:1058:27)\nat c._load (node:electron/js2c/node_init:2:17025)\nat Module.require (node:internal/modules/cjs/loader:1318:19)\nat require (node:internal/modules/helpers:179:18)\nat Object.<anonymous> (/Users/medentem/Dev/electron-flasher/out/electron-flasher-darwin-arm64/electron-flasher.app/Contents/Resources/app.asar/.vite/build/main.js:1:214)\nat Module._compile (node:internal/modules/cjs/loader:1484:14)\nat Module._extensions..js (node:internal/modules/cjs/loader:1564:10)\nat Module.load (node:internal/modules/cjs/loader:1295:32)\n```\n\n```text\nelectron-forge start\n```\n\n```text\nelectron-forge make\n```\n\n```text\nserialport\n```\n\n```text\ndrivelist\n```\n\n```text\nelectron-forge\n```\n\n```text\nAutoUnpackNativesPlugin\n```\n\n```text\nelectron-builder\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport { builtinModules } from \"node:module\";\n\nexport default defineConfig({\n  build: {\n    sourcemap: true,\n    outDir: \".vite\", // Output directory set to .vite\n    lib: {\n      entry: \"src/main.ts\",\n      formats: [\"cjs\"],\n    },\n    rollupOptions: {\n      external: [\"electron\", ...builtinModules, \"serialport\", \"drivelist\"],\n    },\n  },\n});\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport { builtinModules } from \"node:module\";\n\nexport default defineConfig({\n  build: {\n    sourcemap: true,\n    outDir: \".vite/preload\", // Output directory set to .vite\n    emptyOutDir: true,\n    lib: {\n      entry: \"src/preload.ts\",\n      formats: [\"cjs\"],\n    },\n    rollupOptions: {\n      external: [\"electron\", ...builtinModules],\n      output: {\n        entryFileNames: \"[name].js\",\n      },\n    },\n  },\n});\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\nexport default defineConfig({\n  plugins: [react()],\n  base: \"./\",\n  build: {\n    sourcemap: true,\n    outDir: \".vite/renderer\", // Output directory set to .vite\n    emptyOutDir: true,\n  },\n});\n```\n\n```text\nimport type { ForgeConfig } from \"@electron-forge/shared-types\";\nimport { AutoUnpackNativesPlugin } from \"@electron-forge/plugin-auto-unpack-natives\";\nimport { MakerSquirrel } from \"@electron-forge/maker-squirrel\";\nimport { MakerZIP } from \"@electron-forge/maker-zip\";\nimport { MakerDeb } from \"@electron-forge/maker-deb\";\nimport { MakerDMG } from \"@electron-forge/maker-dmg\";\nimport { MakerRpm } from \"@electron-forge/maker-rpm\";\nimport { VitePlugin } from \"@electron-forge/plugin-vite\";\nimport { FusesPlugin } from \"@electron-forge/plugin-fuses\";\nimport { FuseV1Options, FuseVersion } from \"@electron/fuses\";\n\nconst config: ForgeConfig = {\n  packagerConfig: {\n    asar: true,\n    ignore: [/\\/\\.(?!vite)/],\n  },\n  makers: [\n    new MakerSquirrel({}),\n    new MakerZIP({}, [\"darwin\"]),\n    new MakerRpm({}),\n    new MakerDeb({}),\n    new MakerDMG(),\n  ],\n  rebuildConfig: {\n    force: true,\n    onlyModules: [\"serialport\", \"drivelist\"],\n  },\n  plugins: [\n    new AutoUnpackNativesPlugin({}),\n    new VitePlugin({\n      // `build` can specify multiple entry builds, which can be Main process, Preload scripts, Worker process, etc.\n      // If you are familiar with Vite configuration, it will look really familiar.\n      build: [\n        {\n          // `entry` is just an alias for `build.lib.entry` in the corresponding file of `config`.\n          entry: \"src/main.ts\",\n          config: \"vite.main.config.ts\",\n          target: \"main\",\n        },\n        {\n          entry: \"src/preload.ts\",\n          config: \"vite.preload.config.ts\",\n          target: \"preload\",\n        },\n      ],\n      renderer: [\n        {\n          name: \"main_window\",\n          config: \"vite.renderer.config.ts\",\n        },\n      ],\n    }),\n    // Fuses are used to enable/disable various Electron functionality\n    // at package time, before code signing the application\n    new FusesPlugin({\n      version: FuseVersion.V1,\n      [FuseV1Options.RunAsNode]: false,\n      [FuseV1Options.EnableCookieEncryption]: true,\n      [FuseV1Options.EnableNodeOptionsEnvironmentVariable]: false,\n      [FuseV1Options.EnableNodeCliInspectArguments]: false,\n      [FuseV1Options.EnableEmbeddedAsarIntegrityValidation]: true,\n      [FuseV1Options.OnlyLoadAppFromAsar]: true,\n    }),\n  ],\n};\n\nexport default config;\n```\n\n```text\nexternal\n```\n\n```text\nbase\n```\n\n```text\nemptyOutDir\n```\n\n```text\nvite.main.config.ts\n```\n\n```text\nvite.main.config.ts\n```\n\n```text\nvite.preload.config.ts\n```\n\n```text\nvite.renderer.config.ts\n```\n\n```text\nforge.config.ts\n```\n\n========================================\n\nComments:\n- Thank you for sharing your results. This helped me get my project working after hours of trying to figure out why it wasn't building correctly. Worked fine in development more for me as well and then would fail after running make.","metadata":{"transformedAt":"2026-08-18T18:33:46.419Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":243,"estimatedTokens":1806}}331{"id":"stack-75719664","source":"stackoverflow","questionId":75719664,"title":"(!) Some chunks are larger than 500 KiB after minification","tags":["laravel","vue.js","vite","yarn-workspaces"],"text":"Title: (!) Some chunks are larger than 500 KiB after minification\nTags: laravel, vue.js, vite, yarn-workspaces\nSource: Stack Overflow\n\nQuestion:\nOn rRun `yarn dev` it work fine but whenI run `yarn build` it's showing this error\n\n```\n(!) Some chunks are larger than 500 kBs after minification. Consider:\n- Using dynamic import() to code-split the application\n- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/configuration-options/#output-manualchunks\n- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.\nDone in 6.03s.\n```\n\n========================================\n\nTop Answer:\nUpdate your **vite.config.js**:\n\n```\nexport default defineConfig({\n ...,\n build: {\n chunkSizeWarningLimit: 1600\n }\n});\n```\n\nIt will bump up the warning size to 1.6MB which is still a very safe value. Even 2MB would not be a realy problem with todays networks.\n\n========================================\n\nCode:\n```text\n(!) Some chunks are larger than 500 kBs after minification. Consider:\n- Using dynamic import() to code-split the application\n- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/configuration-options/#output-manualchunks\n- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.\nDone in 6.03s.\n```\n\n```text\nyarn dev\n```\n\n```text\nyarn build\n```\n\n```js\nbuild: {\n        rollupOptions: {\n            output:{\n                manualChunks(id) {\n                    if (id.includes('node_modules')) {\n                        return id.toString().split('node_modules/')[1].split('/')[0].toString();\n                    }\n                }\n            }\n        }\n    }\n```\n\n```ts\nexport default defineConfig({\n    plugins: [\n        vue(),\n        laravel({\n            input: ['resources/js/app.js'],\n            refresh: true,\n        }),\n        i18n(),\n    ],\n\n    resolve: {\n        alias: {\n            vue: 'vue/dist/vue.esm-bundler.js',\n            ziggy: path.resolve('vendor/tightenco/ziggy/dist/vue.es.js'),\n\n        },\n    },\n    build: {\n        rollupOptions: {\n            output:{\n                manualChunks(id) {\n                    if (id.includes('node_modules')) {\n                        return id.toString().split('node_modules/')[1].split('/')[0].toString();\n                    }\n                }\n            }\n        }\n    }\n});\n```\n\n```text\nexport default defineConfig({\n    ...,\n    build: {\n        chunkSizeWarningLimit: 1600\n    }\n});\n```\n\n========================================\n\nComments:\n- Not an error just a warning. You can savely ignore this unless you have chunks over a couple of MB. Your font files are probably larger than your code.\n- Thanks! I'm using MUI and am still getting the warning. build/assets/@mui-9a782d5f.js 738.47 kB A workaround to get the warning away (not fix), add this to build object in config file: ` chunkSizeWarningLimit: 800,`\n- those are warnings, and accepted answer does not explain how it helps to minimize chunks\n- The github post from where this answer is says, that it screws with the CSS import order and reverses them backwacks and break the CSS. No solution. Stop copy&pasting this answer everywhere.\n- As per comments above, this still does not *solve* the issue; it merely glosses over it, and as immediate above comment makes note, really fouls up CSS import order (which is key to CSS working properly)\n- this is not an answer as it does not explain what is going on.\n- @theking2 lol it says totally chunk the entire node_modules\n- Not a good idea because this simply suppresses the warning, hiding the real culprit and possibly a real solution yet to be found. 1/10 do not recommend. (the 1 is because some days, .... some days you just need some silence)\n- @weo3dev it's an excellent answer as is bumps up the warning level to a reasonable amount. Unless you are developing for rural America with low bandwidth 1.6MB is a totally acceptable chunk size.\n- Or if I'm on my phone. Which is pretty common.","metadata":{"transformedAt":"2026-08-18T18:33:46.419Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":118,"estimatedTokens":998}}332{"id":"stack-76115552","source":"stackoverflow","questionId":76115552,"title":"Vue 3 / Vite not respecting base url when routing. Route refresh produces 404","tags":["vue.js","iis","vuejs3","vue-router","vite"],"text":"Title: Vue 3 / Vite not respecting base url when routing. Route refresh produces 404\nTags: vue.js, iis, vuejs3, vue-router, vite\nSource: Stack Overflow\n\nQuestion:\nVue 3.2.13,\nVite 3.2.5,\nvite-plugin-rewrite-all 1.0.1\n\nHosted on IIS\n\nI've recently deployed an app I'm working on to IIS. I have to use the --base option with my build as my site is a Application in the website.\n\nMy base url would be https://example.com/myApplicaitons/myApp/vueRoute.\n\nOn the initial load my url is https://example.com/myApplicaitons/myApp/vueRoute but when navigating using a routing link I load my component successfully but the url is https://example.com/vueRoute instead of https://example.com/myApplicaitons/myApp/vueRoute and when I refresh it produces a 404.\n\nI'm already using history mode for the router and I've even installed the rewrite-all node module as suggested in similar posts. I also have a web.config im public folder with the same configuration as https://v3.router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations.\n\nI'll include my vite.config.js, router/index.ts and my script for building.\n\nvite.config.js\n\n```\n// Plugins\nimport vue from \"@vitejs/plugin-vue\";\nimport pluginRewriteAll from \"vite-plugin-rewrite-all\";\n\n// Utilities\nimport { defineConfig } from \"vite\";\nimport { fileURLToPath, URL } from \"node:url\";\n\n// eslint-disable-next-line no-undef\nconst path = require(\"path\");\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [vue(), pluginRewriteAll()],\n define: { \"process.env\": {} },\n resolve: {\n alias: {\n \"@\": fileURLToPath(new URL(\"./src\", import.meta.url)),\n \"~bootstrap\": path.resolve(__dirname, \"node_modules/bootstrap\"),\n },\n extensions: [\".js\", \".json\", \".jsx\", \".mjs\", \".ts\", \".tsx\", \".vue\"],\n },\n server: {\n port: 3000,\n },\n});\n```\n\nrouter/index.ts\n\n```\n// Composables\nimport { Component } from 'vue';\nimport ChildVue from '@/views/child/Child.vue';\nimport { createRouter, createWebHistory } from 'vue-router';\n\nconst routes = [\n {\n path: '/',\n component: HomeVue,\n },\n {\n path: '/MyRoute',\n children: [\n {\n path: '/Child',\n name: 'Child',\n component: ChildVue,\n },\n ],\n },\n] as Route[];\n\nconst router = createRouter({\n history: createWebHistory(process.env.BASE_URL),\n routes,\n});\n\nexport default router;\n\nexport interface Route {\n path: string;\n name?: string;\n component: Component;\n}\n```\n\nBuild script\n`\"build-dev\": \"vite build --mode dev --base=/myApplicaitons/myApp/\"`\n\nTIA\n\n========================================\n\nCode:\n```text\n// Plugins\nimport vue from \"@vitejs/plugin-vue\";\nimport pluginRewriteAll from \"vite-plugin-rewrite-all\";\n\n// Utilities\nimport { defineConfig } from \"vite\";\nimport { fileURLToPath, URL } from \"node:url\";\n\n// eslint-disable-next-line no-undef\nconst path = require(\"path\");\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue(), pluginRewriteAll()],\n  define: { \"process.env\": {} },\n  resolve: {\n    alias: {\n      \"@\": fileURLToPath(new URL(\"./src\", import.meta.url)),\n      \"~bootstrap\": path.resolve(__dirname, \"node_modules/bootstrap\"),\n    },\n    extensions: [\".js\", \".json\", \".jsx\", \".mjs\", \".ts\", \".tsx\", \".vue\"],\n  },\n  server: {\n    port: 3000,\n  },\n});\n```\n\n```text\n// Composables\nimport { Component } from 'vue';\nimport ChildVue from '@/views/child/Child.vue';\nimport { createRouter, createWebHistory } from 'vue-router';\n\nconst routes = [\n    {\n        path: '/',\n        component: HomeVue,\n    },\n    {\n        path: '/MyRoute',\n        children: [\n            {\n                path: '/Child',\n                name: 'Child',\n                component: ChildVue,\n            },\n        ],\n    },\n] as Route[];\n\nconst router = createRouter({\n    history: createWebHistory(process.env.BASE_URL),\n    routes,\n});\n\nexport default router;\n\nexport interface Route {\n    path: string;\n    name?: string;\n    component: Component;\n}\n```\n\n```text\n\"build-dev\": \"vite build --mode dev --base=/myApplicaitons/myApp/\"\n```\n\n```js\ncreateWebHistory(process.env.BASE_URL)\n```\n\n```js\ncreateWebHistory(import.meta.env.BASE_URL)\n```\n\n```text\nprocess.env\n```\n\n========================================\n\nComments:\n- `createWebHistory(process.env.BASE_URL)` seems wrong. With vite the BASE_URL env is `import.meta.env.BASE_URL`. link to docs\n- About `env.BASE_URL` maybe Op refers to the method in this tutorial: vueschool.io/articles/vuejs-tutorials/&hellip;. Perhaps this tutorial could help you: vueschool.io/lessons/&hellip;.\n- @yoduh that did it! Thank you! Please post as an answer so I can give you credit.\n- You're welcome! Glad it solved your issue. Answer is posted.\n- Found this solution after spending 2 hours","metadata":{"transformedAt":"2026-08-18T18:33:46.419Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":189,"estimatedTokens":1161}}333{"id":"stack-68501609","source":"stackoverflow","questionId":68501609,"title":"Integrating Vue+Vite into an existing PHP project","tags":["php","vue.js","vuejs3","vite"],"text":"Title: Integrating Vue+Vite into an existing PHP project\nTags: php, vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI am experienced on PHP and Javascript and used them extensively up to now. I never used modern js frameworks like Vue, Angular or React and very new to this concept. And also have no experience with bundlers.\n\nNow I want to try it and enter to the new world of modern web app development. I've started reading with Vue docs and liked it.\n\nBut I am not ready to develop a Single Page App from scratch. Instead I want to try it within an existing project (with PHP backend and ES6 frontend)\n\nI've searched for such integrations but could not found any helping document.\n\nI want to use:\n\n- .vue SFC files\n\n- Hot updates (HMR)\n\n- Vite\n\n**More info:**\n\nThe PHP framework I use have single index.php entry and virtual routing via htaccess.\n\nSimple structure is like:\n\n```\nwww/\n├──.htaccess\n├──index.php\n├──Application/\n├──public/\n│ ├── js/\n│ ├── css/\n├──Modules/\n│ ├──MyVueApp/\n│ │ ├──Controllers/\n│ │ ├──Views/\n│ │ │ ├──index.phtml\n│ │ ├──Model.php\n│ │ ├── //and etc...\n```\n\nAt location `http://localhost/en/MyVueApp` Backend framework renders a dynamic index page within a layout.\n\n**Contents of index.phtml**\n\n```\nlayout->addCss('css/my-vue-app/main.css')\n$this->layout->addJs('js/my-vue-app/main.js')\n?>\n\n```\n\nHow can I install and run Vite+Vue on this structure and how can I publish it for production ?\n\n========================================\n\nTop Answer:\nThe solution can be found at https://github.com/andrefelipe/vite-php-setup\n\nLive Reload Plugin makes the job.\n\nhttps://www.npmjs.com/package/vite-plugin-live-reload\n\n========================================\n\nCode:\n```text\nwww/\n├──.htaccess\n├──index.php\n├──Application/\n├──public/\n│   ├── js/\n│   ├── css/\n├──Modules/\n│   ├──MyVueApp/\n│   │   ├──Controllers/\n│   │   ├──Views/\n│   │   │   ├──index.phtml\n│   │   ├──Model.php\n│   │   ├── //and etc...\n```\n\n```text\n<?php\n$this->layout->addCss('css/my-vue-app/main.css')\n$this->layout->addJs('js/my-vue-app/main.js')\n?>\n\n<div id=\"app\"><!-- vue app mounts here --></div>\n```\n\n```text\nhttp://localhost/en/MyVueApp\n```\n\n```text\nvite-plugin-php\n```\n\n========================================\n\nComments:\n- ask yourself why you even need php? once you bundle the SPA its can be run from apache or any other static file server, its a SPA after all, you won't need $this->layout->addCss and $this->layout->addJs etc, PHP's job would be simply a rest API, but then your ask yourself why put PHP in the mix when nodejs is js, and doesn't need additional tools, like, server, PHP installed, diff linters and package mangers etc etc.\n- The question was sipmlified to make it easy ro understand. Actual situation is more complicated. I am trying to integrate Vue into an existing project. I can not use an index.html file cause I have to use PHP frameworks layout engine.","metadata":{"transformedAt":"2026-08-18T18:33:46.419Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":108,"estimatedTokens":722}}334{"id":"stack-75988769","source":"stackoverflow","questionId":75988769,"title":"Vite-PWA-plugin how to add webpush (notifications)","tags":["javascript","progressive-web-apps","vite","workbox","web-push"],"text":"Title: Vite-PWA-plugin how to add webpush (notifications)\nTags: javascript, progressive-web-apps, vite, workbox, web-push\nSource: Stack Overflow\n\nQuestion:\nI had the `sw.js` which receive webpush notifications.\nBut recently I intalled vite-PWA-plugin and now i can't add notifications by default config.\n\nHow can i configure this `vite.config.ts` to add to generated `serviceWorker.js` webpush implementation?\n\n`vite.config.ts`:\n\n\r\n\r\n\n```\nimport {defineConfig} from 'vite';\nimport laravel from 'laravel-vite-plugin';\nimport react from '@vitejs/plugin-react';\n\nimport path from 'path';\nimport {VitePWA} from \"vite-plugin-pwa\";\n\nconst manifest = {\n \"theme_color\" : \"#2B2B2B\",\n \"background_color\": \"#2B2B2B\",\n \"display\" : \"standalone\",\n \"scope\" : \"/\",\n \"start_url\" : \"/farm\",\n \"name\" : \"ColorBit\",\n \"short_name\" : \"Mining\",\n \"description\" : \"...\",\n \"icons\" : [\n {\n \"src\" : \"icons/icon-192x192.png\",\n \"sizes\": \"192x192\",\n \"type\" : \"image/png\"\n },\n // ...\n {\n \"src\" : \"icons/maskable_icon.png\",\n \"sizes\" : \"682x682\",\n \"type\" : \"image/png\",\n \"purpose\": \"maskable\"\n }\n ]\n};\n\nconst getCache = ({ name, pattern, strategy = \"CacheFirst\" }: any) => ({\n urlPattern: pattern,\n handler: strategy,\n options: {\n cacheName: name,\n expiration: {\n maxEntries: 500,\n maxAgeSeconds: 60 * 60 * 24 * 60 // 2 months\n },\n cacheableResponse: {\n statuses: [0, 200]\n }\n }\n});\n\nexport default defineConfig({\n plugins: [\n laravel({\n input : [ 'resources/js/app.tsx',],\n refresh: true,\n }),\n react({\n fastRefresh: false\n }),\n VitePWA({\n registerType: 'autoUpdate',\n outDir : path.resolve(__dirname, 'public'),\n manifest : manifest,\n manifestFilename: 'manifest.webmanifest', // Change name for app manifest\n injectRegister : false, // I register SW in app.ts, disable auto registration\n\n workbox : {\n globDirectory: path.resolve(__dirname, 'public'), // Directory for caching\n globPatterns : [\n '{build,images,sounds,icons}/**/*.{js,css,html,ico,png,jpg,mp4,svg}'\n ],\n navigateFallback: null, // Say that we don't need to cache index.html\n swDest : 'public/serviceWorker.js',\n runtimeCaching: [\n // Google fonts cache\n getCache({\n pattern: /^https:\\/\\/fonts\\.googleapis\\.com\\/.*/i,\n name: \"google-fonts-cache\",\n }),\n // Google fonts api cache\n getCache({\n pattern: /^https:\\/\\/fonts\\.gstatic\\.com\\/.*/i,\n name: \"gstatic-fonts-cache\"\n }),\n // Dynamic cache for assets in storage folder\n getCache({\n pattern: /.*storage.*/,\n name: \"dynamic-images-cache\",\n }),\n\n ]\n }\n })\n ],\n resolve: {\n alias : {\n '@' : path.resolve(__dirname, 'resources/js'),\n '@hooks' : path.resolve(__dirname, 'resources/js/hooks'),\n '@assets' : path.resolve(__dirname, 'resources/js/assets/'),\n '@components': path.resolve(__dirname, 'resources/js/components')\n },\n extensions: ['.js', '.ts', '.tsx', '.jsx'],\n },\n});\n```\n\n\r\n\r\n\r\n\nOld webpush implementation in `sw.js`:\n\n\r\n\r\n\n```\n// ^^^ Activate, Install, Fetch... ^^^\n\n/* Webpush Notifications */\n\n// Receive push notifications\nself.addEventListener('push', function (e) {\n if (!(\n self.Notification &&\n self.Notification.permission === 'granted'\n )) {\n //notifications aren't supported or permission not granted!\n return;\n }\n\n if (e.data) {\n let message = e.data.json();\n e.waitUntil(self.registration.showNotification(message.title, {\n body: message.body,\n icon: message.icon,\n actions: message.actions\n }));\n }\n});\n\n// Click and open notification\nself.addEventListener('notificationclick', function(event) {\n event.notification.close();\n\n if (event.action === 'farm') clients.openWindow(\"/farm\");\n else if (event.action === 'home') clients.openWindow(\"/\");\n else if (event.action === 'training') clients.openWindow(\"/mining-training\");\n else if (event.action === 'dns') clients.openWindow(\"/shops/dns\");\n else if (event.action === 'ali') clients.openWindow(\"/shops/aliexpress\");\n else clients.openWindow(\"/farm\");\n}, false);\n```\n\n========================================\n\nTop Answer:\nHad to do this today with Firebase notifications. Here's what I did in case this helps someone else out in the future\n\nCreated the service worker file (included full version because I found it hard to find information on how to add notificiations)\n\n```\nimportScripts(\"https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js\");\nimportScripts(\"https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js\");\n\nif (\"serviceWorker\" in navigator) {\n navigator.serviceWorker\n .register(\"../firebase-messaging-sw.js\")\n .then(function (registration) {\n console.log(\"Registration successful, scope is:\", registration.scope);\n })\n .catch(function (err) {\n console.log(\"Service worker registration failed, error:\", err);\n });\n}\n\n// Initialize the Firebase app in the service worker by passing the generated config\nvar firebaseConfig = {\n apiKey: \"your apiKey\",\n authDomain: \"your authDomain\",\n projectId: \"you get the point by now right?\",\n storageBucket: \"\",\n messagingSenderId: \"\",\n appId: \"\",\n};\n\nfirebase.initializeApp(firebaseConfig);\n\n// Retrieve firebase messaging\nconst messaging = firebase.messaging();\n\nmessaging.onBackgroundMessage(function (payload) {\n console.log(\"Received background message \", payload);\n\n const notificationTitle = payload.notification.title;\n const notificationOptions = {\n body: payload.notification.body,\n icon: \"/images/yourLogo.png\",\n };\n\n self.registration.showNotification(notificationTitle, notificationOptions);\n});\n```\n\nIn my (React) app I registered for foreground notifications like this\n\n```\nimport { initializeApp } from \"firebase/app\";\nimport { getMessaging, getToken, onMessage } from \"firebase/messaging\";\n\nconst firebaseConfig = {\n apiKey: \"your apiKey\",\n authDomain: \"your authDomain\",\n projectId: \"you get the point by now right?\",\n storageBucket: \"\",\n messagingSenderId: \"\",\n appId: \"\",\n};\n\nconst firebaseApp = initializeApp(firebaseConfig);\nconst messaging = getMessaging(firebaseApp);\n\nexport const getFirebaseToken = (setTokenFound) => {\n return getToken(messaging, {\n vapidKey: \"key is generated for you on firebase\",\n })\n .then((currentToken) => {\n if (currentToken) {\n console.log(\"current token for client: \", currentToken);\n setTokenFound(true);\n // Track the token -> client mapping, by sending to backend server\n // show on the UI that permission is secured\n } else {\n console.log(\"No registration token available. Request permission to generate one.\");\n setTokenFound(false);\n // shows on the UI that permission is required\n }\n })\n .catch((err) => {\n console.log(\"An error occurred while retrieving token. \", err);\n // catch error while creating client token\n });\n};\n\nexport const onMessageListener = () =>\n new Promise((resolve) => {\n onMessage(messaging, (payload) => {\n console.log(\"payload\", payload);\n resolve(payload);\n });\n });\n```\n\nand called it in my App.tsx file like this. So now we get a prompt requesting notification permission and we can see the user token in console if they accept\n\n```\ngetFirebaseToken(setTokenFound);\n isTokenFound ? console.log(\"Token found\") : console.log(\"Token not found\");\n\n onMessageListener()\n .then((payload) => {\n toast.success(payload.notification.title, payload.notification.body);\n console.log(payload);\n })\n .catch((err) => console.log(\"failed: \", err));\n```\n\nIn my `vite.config.js` at the top level of the object I return from `defineConfig()` all I had to do was import the script like so\n\n```\nworkbox: {\n importScripts: [\"./firebase-messaging-sw.js\"],\n},\n```\n\nThis last bit took me the longest to figure out....hope it helps someone\n\n========================================\n\nCode:\n```js\nimport {defineConfig} from 'vite';\nimport laravel from 'laravel-vite-plugin';\nimport react from '@vitejs/plugin-react';\n\nimport path from 'path';\nimport {VitePWA} from \"vite-plugin-pwa\";\n\nconst manifest = {\n    \"theme_color\"     : \"#2B2B2B\",\n    \"background_color\": \"#2B2B2B\",\n    \"display\"         : \"standalone\",\n    \"scope\"           : \"/\",\n    \"start_url\"       : \"/farm\",\n    \"name\"            : \"ColorBit\",\n    \"short_name\"      : \"Mining\",\n    \"description\"     : \"...\",\n    \"icons\"           : [\n        {\n            \"src\"  : \"icons/icon-192x192.png\",\n            \"sizes\": \"192x192\",\n            \"type\" : \"image/png\"\n        },\n        // ...\n        {\n            \"src\"    : \"icons/maskable_icon.png\",\n            \"sizes\"  : \"682x682\",\n            \"type\"   : \"image/png\",\n            \"purpose\": \"maskable\"\n        }\n    ]\n};\n\nconst getCache = ({ name, pattern, strategy = \"CacheFirst\" }: any) => ({\n    urlPattern: pattern,\n    handler: strategy,\n    options: {\n        cacheName: name,\n        expiration: {\n            maxEntries: 500,\n            maxAgeSeconds: 60 * 60 * 24 * 60 // 2 months\n        },\n        cacheableResponse: {\n            statuses: [0, 200]\n        }\n    }\n});\n\nexport default defineConfig({\n    plugins: [\n        laravel({\n            input  : [ 'resources/js/app.tsx',],\n            refresh: true,\n        }),\n        react({\n            fastRefresh: false\n        }),\n        VitePWA({\n            registerType: 'autoUpdate',\n            outDir      : path.resolve(__dirname, 'public'),\n            manifest    : manifest,\n            manifestFilename: 'manifest.webmanifest', // Change name for app manifest\n            injectRegister  : false, // I register SW in app.ts, disable auto registration\n\n            workbox         : {\n                globDirectory: path.resolve(__dirname, 'public'), // Directory for caching\n                globPatterns : [\n                    '{build,images,sounds,icons}/**/*.{js,css,html,ico,png,jpg,mp4,svg}'\n                ],\n                navigateFallback: null, // Say that we don't need to cache index.html\n                swDest       : 'public/serviceWorker.js',\n                runtimeCaching: [\n                    // Google fonts cache\n                    getCache({\n                        pattern: /^https:\\/\\/fonts\\.googleapis\\.com\\/.*/i,\n                        name: \"google-fonts-cache\",\n                    }),\n                    // Google fonts api cache\n                    getCache({\n                        pattern: /^https:\\/\\/fonts\\.gstatic\\.com\\/.*/i,\n                        name: \"gstatic-fonts-cache\"\n                    }),\n                    // Dynamic cache for assets in storage folder\n                    getCache({\n                        pattern: /.*storage.*/,\n                        name: \"dynamic-images-cache\",\n                    }),\n\n                ]\n            }\n        })\n    ],\n    resolve: {\n        alias     : {\n            '@'          : path.resolve(__dirname, 'resources/js'),\n            '@hooks'     : path.resolve(__dirname, 'resources/js/hooks'),\n            '@assets'    : path.resolve(__dirname, 'resources/js/assets/'),\n            '@components': path.resolve(__dirname, 'resources/js/components')\n        },\n        extensions: ['.js', '.ts', '.tsx', '.jsx'],\n    },\n});\n```\n\n```js\n// ^^^ Activate, Install, Fetch... ^^^\n\n/* Webpush Notifications */\n\n// Receive push notifications\nself.addEventListener('push', function (e) {\n    if (!(\n        self.Notification &&\n        self.Notification.permission === 'granted'\n    )) {\n        //notifications aren't supported or permission not granted!\n        return;\n    }\n\n    if (e.data) {\n        let message = e.data.json();\n        e.waitUntil(self.registration.showNotification(message.title, {\n            body: message.body,\n            icon: message.icon,\n            actions: message.actions\n        }));\n    }\n});\n\n// Click and open notification\nself.addEventListener('notificationclick', function(event) {\n    event.notification.close();\n\n    if (event.action === 'farm') clients.openWindow(\"/farm\");\n    else if (event.action === 'home') clients.openWindow(\"/\");\n    else if (event.action === 'training') clients.openWindow(\"/mining-training\");\n    else if (event.action === 'dns') clients.openWindow(\"/shops/dns\");\n    else if (event.action === 'ali') clients.openWindow(\"/shops/aliexpress\");\n    else clients.openWindow(\"/farm\");\n}, false);\n```\n\n```text\nsw.js\n```\n\n```text\nvite.config.ts\n```\n\n```text\nserviceWorker.js\n```\n\n```text\nvite.config.ts\n```\n\n```text\nsw.js\n```\n\n```js\nexport default defineConfig({\n  plugins: [\n    laravel({\n      input: ['resources/js/app.tsx', ],\n      refresh: true,\n    }),\n    react({\n      fastRefresh: false\n    }),\n    VitePWA({\n      registerType: 'autoUpdate',\n      outDir: path.resolve(__dirname, 'public'),\n      manifest: manifest,\n      manifestFilename: 'manifest.webmanifest', // Change name for app manifest\n      injectRegister: false, // I register SW in app.ts, disable auto registration\n\n      // HERE! For custom service worker\n      srcDir: path.resolve(__dirname, 'resources/js/'),\n      filename: 'serviceWorker.js',\n      strategies: 'injectManifest',\n\n      workbox: {\n        globDirectory: path.resolve(__dirname, 'public'),\n        globPatterns: [\n          '{build,images,sounds,icons}/**/*.{js,css,html,ico,png,jpg,mp4,svg}'\n        ],\n      },\n    })\n  ],\n  resolve: {\n    alias: {\n      '@': path.resolve(__dirname, 'resources/js'),\n      '@hooks': path.resolve(__dirname, 'resources/js/hooks'),\n      '@assets': path.resolve(__dirname, 'resources/js/assets/'),\n      '@components': path.resolve(__dirname, 'resources/js/components')\n    },\n    extensions: ['.js', '.ts', '.tsx', '.jsx'],\n  },\n\n  // define: {\n  //     // By default, Vite doesn't include shims for NodeJS/\n  //     // necessary for React-joyride. And probably for another libs\n  //     global: {},\n  // },\n});\n```\n\n```js\nimport {ExpirationPlugin} from 'workbox-expiration';\nimport {createHandlerBoundToURL, precacheAndRoute, cleanupOutdatedCaches} from 'workbox-precaching';\nimport {registerRoute} from 'workbox-routing';\nimport {CacheFirst} from 'workbox-strategies';\nimport { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin';\n\n// Register precache routes (static cache)\nprecacheAndRoute(self.__WB_MANIFEST || []);\n\n// Clean up old cache\ncleanupOutdatedCaches();\n\n// Google fonts dynamic cache\nregisterRoute(\n    /^https:\\/\\/fonts\\.googleapis\\.com\\/.*/i,\n    new CacheFirst({\n        cacheName: \"google-fonts-cache\",\n        plugins: [\n            new ExpirationPlugin({maxEntries: 500, maxAgeSeconds: 5184e3}),\n            new CacheableResponsePlugin({statuses: [0, 200]})\n        ]\n    }), \"GET\");\n\n// Google fonts dynamic cache\nregisterRoute(\n    /^https:\\/\\/fonts\\.gstatic\\.com\\/.*/i, new CacheFirst({\n        cacheName: \"gstatic-fonts-cache\",\n        plugins: [\n            new ExpirationPlugin({maxEntries: 500, maxAgeSeconds: 5184e3}),\n            new CacheableResponsePlugin({statuses: [0, 200]})\n        ]\n    }), \"GET\");\n\n// Dynamic cache for images from `/storage/`\nregisterRoute(\n    /.*storage.*/, new CacheFirst({\n        cacheName: \"dynamic-images-cache\",\n        plugins: [\n            new ExpirationPlugin({maxEntries: 500, maxAgeSeconds: 5184e3}),\n            new CacheableResponsePlugin({statuses: [0, 200]})\n        ]\n    }), \"GET\");\n\n// Install and activate service worker\nself.addEventListener('install', () => self.skipWaiting());\nself.addEventListener('activate', () => self.clients.claim());\n\n// Receive push notifications\nself.addEventListener('push', function (e) {\n    if (!(\n        self.Notification &&\n        self.Notification.permission === 'granted'\n    )) {\n        //notifications aren't supported or permission not granted!\n        console.log('nononono')\n        return;\n    }\n\n    if (e.data) {\n        let message = e.data.json();\n        e.waitUntil(self.registration.showNotification(message.title, {\n            body: message.body,\n            icon: message.icon,\n            actions: message.actions\n        }));\n    }\n});\n\n// Click and open notification\nself.addEventListener('notificationclick', function(event) {\n    event.notification.close();\n\n    if (event.action === 'farm') clients.openWindow(\"/farm\");\n    else if (event.action === 'home') clients.openWindow(\"/\");\n    else if (event.action === 'training') clients.openWindow(\"/mining-training\");\n    else if (event.action === 'dns') clients.openWindow(\"/shops/dns\");\n    else if (event.action === 'ali') clients.openWindow(\"/shops/aliexpress\");\n    else if (event.action === 'avito') clients.openWindow(\"/avito\");\n    else if (event.action === 'friends') clients.openWindow(\"/friends\");\n    else if (event.action === 'locations') clients.openWindow(\"/locations\");\n    else if (event.action === 'vk-chat') clients.openWindow(\"https://vk.me/join/au1/k0nOTjLasxMO6wX50QuyPfYosyWdPEI=\");\n    else clients.openWindow(event.action); // Open link from action\n}, false);\n```\n\n```text\nvite.config.ts\n```\n\n```text\n/resouces/js/serviceWorker.js\n```\n\n```text\nimportScripts(\"https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js\");\nimportScripts(\"https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js\");\n\nif (\"serviceWorker\" in navigator) {\n    navigator.serviceWorker\n        .register(\"../firebase-messaging-sw.js\")\n        .then(function (registration) {\n            console.log(\"Registration successful, scope is:\", registration.scope);\n        })\n        .catch(function (err) {\n            console.log(\"Service worker registration failed, error:\", err);\n        });\n}\n\n// Initialize the Firebase app in the service worker by passing the generated config\nvar firebaseConfig = {\n    apiKey: \"your apiKey\",\n    authDomain: \"your authDomain\",\n    projectId: \"you get the point by now right?\",\n    storageBucket: \"\",\n    messagingSenderId: \"\",\n    appId: \"\",\n};\n\nfirebase.initializeApp(firebaseConfig);\n\n// Retrieve firebase messaging\nconst messaging = firebase.messaging();\n\nmessaging.onBackgroundMessage(function (payload) {\n    console.log(\"Received background message \", payload);\n\n    const notificationTitle = payload.notification.title;\n    const notificationOptions = {\n        body: payload.notification.body,\n        icon: \"/images/yourLogo.png\",\n    };\n\n    self.registration.showNotification(notificationTitle, notificationOptions);\n});\n```\n\n```text\nimport { initializeApp } from \"firebase/app\";\nimport { getMessaging, getToken, onMessage } from \"firebase/messaging\";\n\nconst firebaseConfig = {\n    apiKey: \"your apiKey\",\n    authDomain: \"your authDomain\",\n    projectId: \"you get the point by now right?\",\n    storageBucket: \"\",\n    messagingSenderId: \"\",\n    appId: \"\",\n};\n\nconst firebaseApp = initializeApp(firebaseConfig);\nconst messaging = getMessaging(firebaseApp);\n\nexport const getFirebaseToken = (setTokenFound) => {\n    return getToken(messaging, {\n        vapidKey: \"key is generated for you on firebase\",\n    })\n        .then((currentToken) => {\n            if (currentToken) {\n                console.log(\"current token for client: \", currentToken);\n                setTokenFound(true);\n                // Track the token -> client mapping, by sending to backend server\n                // show on the UI that permission is secured\n            } else {\n                console.log(\"No registration token available. Request permission to generate one.\");\n                setTokenFound(false);\n                // shows on the UI that permission is required\n            }\n        })\n        .catch((err) => {\n            console.log(\"An error occurred while retrieving token. \", err);\n            // catch error while creating client token\n        });\n};\n\nexport const onMessageListener = () =>\n    new Promise((resolve) => {\n        onMessage(messaging, (payload) => {\n            console.log(\"payload\", payload);\n            resolve(payload);\n        });\n    });\n```\n\n```text\ngetFirebaseToken(setTokenFound);\n    isTokenFound ? console.log(\"Token found\") : console.log(\"Token not found\");\n\n    onMessageListener()\n        .then((payload) => {\n            toast.success(payload.notification.title, payload.notification.body);\n            console.log(payload);\n        })\n        .catch((err) => console.log(\"failed: \", err));\n```\n\n```text\nworkbox: {\n    importScripts: [\"./firebase-messaging-sw.js\"],\n},\n```\n\n```text\nvite.config.js\n```\n\n```text\ndefineConfig()\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.419Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":711,"estimatedTokens":4981}}335{"id":"stack-75037806","source":"stackoverflow","questionId":75037806,"title":"I use github action and vercel to deploy my project(vite+react+pnpm) to vercel, action said error: \"Error: spawn pnpm ENOENT\"","tags":["github","action","vite","vercel","pnpm"],"text":"Title: I use github action and vercel to deploy my project(vite+react+pnpm) to vercel, action said error: \"Error: spawn pnpm ENOENT\"\nTags: github, action, vite, vercel, pnpm\nSource: Stack Overflow\n\nQuestion:\nwhen I push my github project, the github action was executed, but it failed, the error message from the action is below:\n\n```\nRun vercel build --prod --token=***\nVercel CLI 28.10.3\nDetected `pnpm-lock.yaml` generated by pnpm 7...\nInstalling dependencies...\nError: spawn pnpm ENOENT\nError: Process completed with exit code 1.\n```\n\nthis is my action yml settings:\n\n```\nname: Vercel Deployment\nenv:\n VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}\n VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}\non:\n push:\n branches:\n - master\njobs:\n Deploy-Production:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v3\n - uses: actions/setup-node@v3\n with:\n node-version: 18.12.1\n - name: Install Vercel CLI\n run: npm install --global vercel@latest\n - name: Pull Vercel Environment Information\n run: vercel pull --yes --environment=production --token=${{ secrets.VERCEL_TOKEN }}\n - name: Build Project Artifacts\n run: vercel build --prod --token=${{ secrets.VERCEL_TOKEN }}\n - name: Deploy Project Artifacts to Vercel\n run: vercel deploy --prebuilt --prod --token=${{ secrets.VERCEL_TOKEN }}\n```\n\n========================================\n\nCode:\n```text\nRun vercel build --prod --token=***\nVercel CLI 28.10.3\nDetected `pnpm-lock.yaml` generated by pnpm 7...\nInstalling dependencies...\nError: spawn pnpm ENOENT\nError: Process completed with exit code 1.\n```\n\n```text\nname: Vercel Deployment\nenv:\n  VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}\n  VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}\non:\n  push:\n    branches:\n      - master\njobs:\n  Deploy-Production:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v3\n      - uses: actions/setup-node@v3\n        with:\n          node-version: 18.12.1\n      - name: Install Vercel CLI\n        run: npm install --global vercel@latest\n      - name: Pull Vercel Environment Information\n        run: vercel pull --yes --environment=production --token=${{ secrets.VERCEL_TOKEN }}\n      - name: Build Project Artifacts\n        run: vercel build --prod --token=${{ secrets.VERCEL_TOKEN }}\n      - name: Deploy Project Artifacts to Vercel\n        run: vercel deploy --prebuilt --prod --token=${{ secrets.VERCEL_TOKEN }}\n```\n\n```yaml\njobs:\n  deploy-production:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v3\n      - name: Install Node.js\n        uses: actions/setup-node@v3\n        with:\n          node-version: 18\n      - uses: pnpm/action-setup@v2\n        name: Install pnpm\n        id: pnpm-install\n        with:\n          version: 7\n          run_install: false\n      - name: Install Vercel CLI\n        run: pnpm add --global vercel@latest\n      - name: Pull Vercel Environment Information\n        run: vercel pull --yes --environment=production --token=${{ secrets.VERCEL_TOKEN }}\n      - name: Build Project Artifacts\n        run: vercel build --prod --token=${{ secrets.VERCEL_TOKEN }}\n      - name: Deploy Project Artifacts to Vercel\n        run: vercel deploy --prebuilt --prod --token=${{ secrets.VERCEL_TOKEN }}\n```\n\n```text\npnpm add --global vercel@latest\n```\n\n========================================\n\nComments:\n- I have the exact same issue. Did you find a workaround for this @no13bus?\n- No, util now, I ask vercel for help, they said I can try \"vercel delploy\" in the local enveriment, it is ok. But when I use github action, it does not work. I do not know how to resolve it\n- Hello, I encountered the same issue myself in the monorepo. The problem for me was that on Vercel I had Root Directory defined and I was using Vercel CLI with --cwd option like `vercel pull --yes --pwd projects&#47;my-project`. So removing Root directory from Vercel solved the issue for me. You can play with `.&#47;vercel&#47;projects.json` file yourself to see if it helps","metadata":{"transformedAt":"2026-08-18T18:33:46.419Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":121,"estimatedTokens":994}}336{"id":"stack-77749392","source":"stackoverflow","questionId":77749392,"title":"Vitest error when using jest.mock: jest is not defined","tags":["jestjs","vite","vitest"],"text":"Title: Vitest error when using jest.mock: jest is not defined\nTags: jestjs, vite, vitest\nSource: Stack Overflow\n\nQuestion:\nI have a project where it's using Vitest with Jest and React Testing Library. I have made the configuration for unit tests and it's working properly. However when I want to do a `jest.mock` on a library/file/React component I get the following error:\n\n`ReferenceError: jest is not defined`\n\nHere is my configuration:\n\n```\n// setupTests.ts\n\nimport matchers from '@testing-library/jest-dom/matchers';\nimport { expect } from 'vitest';\n\nexpect.extend(matchers);\n```\n\n```\n// vitest.config.ts\n\n/// \n\nimport react from '@vitejs/plugin-react';\nimport tsconfigPaths from 'vite-tsconfig-paths';\nimport { defineConfig } from 'vitest/config';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react(), tsconfigPaths()],\n test: {\n globals: true,\n environment: 'jsdom',\n include: ['**/*.test.tsx'],\n setupFiles: 'setupTests.ts',\n },\n});\n```\n\n```\n// tsconfig.json\n\n{\n \"compilerOptions\": {\n \"target\": \"es5\",\n \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n \"allowJs\": true,\n \"skipLibCheck\": true,\n \"strict\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"noEmit\": true,\n \"esModuleInterop\": true,\n \"module\": \"esnext\",\n \"moduleResolution\": \"node\",\n \"resolveJsonModule\": true,\n \"isolatedModules\": true,\n \"jsx\": \"preserve\",\n \"incremental\": true,\n \"baseUrl\": \".\",\n \"paths\": {\n \"src/*\": [\"./src/*\"]\n }\n },\n \"include\": [\n \"setupTests.ts\",\n \"vitest.config.ts\",\n \"next-env.d.ts\",\n \"**/*.ts\",\n \"**/*.tsx\"\n ],\n \"exclude\": [\"node_modules\"]\n}\n```\n\nFor mocking, I know you can do `vi.mock` but I prefer using `jest.mock` since I'm used to doing that setup, is this even possible?\n\n========================================\n\nCode:\n```js\n// setupTests.ts\n\nimport matchers from '@testing-library/jest-dom/matchers';\nimport { expect } from 'vitest';\n\nexpect.extend(matchers);\n```\n\n```js\n// vitest.config.ts\n\n/// <reference types=\"vitest\" />\n\nimport react from '@vitejs/plugin-react';\nimport tsconfigPaths from 'vite-tsconfig-paths';\nimport { defineConfig } from 'vitest/config';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n    plugins: [react(), tsconfigPaths()],\n    test: {\n        globals: true,\n        environment: 'jsdom',\n        include: ['**/*.test.tsx'],\n        setupFiles: 'setupTests.ts',\n    },\n});\n```\n\n```js\n// tsconfig.json\n\n{\n    \"compilerOptions\": {\n        \"target\": \"es5\",\n        \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n        \"allowJs\": true,\n        \"skipLibCheck\": true,\n        \"strict\": true,\n        \"forceConsistentCasingInFileNames\": true,\n        \"noEmit\": true,\n        \"esModuleInterop\": true,\n        \"module\": \"esnext\",\n        \"moduleResolution\": \"node\",\n        \"resolveJsonModule\": true,\n        \"isolatedModules\": true,\n        \"jsx\": \"preserve\",\n        \"incremental\": true,\n        \"baseUrl\": \".\",\n        \"paths\": {\n            \"src/*\": [\"./src/*\"]\n        }\n    },\n    \"include\": [\n        \"setupTests.ts\",\n        \"vitest.config.ts\",\n        \"next-env.d.ts\",\n        \"**/*.ts\",\n        \"**/*.tsx\"\n    ],\n    \"exclude\": [\"node_modules\"]\n}\n```\n\n```text\njest.mock\n```\n\n```text\nReferenceError: jest is not defined\n```\n\n```text\nvi.mock\n```\n\n```text\njest.mock\n```\n\n========================================\n\nComments:\n- *\"it's using Vitest with Jest\"* - in what sense? They're two *different* test runners.\n- My question is not valid, as you pointed out, these are two different test runners. I got confused with the text `jest` included in the RTL package name. So I thought the package needed to run with `jest`. I stared at this issue for too long lol\n- Ah you're right! I failed to realize this, I guess I got confused with the text `jest` being included in the RTL package name, so I thought it needed to run with jest for some reason. Yes, these are two different test runners.","metadata":{"transformedAt":"2026-08-18T18:33:46.419Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":168,"estimatedTokens":963}}337{"id":"stack-69348371","source":"stackoverflow","questionId":69348371,"title":"Vue 3 replacing the HTML tags where v-html is called with the provided HTML","tags":["vue.js","vuejs3","vite"],"text":"Title: Vue 3 replacing the HTML tags where v-html is called with the provided HTML\nTags: vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nThis is about a Vue 3 app with Vite, not webpack.\n\nFor now, as you can see from this issue on vite's issue page, vite doesn't have a convenient way of inlining SVGs without using external plugins. Vite does however, support importing files as raw text strings. As such, I had an idea to use this feature and to inline SVG's by passing the raw SVG strings into an element's `v-html`.\n\nIt actually works great, the SVG shows up on the page as expected and I can do the usual CSS transforms (the whole purpose of inlining them like this), but it's not perfect. As it currently stands, the element that receives the `v-html` directive simply places the provided HTML nested as a child. For example, if I do ``, the final HTML comes out something like this\n\n```\n\n \n \n \n\n```\n\nIs there any way for me to essentially replace the parent element on which `v-html` is declared with the top-level element being passed to it? In the above example, it would mean the `` just becomes an ``\n\nEDIT:\n\nThanks to tony19 for mentioning custom directives.\n\nMy final result looks like this:\n\n```\n// main.ts\nimport { createApp } from \"vue\";\nimport App from \"./App.vue\";\n\nconst app = createApp(App);\n\napp.directive(\"inline\", (element) => {\n element.replaceWith(...element.children);\n});\n\napp.mount(\"#app\");\n```\n\nThen, in the component I simply use the directive, `` and it works great!\n\n========================================\n\nTop Answer:\nI found that using the method above works but is only good for a single rendering of the svg... The element starts throwing errors if I try to change the svg contents dynamically, not sure why but assuming that the dom replacement has something to do with it.\n\nI modified the code slightly for my use case.\n\n```\napp.directive('inline-svg', {\n updated: (element) => {\n if (element.children.length === 0) {\n return\n }\n const svg = element.children[0]\n if(svg.tagName.toLowerCase() !== 'svg') {\n return\n }\n for (let i = 0; i In my component I have.\n\n```\n\n```\n\nThe directive now copies the svg attributes across from the child to the parent and then replaces the child with it's children.\n\n========================================\n\nCode:\n```html\n<span>\n  <svg>\n    <!-- SVG attributes go here -->\n  </svg>\n</span>\n```\n\n```js\n// main.ts\nimport { createApp } from \"vue\";\nimport App from \"./App.vue\";\n\nconst app = createApp(App);\n\napp.directive(\"inline\", (element) => {\n  element.replaceWith(...element.children);\n});\n\napp.mount(\"#app\");\n```\n\n```text\nv-html\n```\n\n```text\nv-html\n```\n\n```text\n<span v-html=\"svgRaw\" />\n```\n\n```text\nv-html\n```\n\n```text\n<span>\n```\n\n```text\n<svg>\n```\n\n```text\n<svg v-html=\"svgRaw\" v-inline />\n```\n\n```js\n// main.js\nimport { createApp } from 'vue'\nimport App from './App.vue'\n\ncreateApp(App)\n  .directive('inline-svg', el => {\n    if (!el) {\n      return\n    }\n\n    // copy attributes to first child\n    const content = el.tagName === 'TEMPLATE' ? el.content : el\n    if (content.children.length === 1) {\n      ;[...el.attributes].forEach((attr) => content.firstChild.setAttribute(attr.name, attr.value))\n    }\n\n    // replace element with content\n    if (el.tagName === 'TEMPLATE') {\n      el.replaceWith(el.content)\n    } else {\n      el.replaceWith(...el.children)\n    }\n  })\n  .mount('#app')\n```\n\n```html\n<svg v-html=\"svgRaw\" v-inline-svg />\n<!-- OR -->\n<template v-html=\"svgRaw\" v-inline-svg />\n```\n\n```text\napp.directive()\n```\n\n```text\nv-inline-svg\n```\n\n```text\nv-inline-svg\n```\n\n```text\nv-html\n```\n\n```text\n<template>\n```\n\n```text\n<template v-html=\"svgRaw\" />\n```\n\n```text\nspan\n```\n\n```text\ntemplate\n```\n\n```text\n<template />\n```\n\n```text\nv-html\n```\n\n```js\napp.directive('inline-svg', {\n      updated: (element) => {\n        if (element.children.length === 0) {\n          return\n        }\n        const svg = element.children[0]\n        if(svg.tagName.toLowerCase() !== 'svg') {\n          return\n        }\n        for (let i = 0; i < svg.attributes.length; i++) {\n          const attr = svg.attributes.item(i)\n          element.setAttribute(attr.nodeName, attr.nodeValue)\n        }\n        svg.replaceWith(...svg.children)\n      }\n    })\n```\n\n```html\n<svg v-if=\"linkType !== null\" v-html=\"linkType\" v-inline-svg></svg>\n```\n\n========================================\n\nComments:\n- That renders nothing in Vue 2; and renders the inert `` in Vue 3.\n- I'm using that in a Vue2 project and it works there...? The Vue2 sample you linked does not have anything. I'm still keeping this answer up so people can see it's wrong.\n- I tried this originally, but nothing registers in this case. Evan mentioned in a Github issue (I can't find it currently) that templates don't support any directives\n- @PeterKrebs Yes, the Vue 2 link does not \"have anything\" (i.e., renders nothing for the ``) because using `v-html` on `` is normally not supported in Vue 2. It's interesting that it has any effect in your project. Can you a link?\n- It is not a publicly available project, sorry. The Vue2 docs have an example of using template with v-if, though.\n- I had a problem with this if I used the 'v-inline' on an element and the next sibling element had vue directives on it...essentially, none of the sibling vue enabled items processed correctly. It was as if removing/replacing the element messed up the vue 'tree' or something? Have you seen this before? Is there a 'proper' way to remove elements from the DOM without messing up Vue processing? (fyi, I'm using petite-vue but guessing same thing happens in Vue proper)\n- Its working thx bro.\n- Thanks for this. However, it seems this does not replace the wrapper element (at least not in my experiments with the code shown). Can you a link to a demo of your working code?","metadata":{"transformedAt":"2026-08-18T18:33:46.419Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":228,"estimatedTokens":1448}}338{"id":"stack-69048657","source":"stackoverflow","questionId":69048657,"title":"Dynamic layout in Vue 3 with Vite","tags":["vue.js","vue-router","vuejs3","vite"],"text":"Title: Dynamic layout in Vue 3 with Vite\nTags: vue.js, vue-router, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nNew to Vue and Vite but trying to get dynamic layouts working properly here. I believe I have what is needed but the issue it the meta seems to always come up as an empty object or `undefined`.\n\n**AppLayout.vue**\n\n```\n\n import AppLayoutDefault from './stub/AppLayoutDefault.vue'\n import { markRaw, watch } from 'vue'\n import { useRoute } from 'vue-router'\n\n const layout = markRaw(AppLayoutDefault)\n const route = useRoute()\n\n console.log('Current path: ', route.path)\n console.log('Route meta:', route.meta)\n\n watch(\n () => route.meta,\n async (meta) => {\n try {\n const component = await import(`./stub/${meta.layout}.vue`)\n layout.value = component?.default || AppLayoutDefault\n } catch (e) {\n layout.value = AppLayoutDefault\n }\n },\n { immediate: true }\n )\n\n \n\n```\n\n**App.vue**\n\n```\n\n import AppLayout from '@/layouts/AppLayout.vue'\n\n \n \n \n\n```\n\nEach and every route has the appropriate meta set with a property called `layout`.\n\nI just can't seem to get he layout applied correctly on the first load or any click of a link in the navbar(which are just router-link) for that matter.\n\n========================================\n\nTop Answer:\nThe solution from Tony is great. But you need to add computed inside the watch because it will prevent code execution for the very first \"layout\" variable initialized which is still undefined and it will cause unnecessary rendering. So, please add the computed function inside the watch function. Also you need to watch \"route.path\" not the \"route.meta?.layout\".\n\n```\nimport DefaultLayout from '@/layouts/Default.vue'\nimport { markRaw, ref } from '@vue/reactivity'\nimport { computed, watch } from '@vue/runtime-core'\nimport { useRoute } from 'vue-router'\n\nconst layout = ref()\nconst route = useRoute()\n\nwatch(\n computed(() => route.path), async () => {\n let metaLayout = route.meta?.layout\n\n try {\n const metaLayoutComponent = metaLayout && await import(`./layouts/${metaLayout}.vue`)\n\n layout.value = markRaw(metaLayoutComponent?.default || DefaultLayout)\n } catch (error) {\n layout.value = markRaw(DefaultLayout)\n }\n }\n);\n```\n\n========================================\n\nCode:\n```html\n<script setup lang=\"ts\">\n  import AppLayoutDefault from './stub/AppLayoutDefault.vue'\n  import { markRaw, watch } from 'vue'\n  import { useRoute } from 'vue-router'\n\n  const layout = markRaw(AppLayoutDefault)\n  const route = useRoute()\n\n  console.log('Current path: ', route.path)\n  console.log('Route meta:', route.meta)\n\n  watch(\n    () => route.meta,\n    async (meta) => {\n      try {\n        const component = await import(`./stub/${meta.layout}.vue`)\n        layout.value = component?.default || AppLayoutDefault\n      } catch (e) {\n        layout.value = AppLayoutDefault\n      }\n    },\n    { immediate: true }\n  )\n</script>\n\n<template>\n  <component :is=\"layout\"> <router-view /> </component>\n</template>\n```\n\n```html\n<script setup lang=\"ts\">\n  import AppLayout from '@/layouts/AppLayout.vue'\n</script>\n<template>\n  <AppLayout>\n    <router-view />\n  </AppLayout>\n</template>\n```\n\n```text\nundefined\n```\n\n```text\nlayout\n```\n\n```js\nconst layout = markRaw(AppLayoutDefault) // ❌ not reactive\n```\n\n```js\nconst layout = ref() 1️⃣\n\nwatch(\n  () => route.meta?.layout as string | undefined, 2️⃣\n  async (metaLayout) => {\n    try {\n      const component = metaLayout && await import(/* @vite-ignore */ `./${metaLayout}.vue`)\n      layout.value = markRaw(component?.default || AppLayoutDefault) 3️⃣\n    } catch (e) {\n      layout.value = markRaw(AppLayoutDefault) 3️⃣\n    }\n  },\n  { immediate: true }\n)\n```\n\n```text\nlayout\n```\n\n```text\nmarkRaw()\n```\n\n```text\nref\n```\n\n```text\nlayout\n```\n\n```text\nref\n```\n\n```text\nroute\n```\n\n```text\nroute.meta?.layout\n```\n\n```text\nlayout\n```\n\n```text\nmarkRaw()\n```\n\n```text\nimport DefaultLayout from '@/layouts/Default.vue'\nimport { markRaw, ref } from '@vue/reactivity'\nimport { computed, watch } from '@vue/runtime-core'\nimport { useRoute } from 'vue-router'\n\nconst layout = ref()\nconst route = useRoute()\n\nwatch(\n  computed(() => route.path), async () => {\n    let metaLayout = route.meta?.layout\n\n    try {\n      const metaLayoutComponent = metaLayout && await import(`./layouts/${metaLayout}.vue`)\n\n      layout.value = markRaw(metaLayoutComponent?.default || DefaultLayout)\n    } catch (error) {\n      layout.value = markRaw(DefaultLayout)\n    }\n  }\n);\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.419Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":216,"estimatedTokens":1107}}339{"id":"stack-73813428","source":"stackoverflow","questionId":73813428,"title":"Import svg as component using preact and vite","tags":["reactjs","svg","vite","preact"],"text":"Title: Import svg as component using preact and vite\nTags: reactjs, svg, vite, preact\nSource: Stack Overflow\n\nQuestion:\nI'm currently working on an application using preact, tailwindcss and vite. Unfortunately, importing svgs seems to be a bit problematic.\nThere is a separate repository that only contains the svg resources.\nMy original plan was to just import them as components as I was used to do it in classic react with webpack applications using SVGR and the following syntax:\n\n```\nimport { ReactComponent as Search } from 'assets/icons/search-lg.svg';\n```\n\nThis won't work for (at least) two reasons. One being preact the other one being the lack of SVGR.\nI then proceeded to give vite-plugin-svgr a try by importing it in my `vite.config.js`.\n\n```\nplugins: [svgr({ svgrOptions: { jsxRuntime: 'classic-preact' } }), preact(), tsconfigPaths()],\n```\n\nIt *kinda* works using the following import syntax:\n\n```\nimport Search from 'assets/icons/search-lg.svg?component';\n```\n\nUnfortunately this raises the following error which I couldn't manage to work around besides ignoring it which is not really an option:\n\n```\nTS2307: Cannot find module 'assets/icons/search-lg.svg?component' or its corresponding type declarations\n```\n\nThe alternate plan would now be to create a wrapper component that just imports the svg from the given path and create a component from it myself. This would also simplify styling it with tailwind.\nUnfortunately I fail to import the file in a way I can wrap it with `` tags. Using `` is not really an option because I need to be able to manipulate the svg.\n\nSo, does anybody have an idea how to either\n\n- correctly use the component import in my setup\n\n- create a preact component that imports an svg from a file and still is customizable\n\nThanks in advance!\n\n========================================\n\nCode:\n```text\nimport { ReactComponent as Search } from 'assets/icons/search-lg.svg';\n```\n\n```text\nplugins: [svgr({ svgrOptions: { jsxRuntime: 'classic-preact' } }), preact(), tsconfigPaths()],\n```\n\n```text\nimport Search from 'assets/icons/search-lg.svg?component';\n```\n\n```text\nTS2307: Cannot find module 'assets/icons/search-lg.svg?component' or its corresponding type declarations\n```\n\n```text\nvite.config.js\n```\n\n```text\n<svg>\n```\n\n```text\n<img>\n```\n\n```text\nimport { ReactComponent as Search } from 'assets/icons/search-lg.svg';\n```\n\n```text\n/// <reference types=\"vite-plugin-svgr/client\" />\n```\n\n```text\nvite-env.d.ts\n```\n\n========================================\n\nComments:\n- What about this plugin github.com/pd4d10/vite-plugin-svgr? Example stackblitz.com/edit/vitejs-vite-qk88v1\n- @qk88v1 the plugin I used was a fork of the one you linked I think. I tried yours and found the issue I guess. I was missing `&#47;&#47;&#47; ` in vite-env.d.ts. Thanks so much for pointing me in the right direction\n- FWIW, `svgr` is a really, really poor way to use SVGs and it should be avoided if at all possible. See twitter.com/_developit/status/1382838799420514317\n- Interesting, thank you! What alternative would you choose given that it should be possible to manipulate the svg with tailwind/css?\n- `` is probably what you want: developer.mozilla.org/en-US/docs/Web/SVG/Element/use","metadata":{"transformedAt":"2026-08-18T18:33:46.419Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":94,"estimatedTokens":803}}340{"id":"stack-75223542","source":"stackoverflow","questionId":75223542,"title":"How to use environment variables in Sveltekit 1.0?","tags":["environment-variables","vite","sveltekit"],"text":"Title: How to use environment variables in Sveltekit 1.0?\nTags: environment-variables, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have an .env file which contains two sensitive items and two non-sensitive. Running Sveltekit 1.0 and using Netlify Serverless functions with a db-helper file which has\n\n```\nrequire('dotenv').config();\nconst dbName = process.env.MONGODB_DATABASE;\n```\n\nand similarly gets the other variables. However, this crashes with error \"cant find module 'dotenv'!\n\nI tried, with same error ..\n\n```\nconst dbName = import.meta.env.MONGODB_DATABASE\n```\n\nI tried process.env['MONGODB_DATABASE'] and import.meta.env['MONGODB_DATABASE']. Failed.\n\nI tried prefixing env vars with VITE using both process.env and import.meta.env with and without [' '] wrapper. Failed.\n\nI read that you dont have to explicitly load dotenv as Vite does this. Tried without. Failed.\n\nHas anyone got a solution to this?\n\n========================================\n\nTop Answer:\nI was using\n\n```\nrequire('dotenv').config()\n```\n\nwhich worked locally but gave a \"cannot find module dotenv\" when deployed (to Netlify). I found that in I used \"import\" instead of \"require\" then it worked ..\n\n```\nimport dotenv from 'dotenv';\ndotenv.config();\n```\n\nSo thats a solution. But, H.B. correctly pointed out the new sveltekit way env variables should be used. Thanks for that.\n\nPS. The require/import also fails/works for jsonwebtoken so use *import * as jwt from 'jsonwebtoken'* instead of *const jwt = require('jsonwebtoken')*\n\n========================================\n\nCode:\n```text\nrequire('dotenv').config();\nconst dbName = process.env.MONGODB_DATABASE;\n```\n\n```text\nconst dbName = import.meta.env.MONGODB_DATABASE\n```\n\n```text\n$env/dynamic/private\n```\n\n```text\n$env/dynamic/public\n```\n\n```text\n$env/static/private\n```\n\n```text\n$env/static/public\n```\n\n```text\nPUBLIC_\n```\n\n```text\n.env\n```\n\n```text\nrequire('dotenv').config()\n```\n\n```text\nimport dotenv from 'dotenv';\ndotenv.config();\n```\n\n========================================\n\nComments:\n- Is this crash in the client-side code? I.e. in the web browser not in node.js.\n- Runs fine locally. Deployed to Netlify it crashes. So server side. The web app runs fine otherwise on Netlify and the build shows no errors. Its how to handle the environment variables, server-side.\n- Thanks. I cant figure out yet how to implement the linked docs methods but thanks for these. Meanwhile, I set up the environment variables on Netlify and removed the require('dotenv').config() from my db_helper file and the deployed app is now working fine, so that a workaround till I get my head around the documented methods. Thanks again.","metadata":{"transformedAt":"2026-08-18T18:33:46.419Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":99,"estimatedTokens":665}}341{"id":"stack-74076180","source":"stackoverflow","questionId":74076180,"title":"Vitest - ReferenceError: File Is Not Defined","tags":["typescript","vue.js","vite","vitest"],"text":"Title: Vitest - ReferenceError: File Is Not Defined\nTags: typescript, vue.js, vite, vitest\nSource: Stack Overflow\n\nQuestion:\nI'm usually able to use `File` wherever I want to in my code, but for some reason when I try using it in vitest it throws this error. Why does this happen and how can I resolve this error?\n\nHere is my `vite.config.ts`\n\n```\n/// \nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// Configure Vitest (https://vitest.dev/config/)\nexport default defineConfig({\n test: {\n /* for example, use global to avoid globals imports (describe, test, expect): */\n // globals: true,\n },\n plugins: [vue()],\n})\n```\n\nAnd here is my test file code.\n\n```\nimport { assert, expect, test } from 'vitest'\n\ntest('File', () => {\n let applicationZip = new File(new Array(), \"Mock.zip\", { type: 'application/zip' })\n})\n```\n\nWhenever I run vitest it throws the following error.\n\n```\nReferenceError: File is not defined\n ❯ test/basic.test.ts:25:23\n 23| \n 24| test('File', () => {\n 25| let applicationZip = new File(new Array(), \"Mock.zip\", { type: 'application/zip' })\n | ^\n 26| })\n 27|\n```\n\n========================================\n\nCode:\n```text\n/// <reference types=\"vitest\" />\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// Configure Vitest (https://vitest.dev/config/)\nexport default defineConfig({\n  test: {\n    /* for example, use global to avoid globals imports (describe, test, expect): */\n    // globals: true,\n  },\n  plugins: [vue()],\n})\n```\n\n```text\nimport { assert, expect, test } from 'vitest'\n\ntest('File', () => {\n  let applicationZip = new File(new Array<Blob>(), \"Mock.zip\", { type: 'application/zip' })\n})\n```\n\n```text\nReferenceError: File is not defined\n ❯ test/basic.test.ts:25:23\n     23| \n     24| test('File', () => {\n     25|   let applicationZip = new File(new Array<Blob>(), \"Mock.zip\", { type: 'application/zip' })\n       |                       ^\n     26| })\n     27|\n```\n\n```text\nFile\n```\n\n```text\nvite.config.ts\n```\n\n```text\n/// <reference types=\"vitest\" />\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\nexport default defineConfig({\n  plugins: [vue()],\n  test: {\n    globals: true,\n    environment: \"jsdom\",\n  },\n  root: \".\",\n})\n```\n\n```text\nFile\n```\n\n```text\nFile\n```\n\n```text\nvite.config.ts\n```\n\n========================================\n\nComments:\n- Thanks! For React with typescript, I had to put test section in a separate vitest.config.ts as described here: vitest.dev/config. BR","metadata":{"transformedAt":"2026-08-18T18:33:46.419Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":123,"estimatedTokens":623}}342{"id":"stack-77061660","source":"stackoverflow","questionId":77061660,"title":"Scope CSS with React + Vite","tags":["reactjs","vite"],"text":"Title: Scope CSS with React + Vite\nTags: reactjs, vite\nSource: Stack Overflow\n\nQuestion:\nI am new to react and have researched a lot but I couldn't find a solution for my specific problem. I have a 20'000 line long CSS and a long HTML file from someone else. I have to display it on my website (I can't use an iframe due to technical reasons). So I created a react component that returns the HTML and I imported the CSS file, which is now messing up the style of the rest of the website.\n\nHow can I scope the CSS to only be applied to that component? As the file is so long, I can't just add more specific classes to every CSS selector. Obviously, I can't use inline styles and I also can't use modules because not everything in that CSS file is under a specific class. For example, there is this in the CSS: `input[type=\"text\"]{...}` (without a class or id that would differentiate between my own text inputs).\n\nAm I missing something?\n\n========================================\n\nCode:\n```text\ninput[type=\"text\"]{...}\n```\n\n```none\nimport \"./styles.scss\";\n\nconst MyComponent = () => (\n  <div id=\"scoped\">\n    {/* ... */}\n  </div>\n);\n\nexport default MyComponent;\n```\n\n```scss\n#scoped {\n  // CSS here\n}\n```\n\n```text\nnpm add -D sass\n```\n\n```text\nhtml\n```\n\n```text\nsass\n```\n\n========================================\n\nComments:\n- I there a reason why you can't edit the file?\n- @Arkellys I'm sorry, I didn't write that clearly. I am able to edit the file. What I meant was that I am not able to add classes to every CSS selector to narrow it down to only elements that are part of that component, because the file is so long.","metadata":{"transformedAt":"2026-08-18T18:33:46.420Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":53,"estimatedTokens":405}}343{"id":"stack-77037900","source":"stackoverflow","questionId":77037900,"title":"import module relative to source root directory in Cypress tests","tags":["cypress","vite"],"text":"Title: import module relative to source root directory in Cypress tests\nTags: cypress, vite\nSource: Stack Overflow\n\nQuestion:\nIn my app that's build with Vite I can import modules relative to the source root directory with\n\n```\nimport { randomId } from '@/utils/string-utils'\n```\n\nThis works because in my `vite.config.js` I've defined this alias\n\n```\nresolve: {\n alias: {\n '@': path.resolve(__dirname, \"./src\")\n }\n}\n```\n\nBut Cypress doesn't know anything about this, so if I want to import the module above in a Cypress file, I have to use something like\n\n```\nimport { randomId } from '../../../../src/utils/string-utils'\n```\n\nThis is tedious and error-prone, because if the Cypress directory structure changed, the import may no longer work. Is it possible to define something similar to the `@` alias that will work in Cypress?\n\n========================================\n\nTop Answer:\nTo do this, you need to create a tsconfig.json file in your Cypress directory and configure the baseUrl and paths options. see below\n\n```\n// cypress/tsconfig.json\n{\n \"compilerOptions\": {\n \"baseUrl\": \"../src\", // Set the base directory for resolving modules\n \"paths\": {\n \"@/*\": [\"*\"] // Define aliases here\n }\n },\n \"include\": [\"**/*.ts\"]\n}\n```\n\nthen you can use it below\n\n```\n// cypress/integration/test-file.ts\nimport { randomId } from '@/utils/string-utils'; // Use the alias here\n```\n\nif your project is in Javascript\n\nyou can create a custom alias for importing modules in Cypress by configuring the Webpack bundler used by Cypress. To set up an alias, you can use the webpack.config.js file within your Cypress directory.\n\nCreate a webpack.config.js file in your Cypress directory ( at cypress/webpack.config.js) .\n\nIn the webpack.config.js file, configure the aliases by defining a resolve section in the Webpack configuration. You can set up an alias that points to your project's source directory. For example:\n\n```\n// cypress/weboack.config.js\nconst path = require('path');\n\nmodule.exports = (on, config) => {\n config.resolve.alias = {\n '@': path.resolve(__dirname, '../src'), // Adjust the path as needed\n };\n\n // Other configurations...\n\n return config;\n};\n```\n\nusage\n\n========================================\n\nCode:\n```text\nimport { randomId } from '@/utils/string-utils'\n```\n\n```text\nresolve: {\n  alias: {\n    '@': path.resolve(__dirname, \"./src\")\n  }\n}\n```\n\n```text\nimport { randomId } from '../../../../src/utils/string-utils'\n```\n\n```text\nvite.config.js\n```\n\n```text\n@\n```\n\n```js\nimport { defineConfig } from 'cypress'\nimport vitePreprocessor from 'cypress-vite'\nimport { fileURLToPath } from 'node:url'\n\nexport default defineConfig({\n  e2e: {\n    setupNodeEvents(on, config) {\n      on(\n        'file:preprocessor',\n        vitePreprocessor({\n          resolve: {\n            alias: {\n              // define two aliases\n              '@cy': fileURLToPath(new URL('./cypress', import.meta.url)),\n              '@': fileURLToPath(new URL('../../src', import.meta.url))\n            }\n          }\n        })\n      )\n    },\n    baseUrl: 'http://localhost:8081'\n  }\n})\n```\n\n```text\ncypress.config.js\n```\n\n```text\n// cypress/tsconfig.json\n{\n  \"compilerOptions\": {\n    \"baseUrl\": \"../src\", // Set the base directory for resolving modules\n    \"paths\": {\n      \"@/*\": [\"*\"] // Define aliases here\n    }\n  },\n  \"include\": [\"**/*.ts\"]\n}\n```\n\n```text\n// cypress/integration/test-file.ts\nimport { randomId } from '@/utils/string-utils'; // Use the alias here\n```\n\n```text\n// cypress/weboack.config.js\nconst path = require('path');\n\nmodule.exports = (on, config) => {\n  config.resolve.alias = {\n    '@': path.resolve(__dirname, '../src'), // Adjust the path as needed\n  };\n\n  // Other configurations...\n\n  return config;\n};\n```\n\n========================================\n\nComments:\n- How would you do it for a Javascript project?\n- updated my ans for javascript.\n- Thanks - feels like somethings missing?\n- This might work for a project using Webpack, but I'm using Vite","metadata":{"transformedAt":"2026-08-18T18:33:46.420Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":176,"estimatedTokens":990}}344{"id":"stack-77544208","source":"stackoverflow","questionId":77544208,"title":"How to run React Vite project correctly in production mode?","tags":["reactjs","vite"],"text":"Title: How to run React Vite project correctly in production mode?\nTags: reactjs, vite\nSource: Stack Overflow\n\nQuestion:\nI'm using Vite with React, I want to run the project in production mode on a server.\nThis is the `vite.config.js` :\n\n```\nexport default defineConfig({\n esbuild: {\n loader: \"jsx\",\n },\n optimizeDeps: {\n esbuildOptions: {\n loader: {\n \".js\": \"jsx\",\n },\n },\n },\n server: {\n port: 3000,\n }\n});\n```\n\nAnd in the running pod on the server after deployment, I have this log :\n\n```\nEnvironment:\nDEV_MODE=false\nNODE_ENV=production\nDEBUG_PORT=XXXX\nLaunching via npm...\n> my-project start\n> vite\nnpm http fetch GET 200 https://registry.npmjs.org/npm 2333ms (cache miss)\nVITE v4.3 ready in 2303 ms\n➜ Local: http://127.0.0.1:3000/\n➜ Network: use --host to expose\n```\n\nIs it normal to have it running like that? Also on the port 3000? it looks like the log I get in my localhost.\n\nIf not, how can I run the project correctly in production mode and what's the right Vite config for it please?\n\nAnd using `react-react-app`:\n\n```\nEnvironment:\nDEV_MODE=false\nNODE_ENV=production\nDEBUG_PORT=XXXX\nLaunching via npm...\nnpm info it worked if it ends with ok\nnpm info using npm\nnpm info using node\n> @my-app start /opt/app-root/src\n> react-scripts start\nℹ 「wds」: Project is running at http://XX.XX.XXX.XXX/\nℹ 「wds」: webpack output is served from\nℹ 「wds」: Content not from webpack is served from /opt/app-root/src/public\nℹ 「wds」: 404s will fallback to /\nStarting the development server...\n```\n\n========================================\n\nTop Answer:\nAdding a docker compose option to run Vite in production:\n\ndocker-compose-prod.yml\n\n```\nservices:\n vite-react-app:\n container_name: vite-react-app-prod\n image: nginx:latest\n ports:\n - \"80:80\"\n volumes:\n - ./dist:/usr//nginx/html\n depends_on:\n - build-app\n\n build-app:\n image: node:23\n container_name: vite-react-build\n working_dir: /app\n volumes:\n - .:/app\n - /app/node_modules\n command: >\n sh -c \"npm install && npm run build\"\n```\n\nThen:\n\n```\ndocker compose -f docker-compose-prod.yml build \ndocker compose -f docker-compose-prod.yml up\n```\n\n========================================\n\nCode:\n```text\nexport default defineConfig({\n  esbuild: {\n    loader: \"jsx\",\n  },\n  optimizeDeps: {\n    esbuildOptions: {\n      loader: {\n        \".js\": \"jsx\",\n      },\n    },\n  },\n  server: {\n    port: 3000,\n  }\n});\n```\n\n```text\nEnvironment:\nDEV_MODE=false\nNODE_ENV=production\nDEBUG_PORT=XXXX\nLaunching via npm...\n> my-project start\n> vite\nnpm http fetch GET 200 https://registry.npmjs.org/npm 2333ms (cache miss)\nVITE v4.3 ready in 2303 ms\n➜ Local: http://127.0.0.1:3000/\n➜ Network: use --host to expose\n```\n\n```text\nEnvironment:\nDEV_MODE=false\nNODE_ENV=production\nDEBUG_PORT=XXXX\nLaunching via npm...\nnpm info it worked if it ends with ok\nnpm info using npm\nnpm info using node\n> @my-app start /opt/app-root/src\n> react-scripts start\nℹ 「wds」: Project is running at http://XX.XX.XXX.XXX/\nℹ 「wds」: webpack output is served from\nℹ 「wds」: Content not from webpack is served from /opt/app-root/src/public\nℹ 「wds」: 404s will fallback to /\nStarting the development server...\n```\n\n```text\nvite.config.js\n```\n\n```text\nreact-react-app\n```\n\n```text\nFROM node:18-alpine3.17 as build\n\nWORKDIR /app\nCOPY . /app\n\nRUN npm install\nRUN npm run build\n\nFROM ubuntu\nRUN apt-get update\nRUN apt-get install nginx -y\nCOPY --from=build /app/dist /var/www/html/\nEXPOSE 80\nCMD [\"nginx\",\"-g\",\"daemon off;\"]\n```\n\n```bash\ndocker build -t vite-app .\ndocker run -p 80:80 vite-app\n```\n\n```text\nvite\n```\n\n```text\nvite\n```\n\n```text\nvite build\n```\n\n```text\nservices:\n  vite-react-app:\n    container_name: vite-react-app-prod\n    image: nginx:latest\n    ports:\n      - \"80:80\"\n    volumes:\n      - ./dist:/usr/share/nginx/html\n    depends_on:\n      - build-app\n\n  build-app:\n    image: node:23\n    container_name: vite-react-build\n    working_dir: /app\n    volumes:\n      - .:/app\n      - /app/node_modules\n    command: >\n      sh -c \"npm install && npm run build\"\n```\n\n```text\ndocker compose -f docker-compose-prod.yml build \ndocker compose -f docker-compose-prod.yml up\n```\n\n========================================\n\nComments:\n- For frontend app only, you should not run a server. The only thing you need to do is to build your app and serve it as static files.\n- *\"I don't have much control of the server\"* - in that case there's not much we can do either. You need to speak to whoever *does* have control of how it's deployed.\n- @jonrsharpe I need to know first if that log is what I should probobaly expect or there's something wrong with my Vite configuration. I want to know people's opinion about this matter.\n- If you're just asking *\"should I run the dev server in production?\"*, then: no, it's the *dev* server.\n- When build react in production mode, you should remove `React.StrictMode` because it only run in development mode.\n- @Dwix please contact your manager to deploy your frontend application in some cloud solution, AWS::CloudFront and AWS::S3, I believe an organization has the budget. If it just an application for internal usage, have fun with my solution, it is ok.","metadata":{"transformedAt":"2026-08-18T18:33:46.420Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":235,"estimatedTokens":1271}}345{"id":"stack-67992023","source":"stackoverflow","questionId":67992023,"title":"Vue devServer.proxy in vue.config.js not working","tags":["vue.js","vite"],"text":"Title: Vue devServer.proxy in vue.config.js not working\nTags: vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI'm using the following configuration in my `vue.config.js` located in the root of my repository and it's not working.\n\n```\nmodule.exports = {\n devServer: {\n proxy: \"http://localhost:3030\"\n }\n }\n```\n\nand this is how I'm trying to call it\n\n```\nreturn await fetch(\"/posts\", options).then((response) =>\n response.json()\n ).catch(e => console.log(\"Error fetching posts\", e));\n```\n\nhowever when I change the calling code to the code shown below everything works\n\n```\nreturn await fetch(\"http://localhost:3030/posts\", options).then((response) =>\n response.json()\n ).catch(e => console.log(\"Error fetching posts\", e));\n```\n\n**Edit**:\n\nI should have mentioned that I'm using Vite for builds as that was causing some other problems for me with environment variables so it's possible they are causing problems with proxies too.\n\nI looked into this more and it turns out that Vite does have proxy features and so I tried updating my code to use their proxy with still no luck.\n\n```\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [vue()],\n server: {\n \"/posts\": \"http://localhost:3030/posts\"\n }\n})\n```\n\n========================================\n\nCode:\n```js\nmodule.exports = {\n    devServer: {\n        proxy: \"http://localhost:3030\"\n      }\n  }\n```\n\n```js\nreturn await fetch(\"/posts\", options).then((response) =>\n    response.json()\n  ).catch(e => console.log(\"Error fetching posts\", e));\n```\n\n```js\nreturn await fetch(\"http://localhost:3030/posts\", options).then((response) =>\n    response.json()\n  ).catch(e => console.log(\"Error fetching posts\", e));\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue()],\n  server: {\n    \"/posts\": \"http://localhost:3030/posts\"\n  }\n})\n```\n\n```text\nvue.config.js\n```\n\n```js\n\"/posts\": \"http://localhost:3030/posts\"\n                                ^^^^^^\n```\n\n```js\n\"/posts\": \"http://localhost:3030\"\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  server: {\n    proxy: {\n      '/posts': 'http://localhost:3030'\n    }\n  }\n})\n```\n\n```text\nvue.config.js\n```\n\n```text\nvite.config.js\n```\n\n```text\nserver.proxy\n```\n\n```text\n/posts\n```\n\n========================================\n\nComments:\n- `proxy` takes an object as the argument, where the property 'key' is a path. What are you trying to achieve here?\n- @match I'm wanting the call to `fetch(\"&#47;posts\", options)` to resolve to `http:&#47;&#47;localhost:3030&#47;posts` in dev builds","metadata":{"transformedAt":"2026-08-18T18:33:46.420Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":135,"estimatedTokens":689}}346{"id":"stack-73631193","source":"stackoverflow","questionId":73631193,"title":"How to expose vite js host to the outside docker","tags":["laravel","docker","vite"],"text":"Title: How to expose vite js host to the outside docker\nTags: laravel, docker, vite\nSource: Stack Overflow\n\nQuestion:\nI'm new in vite js when upgrade from Laravel version 8 to 9.\nI'm building docker for a Laravel 9 project use vite js. There is a problem: I can't expose host of resources out of docker containers. It's still working in the inside docker containers.\nAre there any advice ? Thanks.\n\nThis is my docker-compose file\n\n```\nversion: \"3.9\"\n\nservices:\n nginx:\n image: nginx:1.23-alpine\n ports:\n - 80:80\n mem_limit: \"512M\"\n volumes:\n - type: bind\n source: ./api\n target: /usr//nginx/html/api\n - type: bind\n source: ./docker/nginx/dev/default.conf\n target: /etc/nginx/conf.d/default.conf\n\n php:\n platform: linux/amd64\n build:\n context: .\n dockerfile: ./docker/php/dev/Dockerfile\n mem_limit: \"512M\"\n volumes:\n - type: bind\n source: ./api\n target: /usr//nginx/html/api\n\n oracle:\n platform: linux/amd64\n image: container-registry.oracle.com/database/express:21.3.0-xe\n ports:\n - 1521:1521\n # - 5500:5500\n volumes:\n - type: volume\n source: oracle\n target: /opt/oracle/oradata\n\nvolumes:\n oracle:\n```\n\n========================================\n\nTop Answer:\nThere has been voiced downsides to named volumes @David Maze.\n\nSince you can't access the contents of a named volume from outside of Docker, they're harder to back up and manage, and a poor match for tasks like injecting config files and reviewing logs.\n\nWould you try altering all volume types to bind.\n\nMount volume from host in Dockerfile long format\n\n========================================\n\nCode:\n```text\nversion: \"3.9\"\n\nservices:\n  nginx:\n    image: nginx:1.23-alpine\n    ports:\n      - 80:80\n    mem_limit: \"512M\"\n    volumes:\n      - type: bind\n        source: ./api\n        target: /usr/share/nginx/html/api\n      - type: bind\n        source: ./docker/nginx/dev/default.conf\n        target: /etc/nginx/conf.d/default.conf\n\n  php:\n    platform: linux/amd64\n    build:\n      context: .\n      dockerfile: ./docker/php/dev/Dockerfile\n    mem_limit: \"512M\"\n    volumes:\n      - type: bind\n        source: ./api\n        target: /usr/share/nginx/html/api\n\n  oracle:\n    platform: linux/amd64\n    image: container-registry.oracle.com/database/express:21.3.0-xe\n    ports:\n      - 1521:1521\n      # - 5500:5500\n    volumes:\n      - type: volume\n        source: oracle\n        target: /opt/oracle/oradata\n\nvolumes:\n  oracle:\n```\n\n```text\n\"scripts\": {\n  \"dev\": \"vite --host\",\n  \"build\": \"vite build\"\n}\n```\n\n```text\nphp:\n    platform: linux/amd64\n    build:\n      context: .\n      dockerfile: ./docker/php/dev/Dockerfile\n    mem_limit: \"512M\"\n    ports:\n      - 5173:5173\n    volumes:\n      - type: bind\n        source: ./api\n        target: /usr/share/nginx/html/api\n```\n\n========================================\n\nComments:\n- It would be helpful to know what you tried. For example have you tried (if you are using just docker) to use the `-p` option (described here)? Or if you are using docker-compose have you tried using ports?\n- thank you @katxeus, but it does not work","metadata":{"transformedAt":"2026-08-18T18:33:46.420Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":138,"estimatedTokens":758}}347{"id":"stack-72995266","source":"stackoverflow","questionId":72995266,"title":"Unable to Install @vitejs/plugin-vue inside Laravel project","tags":["laravel","vue.js","vite","laravel-vite"],"text":"Title: Unable to Install @vitejs/plugin-vue inside Laravel project\nTags: laravel, vue.js, vite, laravel-vite\nSource: Stack Overflow\n\nQuestion:\nI created a fresh Laravel project. And to use Vue JS I tried installing this package,\n\n```\n@vitejs/plugin-vue\n```\n\nBut this throws me a set of errors,\n\n```\nnpm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.\nnpm ERR! code ERESOLVE\nnpm ERR! ERESOLVE could not resolve\nnpm ERR! \nnpm ERR! While resolving: @vitejs/plugin-vue@3.0.0\nnpm ERR! Found: vite@2.9.14\nnpm ERR! node_modules/vite\nnpm ERR! dev vite@\"^2.9.11\" from the root project\nnpm ERR! peer vite@\"^2.9.9\" from laravel-vite-plugin@0.4.0\nnpm ERR! node_modules/laravel-vite-plugin\nnpm ERR! dev laravel-vite-plugin@\"^0.4.0\" from the root project\nnpm ERR!\nnpm ERR! Could not resolve dependency:\nnpm ERR! peer vite@\"^3.0.0\" from @vitejs/plugin-vue@3.0.0\nnpm ERR! node_modules/@vitejs/plugin-vue\nnpm ERR! @vitejs/plugin-vue@\"^3.0.0\" from the root project\nnpm ERR!\nnpm ERR! Conflicting peer dependency: vite@3.0.0\nnpm ERR! node_modules/vite\nnpm ERR! peer vite@\"^3.0.0\" from @vitejs/plugin-vue@3.0.0\nnpm ERR! node_modules/@vitejs/plugin-vue\nnpm ERR! @vitejs/plugin-vue@\"^3.0.0\" from the root project\nnpm ERR!\nnpm ERR! Fix the upstream dependency conflict, or retry\nnpm ERR! this command with --force, or --legacy-peer-deps\nnpm ERR! to accept an incorrect (and potentially broken) dependency resolution.\n```\n\nI followed these steps,\n\n```\n1.laravel new {proj_name}.\n\n2. npm install vue@next.\n\n3. npm install.\n\n4. After that I created a vue file and imported into app.js (resources/js/app.js).\n\n5. I went to the blade file and cleared all -> hit `!` for emmet snippet, created a div with id #app, and add\n @vite('resources/js/app.js').\n```\n\n**I throw an error saying install @vitejs/plugin-vue. But when I try to install that it throws me those errors.**\n\n========================================\n\nTop Answer:\nIf someone else is facing this issue add it directly to your package.json and then run npm i:\n\n\"@vitejs/plugin-vue\": \"^3.0.1\"\n\n========================================\n\nCode:\n```text\n@vitejs/plugin-vue\n```\n\n```text\nnpm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.\nnpm ERR! code ERESOLVE\nnpm ERR! ERESOLVE could not resolve\nnpm ERR! \nnpm ERR! While resolving: @vitejs/plugin-vue@3.0.0\nnpm ERR! Found: vite@2.9.14\nnpm ERR! node_modules/vite\nnpm ERR!   dev vite@\"^2.9.11\" from the root project\nnpm ERR!   peer vite@\"^2.9.9\" from laravel-vite-plugin@0.4.0\nnpm ERR!   node_modules/laravel-vite-plugin\nnpm ERR!     dev laravel-vite-plugin@\"^0.4.0\" from the root project\nnpm ERR!\nnpm ERR! Could not resolve dependency:\nnpm ERR! peer vite@\"^3.0.0\" from @vitejs/plugin-vue@3.0.0\nnpm ERR! node_modules/@vitejs/plugin-vue\nnpm ERR!   @vitejs/plugin-vue@\"^3.0.0\" from the root project\nnpm ERR!\nnpm ERR! Conflicting peer dependency: vite@3.0.0\nnpm ERR! node_modules/vite\nnpm ERR!   peer vite@\"^3.0.0\" from @vitejs/plugin-vue@3.0.0\nnpm ERR!   node_modules/@vitejs/plugin-vue\nnpm ERR!     @vitejs/plugin-vue@\"^3.0.0\" from the root project\nnpm ERR!\nnpm ERR! Fix the upstream dependency conflict, or retry\nnpm ERR! this command with --force, or --legacy-peer-deps\nnpm ERR! to accept an incorrect (and potentially broken) dependency resolution.\n```\n\n```text\n1.laravel new {proj_name}.\n\n\n\n2. npm install vue@next.\n\n\n\n3. npm install.\n\n\n\n4. After that I created a vue file and imported into app.js (resources/js/app.js).\n\n\n\n5. I went to the blade file and cleared all -> hit `!` for emmet snippet, created a div with id #app, and add\n    @vite('resources/js/app.js').\n```\n\n```text\nnpm install vue@next vue-loader@next\nnpm i @vitejs/plugin-vue@2.3.3\ncomposer require innocenzi/laravel-vite:0.2.*\nnpm i -D vite vite-plugin-laravel\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport laravel from 'vite-plugin-laravel'\n\nexport default defineConfig({\n    plugins: [\n        vue(),\n        laravel({\n        input: [\n            'resources/css/app.css',\n            'resources/js/app.js',\n        ],\n        refresh: true,\n    })\n    ]\n})\n```\n\n```text\nimport {createApp} from 'vue/dist/vue.esm-bundler.js';\n```\n\n```text\nimport {createApp, defineAsyncComponent} from 'vue/dist/vue.esm-bundler.js';\n```\n\n========================================\n\nComments:\n- I just installed npm i @vitejs/plugin-vue@2.3.3 and it worked thanks","metadata":{"transformedAt":"2026-08-18T18:33:46.420Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":161,"estimatedTokens":1106}}348{"id":"stack-72442802","source":"stackoverflow","questionId":72442802,"title":"vite build styles have to be imported separately","tags":["vue.js","vite"],"text":"Title: vite build styles have to be imported separately\nTags: vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI have a vue3+vite package and I want to publish it to npm, but when I import it to a test project I have to import styles from the dist folder separately, but I want my styles to be imported as my package registers as demonstrated below\n\nhow I import now:\n\n```\nimport myComp from 'foo'\napp.use(myComp)\nimport 'foo/dist/style.css'\n```\n\nwhat I want:\n\n```\nimport myComp from 'foo'\napp.use(myComp)\n// and styles work out of the box\n```\n\ninstall.ts(entry):\n\n```\n// @ts-ignore\nimport componentRegisterer from './plugins/components.ts'\n// @ts-ignore\nimport mixins from './plugins/mixins.ts'\n\nexport default {\n install: (app: any, options: any): void => {\n app.mixin(mixins)\n componentRegisterer(app)\n }\n}\n```\n\nvite.config.js:\n\n```\n/// \nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport vueI18n from '@intlify/vite-plugin-vue-i18n'\n\n// https://vitejs.dev/config/\nconst path = require(\"path\")\nexport default defineConfig({\n test: {\n setupFiles: ['./tests/config.ts']\n },\n build: {\n lib: {\n entry: path.resolve(__dirname, 'src/install.ts'),\n name: 'vcp',\n fileName: (format) => `vcp.${format}.ts`\n },\n rollupOptions: {\n external: ['vue', 'vueI18n'],\n output: {\n exports: 'named',\n globals: {\n vue: 'Vue',\n vcp: 'Vcp'\n }\n }\n },\n },\n plugins: [\n vue(),\n vueI18n({\n include: path.resolve(__dirname, 'src/assets/translations.ts'),\n globalSFCScope: true,\n compositionOnly: false,\n }),\n ],\n server: {\n port: 8080\n },\n resolve: {\n dedupe: ['vue'],\n alias: {\n \"~\": path.resolve(__dirname, \"./src\"),\n \"@\": path.resolve(__dirname, \"./src\"),\n },\n },\n})\n```\n\npackage.json:\n\n```\n{\n \"name\": \"vcp\",\n \"version\": \"0.9.11\",\n \"private\": false,\n \"author\": \"Alireza Safari (http://alireza-safari.ir)\",\n \"license\": \"MIT\",\n \"main\": \"./dist/vcp.umd.ts\",\n \"description\": \"Vue Client Print with Template Builder\",\n \"exports\": {\n \".\": {\n \"require\": \"./dist/vcp.umd.ts\"\n },\n \"./dist/style.css\": \"./dist/style.css\"\n },\n \"keywords\": [\n \"vcp\",\n \"vue print\",\n \"vue client print\",\n \"template builder\",\n \"vue report\",\n \"vue report generator\"\n ],\n \"files\": [\n \"dist/*\"\n ],\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/alireza0sfr/vue-client-print\"\n },\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"serve\": \"vite preview\",\n \"test\": \"vitest run --environment jsdom\",\n \"test:ui:\": \"vitest --environment jsdom --ui\",\n \"test:coverage\": \"vitest run --coverage --environment jsdom\",\n \"test:watch\": \"vitest --environment jsdom\"\n },\n \"dependencies\": {\n \"dom-to-image\": \"^2.6.0\",\n \"file-saver\": \"^2.0.5\",\n \"jsdom\": \"^19.0.0\",\n \"print-js\": \"^1.6.0\",\n \"register-service-worker\": \"^1.7.2\",\n \"typescript\": \"^4.7.2\",\n \"vitest\": \"^0.12.9\",\n \"vue\": \"^3.2.36\",\n \"vue-i18n\": \"^9.1.10\"\n },\n \"devDependencies\": {\n \"@intlify/vite-plugin-vue-i18n\": \"^3.4.0\",\n \"@vitejs/plugin-vue\": \"^2.3.3\",\n \"@vitest/ui\": \"^0.12.9\",\n \"@vue/compiler-sfc\": \"^3.2.36\",\n \"@vue/test-utils\": \"^2.0.0-rc.18\",\n \"c8\": \"^7.11.3\",\n \"cz-conventional-changelog\": \"^3.0.1\",\n \"vite\": \"^2.9.9\"\n }\n}\n```\n\n========================================\n\nCode:\n```text\nimport myComp from 'foo'\napp.use(myComp)\nimport 'foo/dist/style.css'\n```\n\n```text\nimport myComp from 'foo'\napp.use(myComp)\n// and styles work out of the box\n```\n\n```text\n// @ts-ignore\nimport componentRegisterer from './plugins/components.ts'\n// @ts-ignore\nimport mixins from './plugins/mixins.ts'\n\nexport default {\n  install: (app: any, options: any): void => {\n    app.mixin(mixins)\n    componentRegisterer(app)\n  }\n}\n```\n\n```text\n/// <reference types=\"vitest\" />\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport vueI18n from '@intlify/vite-plugin-vue-i18n'\n\n// https://vitejs.dev/config/\nconst path = require(\"path\")\nexport default defineConfig({\n  test: {\n    setupFiles: ['./tests/config.ts']\n  },\n  build: {\n    lib: {\n      entry: path.resolve(__dirname, 'src/install.ts'),\n      name: 'vcp',\n      fileName: (format) => `vcp.${format}.ts`\n    },\n    rollupOptions: {\n      external: ['vue', 'vueI18n'],\n      output: {\n        exports: 'named',\n        globals: {\n          vue: 'Vue',\n          vcp: 'Vcp'\n        }\n      }\n    },\n  },\n  plugins: [\n    vue(),\n    vueI18n({\n      include: path.resolve(__dirname, 'src/assets/translations.ts'),\n      globalSFCScope: true,\n      compositionOnly: false,\n    }),\n  ],\n  server: {\n    port: 8080\n  },\n  resolve: {\n    dedupe: ['vue'],\n    alias: {\n      \"~\": path.resolve(__dirname, \"./src\"),\n      \"@\": path.resolve(__dirname, \"./src\"),\n    },\n  },\n})\n```\n\n```text\n{\n  \"name\": \"vcp\",\n  \"version\": \"0.9.11\",\n  \"private\": false,\n  \"author\": \"Alireza Safari <alireza.safaree@gmail.com> (http://alireza-safari.ir)\",\n  \"license\": \"MIT\",\n  \"main\": \"./dist/vcp.umd.ts\",\n  \"description\": \"Vue Client Print with Template Builder\",\n  \"exports\": {\n    \".\": {\n      \"require\": \"./dist/vcp.umd.ts\"\n    },\n    \"./dist/style.css\": \"./dist/style.css\"\n  },\n  \"keywords\": [\n    \"vcp\",\n    \"vue print\",\n    \"vue client print\",\n    \"template builder\",\n    \"vue report\",\n    \"vue report generator\"\n  ],\n  \"files\": [\n    \"dist/*\"\n  ],\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/alireza0sfr/vue-client-print\"\n  },\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"serve\": \"vite preview\",\n    \"test\": \"vitest run --environment jsdom\",\n    \"test:ui:\": \"vitest --environment jsdom --ui\",\n    \"test:coverage\": \"vitest run --coverage --environment jsdom\",\n    \"test:watch\": \"vitest --environment jsdom\"\n  },\n  \"dependencies\": {\n    \"dom-to-image\": \"^2.6.0\",\n    \"file-saver\": \"^2.0.5\",\n    \"jsdom\": \"^19.0.0\",\n    \"print-js\": \"^1.6.0\",\n    \"register-service-worker\": \"^1.7.2\",\n    \"typescript\": \"^4.7.2\",\n    \"vitest\": \"^0.12.9\",\n    \"vue\": \"^3.2.36\",\n    \"vue-i18n\": \"^9.1.10\"\n  },\n  \"devDependencies\": {\n    \"@intlify/vite-plugin-vue-i18n\": \"^3.4.0\",\n    \"@vitejs/plugin-vue\": \"^2.3.3\",\n    \"@vitest/ui\": \"^0.12.9\",\n    \"@vue/compiler-sfc\": \"^3.2.36\",\n    \"@vue/test-utils\": \"^2.0.0-rc.18\",\n    \"c8\": \"^7.11.3\",\n    \"cz-conventional-changelog\": \"^3.0.1\",\n    \"vite\": \"^2.9.9\"\n  }\n}\n```\n\n```text\nbuild.cssCodeSplit\n```\n\n```text\ntrue\n```\n\n========================================\n\nComments:\n- For es.js, a better solution to this is using vite-plugin-css-injected-by-js","metadata":{"transformedAt":"2026-08-18T18:33:46.420Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":310,"estimatedTokens":1574}}349{"id":"stack-76185469","source":"stackoverflow","questionId":76185469,"title":"Load onnx model in browser, can't find wasm file","tags":["javascript","vite","webassembly","onnx","onnxruntime"],"text":"Title: Load onnx model in browser, can't find wasm file\nTags: javascript, vite, webassembly, onnx, onnxruntime\nSource: Stack Overflow\n\nQuestion:\nI'm trying to load an `.onnx` model that I have into browser using `onnxruntime-web`.\n\nThe code is run in a React app using a Vite server:\n\n```\nimport * as ort from 'onnxruntime-web';\n\nconst App = () => {\n\n const create = async () => {\n const session = await ort.InferenceSession.create('./src/assets/silero_vad.onnx');\n }\n create();\n\n return <>Hello world\n}\n\nexport default App\n```\n\n`.wasm` module fails to load and gives error\n\n```\nGET http://localhost:5173/ort-wasm-simd.wasm net::ERR_ABORTED 404 (Not Found)\n```\n\nUsing Google Chrome version `Google Chrome 112.0.5615.165` on Ubuntu 22.04. No idea how to fix this?\n\n========================================\n\nTop Answer:\n```\nexport default defineConfig({\n ...,\n\n assetsInclude: [\"**/*.onnx\"],\n optimizeDeps: {\n exclude: [\"onnxruntime-web\"],\n },\n\n ...\n});\n```\n\nTry using this. It fixed it for me.\n\n========================================\n\nCode:\n```jsx\nimport * as ort from 'onnxruntime-web';\n\nconst App = () => {\n\n    const create = async () => {\n        const session = await ort.InferenceSession.create('./src/assets/silero_vad.onnx');\n    }\n    create();\n\n    return <>Hello world</>\n}\n\nexport default App\n```\n\n```text\nGET http://localhost:5173/ort-wasm-simd.wasm net::ERR_ABORTED 404 (Not Found)\n```\n\n```text\n.onnx\n```\n\n```text\nonnxruntime-web\n```\n\n```text\n.wasm\n```\n\n```text\nGoogle Chrome 112.0.5615.165\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport { viteStaticCopy } from 'vite-plugin-static-copy';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    react(),\n    viteStaticCopy({\n      targets: [\n        {\n          src: 'node_modules/onnxruntime-web/dist/*.wasm',\n          dest: '.'\n        }\n      ]\n    }),\n  ],\n})\n```\n\n```text\nvite\n```\n\n```text\nvite\n```\n\n```text\nvite-plugin-static-copy\n```\n\n```text\nviteStaticCopy\n```\n\n```text\nvite.config.js\n```\n\n```text\n.wasm\n```\n\n```text\ndist\n```\n\n```text\nfetch(local_server_uri/file_to_grab.wasm, ...)\n```\n\n```none\nexport default defineConfig({\n  ...,\n\n  assetsInclude: [\"**/*.onnx\"],\n  optimizeDeps: {\n    exclude: [\"onnxruntime-web\"],\n  },\n\n  ...\n});\n```\n\n========================================\n\nComments:\n- You can just put them in the public folder\n- Hi, I have a similar problem. Could you elaborate by what you mean by 'just put them in the public folder' ? I am making a react app which will be served statically, without a server.\n- @Frotaur At the top level directory of your project you can create a folder named 'public' and then fetch will automatically look for files there. So another solution to my problem could have been to put all the .wasm/.onnx files I needed and put them in the public folder. Then for example if I have a file `model.onnx` in the `public` directory I can fetch it with `fetch('.&#47;model.onnx')`\n- @Frotaur I prefer the solution above because its cleaner and all the files I need from onnxruntime are automatically copied over from node package folder\n- @Frotaur also all react apps have to be served from somewhere? do you mean you're using static hosting?\n- I probably expressed myself poorly, since I'm new to webdev. I just mean that I webpack the app and in the end I am left with an .HTML file with a bunch of javascript, that does not need a 'backend' to run. Of course, the HTML file will be served by a webserver such as nginx an so on. At least that's my understanding. In any case, the .wasm copying trick worked for me, thanks !\n- here is a webpack example with its copy configuration github.com/microsoft/onnxruntime-inference-examples/tree/mai&zwnj;&#8203;n/&hellip;\n- How to solve this for Next.js?\n- what about iff it is in react .ts project.","metadata":{"transformedAt":"2026-08-18T18:33:46.420Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":168,"estimatedTokens":957}}350{"id":"stack-77839240","source":"stackoverflow","questionId":77839240,"title":"Can Vitest UI display coverage report directory?","tags":["vite","vitest"],"text":"Title: Can Vitest UI display coverage report directory?\nTags: vite, vitest\nSource: Stack Overflow\n\nQuestion:\nI have a Vite project, and I would like to include Vitest UI. I have added the configuration, plus the coverage report configuration.\n\nHere is the `vite.config`:\n\n```\ntest: {\n globals: true,\n environment: \"jsdom\",\n include: [\"**/*.test.{ts,tsx}\"],\n setupFiles: [\"./src/test/setup.ts\"],\n css: true,\n reporters: ['default', 'html'],\n coverage: {\n reportsDirectory: \"html/ui\",\n include: [\"**/*.{ts,tsx}\"],\n exclude: [\"src/test/**/*.{ts,tsx}\"],\n reporter: ['text', ['html', { subdir: 'coverage'}]],\n provider: \"v8\",\n }\n },\n```\n\nWhen I run\n\n```\nvitest --ui --coverage.enabled=true\n```\n\nthe UI appears (`http://localhost:51204/__vitest__/#/?file=`) however I don't see the coverage report button:\n\nhttps://i.sstatic.net/8SAYs.png\n\nExpected:\n\nhttps://i.sstatic.net/OrIdl.png\n\nHowever, when I run the following command:\n\n```\nnpx vite preview --outDir ./html\n```\n\nI do see the coverage report button on the browser, `http://localhost:4173/`\n\nhttps://i.sstatic.net/HD2wZ.png\n\nIs there a way to add the coverage button when running `vitest --ui` or this is not possible? Is it only available on `vite preview`? I've read the docs, and it seems to imply you can have the reports button when running `vitest --ui`. Perhaps I'm missing a configuration somewhere or misunderstanding the docs.\n\nUPDATE:\nThis command seems to be working now `\"test:ui\": \"vitest --ui --coverage\"`. There was a patch somewhere that got this fixed.\n\n========================================\n\nTop Answer:\nI added below line in my package.json and its working.\n\n```\n\"test\": \"vitest --ui --coverage.enabled --coverage.all --coverage.src='./src --coverage.reporter='html'\"\n```\n\nWith above command ui will open at http://localhost:51204/**vitest**/#/ and will have a coverage button\n\n========================================\n\nCode:\n```javascript\ntest: {\n        globals: true,\n        environment: \"jsdom\",\n        include: [\"**/*.test.{ts,tsx}\"],\n        setupFiles: [\"./src/test/setup.ts\"],\n        css: true,\n        reporters: ['default', 'html'],\n        coverage: {\n            reportsDirectory: \"html/ui\",\n            include: [\"**/*.{ts,tsx}\"],\n            exclude: [\"src/test/**/*.{ts,tsx}\"],\n            reporter: ['text', ['html', { subdir: 'coverage'}]],\n            provider: \"v8\",\n        }\n    },\n```\n\n```bash\nvitest --ui --coverage.enabled=true\n```\n\n```bash\nnpx vite preview --outDir ./html\n```\n\n```text\nvite.config\n```\n\n```text\nhttp://localhost:51204/__vitest__/#/?file=\n```\n\n```text\nhttp://localhost:4173/\n```\n\n```text\nvitest --ui\n```\n\n```text\nvite preview\n```\n\n```text\nvitest --ui\n```\n\n```text\n\"test:ui\": \"vitest --ui --coverage\"\n```\n\n```text\n\"test:ui\": \"vitest --ui --coverage\",\n```\n\n```text\n\"test\": \"vitest --ui --coverage.enabled --coverage.all --coverage.src='./src --coverage.reporter='html'\"\n```\n\n```js\ntest: {\n      globals: true,\n      environment: 'jsdom',\n      setupFiles: './tests/setup.ts',\n      css: true,\n      coverage: {\n        enabled: true,\n        reporter: ['html'],\n      },\n    },\n```\n\n========================================\n\nComments:\n- Did you have any luck with this? I have this exact same question\n- Unfortunately, this is still a mystery; I have moved on from this issue. I hope the community can answer this.\n- This is not working, this command is equivalent to what I stated at the top of question - `vitest --ui --coverage.enabled=true`\n- ok, it seems to be a version issue. Three months ago this was known issue, but now it seems to be resolving correctly. I'm assuming there was a patch somewhere.\n- What vitest version do you have?\n- @medev21 I am using 1.3.1 version\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:46.420Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":155,"estimatedTokens":993}}351{"id":"stack-75268328","source":"stackoverflow","questionId":75268328,"title":"Vite doesn't resolve extension for build","tags":["webpack","vite","laravel-mix"],"text":"Title: Vite doesn't resolve extension for build\nTags: webpack, vite, laravel-mix\nSource: Stack Overflow\n\nQuestion:\nI tre to migrate from laravel-mix to vite by this guide\n\nWhen i run `npm run dev` (`vite`), everything is great.\n\nBut when i run `npm run build`, i get the error:\n\nError: Could not load resources/js/hooks/useRoute (imported by resources/js/app.tsx): ENOENT: no such file or directory, open 'C:\\OpenServer\\domains\\colorbit.local\\reso\nurces\\js\\hooks\\useRoute'\n\nIt's because i import all files without extensions. PhpStorm said that this is how it should be, if you add an extension, then it gave an error that it’s better not to do this. So I used imports without file extension everywhere in the project.\n\nHow to ignore extensions when importing files? How should i change my vite.config.js?\nExample: `import {Button} from '@componenst/ui/Button` - not `.ts` extension.\n\nHere's the code\n\n```\n// vite.config.js\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\nimport react from '@vitejs/plugin-react';\n\nexport default defineConfig({\n plugins: [\n laravel({\n input: [\n 'resources/js/app.tsx',\n ],\n refresh: true,\n }),\n react({\n fastRefresh: false\n }),\n\n ],\n resolve: {\n alias : {\n '@' : 'resources/js',\n '@assets' : 'resources/js/assets',\n '@hooks' : 'resources/js/hooks',\n '@components': 'resources/js/components'\n },\n extensions: ['.js', '.ts', '.tsx', '.jsx'],\n },\n});\n\n// package.json\n{\n \"private\": true,\n \"scripts\": {\n \"ssr\": \"mix --mix-config=webpack.ssr.mix.js\",\n \"routes\": \"php artisan ziggy:generate\",\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"serve\": \"vite preview\"\n },\n \"devDependencies\": {\n \"@babel/preset-react\": \"^7.17.12\",\n \"@headlessui/react\": \"^1.6.3\",\n \"@inertiajs/server\": \"^0.1.0\",\n \"@pmmmwh/react-refresh-webpack-plugin\": \"^0.5.0-rc.0\",\n \"@prettier/plugin-php\": \"^0.18.5\",\n \"@tailwindcss/forms\": \"^0.5.2\",\n \"@tailwindcss/typography\": \"^0.5.2\",\n \"@types/react\": \"^18.0.9\",\n \"@types/react-dom\": \"^18.0.5\",\n \"@types/ziggy-js\": \"^1.3.2\",\n \"@vitejs/plugin-react\": \"^3.0.1\",\n \"@vitejs/plugin-react-refresh\": \"^1.3.6\",\n \"autoprefixer\": \"10.4.5\",\n \"laravel-vite-plugin\": \"^0.7.3\",\n \"postcss\": \"^8.4.14\",\n \"postcss-import\": \"^14.1.0\",\n \"react-refresh\": \"^0.14.0\",\n \"resolve-url-loader\": \"^5.0.0\",\n \"sass\": \"^1.52.1\",\n \"sass-loader\": \"^12.1.0\",\n \"tailwindcss\": \"^3.0.24\",\n \"ts-loader\": \"^9.3.0\",\n \"typescript\": \"^4.7.2\",\n \"webpack-node-externals\": \"^3.0.0\"\n },\n \"dependencies\": {\n \"@inertiajs/inertia\": \"^0.11.0\",\n \"@inertiajs/inertia-react\": \"^0.8.0\",\n \"@inertiajs/progress\": \"^0.2.7\",\n \"laravel-vite\": \"^0.0.24\",\n \"react\": \"^18.1.0\",\n \"react-dom\": \"^18.1.0\",\n \"react-joyride\": \"^2.5.3\",\n \"use-sound\": \"^4.0.1\",\n \"vite\": \"^4.0.4\",\n \"ziggy-js\": \"^1.4.6\"\n }\n}\n\n// Index.blade.php\n\ngetLocale()) }}\">\n\n \n \n\n {{-- MANIFEST --}}\n \n\n {{-- ICONS --}}\n \n\n \n {{ config('app.name', 'Colorbit') }}\n\n \n \n\n \n @routes\n @vite\n @inertiaHead\n\n @inertia\n\n// resources/js/app.tsx\nimport React from \"react\";\nimport Layout from \"./Layouts/Layout\";\nimport {createRoot} from 'react-dom/client';\nimport {createInertiaApp} from '@inertiajs/inertia-react';\nimport {InertiaProgress} from '@inertiajs/progress';\nimport axios from 'axios';\nimport {RouteContext} from '@hooks/useRoute';\nimport {initPush} from \"./enable-push\";\n\nimport '../css/app.scss';\nimport {resolvePageComponent} from \"laravel-vite-plugin/inertia-helpers\";\n\nwindow.axios = axios;\nwindow.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';\n\nconst appName =\n window.document.getElementsByTagName('title')[0]?.innerText || 'ColorBit';\n\ncreateInertiaApp({\n title: (title: string) => `${title} - ${appName}`,\n resolve: async (name: string) => {\n const page = (await resolvePageComponent(\n `./Pages/${name}.tsx`,\n import.meta.glob('./Pages/**/*.tsx'\n ))).default;\n\n page.layout = page.layout || ((page: React.ReactElement) => );\n\n return page;\n },\n setup({el, App, props}) {\n const root = createRoot(el);\n return root.render(\n \n \n \n \n \n );\n },\n});\n\nInertiaProgress.init({color: '#CC3824'});\n```\n\n========================================\n\nTop Answer:\nI also got the error `Cannot find module '/.../myapp/node_modules/mylib/bar/Foo'` and thought that the extension is the problem (given that it's Foo.js, of course), but it was the path, like in your case.\n\nI had the problem with a library that belongs to my project and is in a sibling directory. So, I was able to fix it similar to you:\n\n```\nimport { defineConfig } from 'vite';\nimport path from 'path';\n\nexport default defineConfig({\n resolve: {\n alias: {\n \"mylib\": path.resolve(\"../mylib/\")\n },\n },\n});\n```\n\ngiven that `mylib/` is in a sibling directory to `myapp/`.\n\nThank you for posting your problem and your solution.\n\n========================================\n\nCode:\n```text\n// vite.config.js\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\nimport react from '@vitejs/plugin-react';\n\nexport default defineConfig({\n    plugins: [\n        laravel({\n            input: [\n                'resources/js/app.tsx',\n            ],\n            refresh: true,\n        }),\n        react({\n            fastRefresh: false\n        }),\n\n    ],\n    resolve: {\n        alias     : {\n            '@'          : 'resources/js',\n            '@assets'    : 'resources/js/assets',\n            '@hooks'     : 'resources/js/hooks',\n            '@components': 'resources/js/components'\n        },\n        extensions: ['.js', '.ts', '.tsx', '.jsx'],\n    },\n});\n\n// package.json\n{\n    \"private\": true,\n    \"scripts\": {\n        \"ssr\": \"mix --mix-config=webpack.ssr.mix.js\",\n        \"routes\": \"php artisan ziggy:generate\",\n        \"dev\": \"vite\",\n        \"build\": \"vite build\",\n        \"serve\": \"vite preview\"\n    },\n    \"devDependencies\": {\n        \"@babel/preset-react\": \"^7.17.12\",\n        \"@headlessui/react\": \"^1.6.3\",\n        \"@inertiajs/server\": \"^0.1.0\",\n        \"@pmmmwh/react-refresh-webpack-plugin\": \"^0.5.0-rc.0\",\n        \"@prettier/plugin-php\": \"^0.18.5\",\n        \"@tailwindcss/forms\": \"^0.5.2\",\n        \"@tailwindcss/typography\": \"^0.5.2\",\n        \"@types/react\": \"^18.0.9\",\n        \"@types/react-dom\": \"^18.0.5\",\n        \"@types/ziggy-js\": \"^1.3.2\",\n        \"@vitejs/plugin-react\": \"^3.0.1\",\n        \"@vitejs/plugin-react-refresh\": \"^1.3.6\",\n        \"autoprefixer\": \"10.4.5\",\n        \"laravel-vite-plugin\": \"^0.7.3\",\n        \"postcss\": \"^8.4.14\",\n        \"postcss-import\": \"^14.1.0\",\n        \"react-refresh\": \"^0.14.0\",\n        \"resolve-url-loader\": \"^5.0.0\",\n        \"sass\": \"^1.52.1\",\n        \"sass-loader\": \"^12.1.0\",\n        \"tailwindcss\": \"^3.0.24\",\n        \"ts-loader\": \"^9.3.0\",\n        \"typescript\": \"^4.7.2\",\n        \"webpack-node-externals\": \"^3.0.0\"\n    },\n    \"dependencies\": {\n        \"@inertiajs/inertia\": \"^0.11.0\",\n        \"@inertiajs/inertia-react\": \"^0.8.0\",\n        \"@inertiajs/progress\": \"^0.2.7\",\n        \"laravel-vite\": \"^0.0.24\",\n        \"react\": \"^18.1.0\",\n        \"react-dom\": \"^18.1.0\",\n        \"react-joyride\": \"^2.5.3\",\n        \"use-sound\": \"^4.0.1\",\n        \"vite\": \"^4.0.4\",\n        \"ziggy-js\": \"^1.4.6\"\n    }\n}\n\n\n// Index.blade.php\n<!DOCTYPE html>\n<html lang=\"{{ str_replace('_', '-', app()->getLocale()) }}\">\n\n<head>\n    <meta charset=\"utf-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\n    {{--  MANIFEST  --}}\n    <link rel=\"manifest\" href=\"/manifest.json\">\n\n    {{--  ICONS  --}}\n    <link rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"/icons/favicon-16x16.png\">\n\n    <!-- Title -->\n    <title inertia>{{ config('app.name', 'Colorbit') }}</title>\n\n    <!-- CSRF -->\n    <meta name=\"csrf-token\" content=\"{{ csrf_token() }}\" />\n\n    <!-- Scripts -->\n    @routes\n    @vite\n    @inertiaHead\n</head>\n\n<body class=\"font-sans antialiased\">\n    @inertia\n</body>\n</html>\n\n// resources/js/app.tsx\nimport React from \"react\";\nimport Layout from \"./Layouts/Layout\";\nimport {createRoot} from 'react-dom/client';\nimport {createInertiaApp} from '@inertiajs/inertia-react';\nimport {InertiaProgress} from '@inertiajs/progress';\nimport axios from 'axios';\nimport {RouteContext} from '@hooks/useRoute';\nimport {initPush} from \"./enable-push\";\n\nimport '../css/app.scss';\nimport {resolvePageComponent} from \"laravel-vite-plugin/inertia-helpers\";\n\nwindow.axios = axios;\nwindow.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';\n\nconst appName =\n    window.document.getElementsByTagName('title')[0]?.innerText || 'ColorBit';\n\ncreateInertiaApp({\n    title: (title: string) => `${title} - ${appName}`,\n    resolve: async (name: string) => {\n        const page = (await resolvePageComponent<any>(\n            `./Pages/${name}.tsx`,\n            import.meta.glob('./Pages/**/*.tsx'\n        ))).default;\n\n        page.layout = page.layout || ((page: React.ReactElement) => <Layout children={page}/>);\n\n        return page;\n    },\n    setup({el, App, props}) {\n        const root = createRoot(el);\n        return root.render(\n            <React.StrictMode>\n                <RouteContext.Provider value={(window as any).route || 123}>\n                    <App {...props} />\n                </RouteContext.Provider>\n            </React.StrictMode>\n        );\n    },\n});\n\nInertiaProgress.init({color: '#CC3824'});\n```\n\n```text\nnpm run dev\n```\n\n```text\nvite\n```\n\n```text\nnpm run build\n```\n\n```text\nimport {Button} from '@componenst/ui/Button\n```\n\n```text\n.ts\n```\n\n```js\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\nimport react from '@vitejs/plugin-react';\n\nimport path from 'path'\n\nexport default defineConfig({\n    plugins: [\n        laravel({\n            input: [\n                'resources/js/app.tsx',\n            ],\n            refresh: true,\n        }),\n        react({\n            fastRefresh: false\n        }),\n\n    ],\n    resolve: {\n        alias     : {\n            '@'          : path.resolve(__dirname, 'resources/js'),\n            '@hooks'     : path.resolve(__dirname, 'resources/js/hooks'),\n            '@assets'    : path.resolve(__dirname, 'resources/js/assets/'),\n            '@components': path.resolve(__dirname, 'resources/js/components')\n        },\n        extensions: ['.js', '.ts', '.tsx', '.jsx'],\n    },\n});\n```\n\n```text\nnpm run build\n```\n\n```text\npath.resolve\n```\n\n```text\npath.resolve\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport path from 'path';\n\nexport default defineConfig({\n  resolve: {\n    alias: {\n      \"mylib\": path.resolve(\"../mylib/\")\n    },\n  },\n});\n```\n\n```text\nCannot find module '/.../myapp/node_modules/mylib/bar/Foo'\n```\n\n```text\nmylib/\n```\n\n```text\nmyapp/\n```\n\n```text\nresolve: {\n  alias     : {\n    '@'          : path.resolve(new URL(import.meta.url).pathname, './src'),\n    '@routes'    : path.resolve(new URL(import.meta.url).pathname, '../src/routes'),\n    '@assets'    : path.resolve(new URL(import.meta.url).pathname, '../src/assets'),\n    '@components': path.resolve(new URL(import.meta.url).pathname, '../src/components')\n  },\n  extensions: ['.js', '.jsx'],\n},\n```\n\n```text\n__dirname\n```\n\n```text\nnew URL(import.meta.url).pathname\n```\n\n```text\n# .env\nVITE_APP_SITE=https://multiwhats.app\n```\n\n```html\n<!-- Wrong: -->\n<link rel=\"stylesheet\" href=\"assets/css/custom.css\" />\n\n<!-- Correct: -->\n<link rel=\"stylesheet\" href=\"%VITE_APP_SITE%/assets/css/custom.css\" />\n```\n\n```text\n.env\n```\n\n```text\nVITE_APP_SITE\n```\n\n```text\nindex.html\n```\n\n```text\nindex.html\n```\n\n========================================\n\nComments:\n- @AhmedSbai idk, that's a base config for vue, i have tried alomist idetical config but without vue","metadata":{"transformedAt":"2026-08-18T18:33:46.420Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":500,"estimatedTokens":2862}}352{"id":"stack-72077976","source":"stackoverflow","questionId":72077976,"title":"How to build vue component library with vite and tailwind? (tailwind classes not working when importing to other project)","tags":["vue.js","nuxt.js","tailwind-css","vite"],"text":"Title: How to build vue component library with vite and tailwind? (tailwind classes not working when importing to other project)\nTags: vue.js, nuxt.js, tailwind-css, vite\nSource: Stack Overflow\n\nQuestion:\n### Current\n\nI have two repositories:\n\n- Main Web App - simple nuxt3 web app\n\n- Component Library - simple vite/vue app\n\n### Goal\n\nBuild my own component library using vite, vue3 and tailwindcss\n\n### Problem\n\nWhen I use `npm run dev` I can se my components working fine (from the vite app) but when I build my library `npm run build:watch` and import them in another project (nuxt app) tailwind classes/styles are not working\n\nThis is mi vite app (all good)\n\nThis is the nuxt app where I imported the component (no style)\n\nRepositories:\n\n- Main Web App: https://github.com/fro-systems/clau-web\n\n- Component Library: https://github.com/fro-systems/clau-components\n\n========================================\n\nCode:\n```text\nnpm run dev\n```\n\n```text\nnpm run build:watch\n```\n\n```text\n\"exports\": {\n    \"./dist/style.css\": \"./dist/style.css\"\n  },\n```\n\n```text\ncss: [\n  \"clau-components/dist/style.css\"\n],\n```\n\n```text\npackage.json\n```\n\n```text\nnuxt.config.ts\n```\n\n========================================\n\nComments:\n- Can I ask if there is a way to fix this **without explicitly importing css in the host project** (in this case, `nuxt.config.ts`)? Cos if we have a lot of custom libraries then importing the bundled css is going to need a lot of manual work. Pls advice if I should post a separate qn\n- Were you are to resolve this without an explicit import to the host project?","metadata":{"transformedAt":"2026-08-18T18:33:46.420Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":67,"estimatedTokens":395}}353{"id":"stack-78406077","source":"stackoverflow","questionId":78406077,"title":"React/Vite using createBrowserRouter hosted in a subdirectory does not work without a trailing slash","tags":["javascript","reactjs","express","react-router-dom","vite"],"text":"Title: React/Vite using createBrowserRouter hosted in a subdirectory does not work without a trailing slash\nTags: javascript, reactjs, express, react-router-dom, vite\nSource: Stack Overflow\n\nQuestion:\nI'm using React/Vite/Express to build an app that is hosted in a subdirectory. As an example, let's say it's hosted at: https://example.com/my/app/\n\nIn my Vite config, I've set `base` to `./`\n\n```\nexport default defineConfig({\n base: './',\n build: {\n outDir: './public/build',\n },\n plugins: [react()],\n css: {\n preprocessorOptions: {\n scss: {\n implementation: sass,\n },\n },\n }\n});\n```\n\nI am also using react-router-dom. Here is my config for `createBrowserRouter`:\n\n```\nexport const router = createBrowserRouter(\n [\n {\n path: '/',\n element: ,\n errorElement: ,\n children: [\n {\n path: '/',\n element: ,\n },\n {\n path: '/test1',\n element: ,\n },\n {\n path: '/test2',\n element: ,\n },\n ],\n },\n ],\n {\n basename: '/my/app',\n },\n);\n```\n\nWhen I visit the page with the `/`, it works just fine, e.g. `https://example.com/my/app/`\n\nHowever, if I remove the trailing app using `https://example.com/my/app`, Vite thinks that the base is the parent directory `/my/` and uses that as the root. The React JS and CSS then throw 404s.\n\nIs there a way in Vite to fix this without hard-coding the full path as `base`, or is this something I need to fix on the server to redirect to the URL with the trailing slash?\n\nI'd rather not hard code the base because it will change depending on environments. If that's the best-practice approach, though, I'll go with that solution.\n\nI expected that the application would assume that `my/app` was a directory. Instead, it seem to be using `my/` as the directory. I've tried changing `base` to `.` and to an empty string, with no luck.\n\n========================================\n\nCode:\n```text\nexport default defineConfig({\n    base: './',\n    build: {\n        outDir: './public/build',\n    },\n    plugins: [react()],\n    css: {\n        preprocessorOptions: {\n            scss: {\n                implementation: sass,\n            },\n        },\n    }\n});\n```\n\n```text\nexport const router = createBrowserRouter(\n    [\n        {\n            path: '/',\n            element: <App />,\n            errorElement: <Error />,\n            children: [\n                {\n                    path: '/',\n                    element: <Home />,\n                },\n                {\n                    path: '/test1',\n                    element: <Test1 />,\n                },\n                {\n                    path: '/test2',\n                    element: <Test2 />,\n                },\n            ],\n        },\n    ],\n    {\n        basename: '/my/app',\n    },\n);\n```\n\n```text\nbase\n```\n\n```text\n./\n```\n\n```text\ncreateBrowserRouter\n```\n\n```text\n/\n```\n\n```text\nhttps://example.com/my/app/\n```\n\n```text\nhttps://example.com/my/app\n```\n\n```text\n/my/\n```\n\n```text\nbase\n```\n\n```text\nmy/app\n```\n\n```text\nmy/\n```\n\n```text\nbase\n```\n\n```text\n.\n```\n\n```js\nexport const router = createBrowserRouter(\n    [\n        {\n            element: <App />,\n            errorElement: <Error />,\n            children: [\n                {\n                    index: true,\n                    element: <Home />,\n                },\n                {\n                    path: '/test1',\n                    element: <Test1 />,\n                },\n                {\n                    path: '/test2',\n                    element: <Test2 />,\n                },\n            ],\n        },\n    ],\n    {\n        basename: '/my/app',\n    },\n);\n```\n\n```js\nexport default defineConfig({\n    base: '/my/app/',\n    ...\n});\n```\n\n```text\nvite\n```\n\n```text\nbasename\n```\n\n```text\n'/my/app'\n```\n\n```text\n<Home />\n```\n\n```text\nindex: true\n```\n\n```text\npath: '/'\n```\n\n```text\npath\n```\n\n```text\n<App>\n```\n\n```text\nvite\n```\n\n========================================\n\nComments:\n- I think the problem is unrelated to vite configuration. let me guess: you're using react-router-dom with your app? how do you configure it? have you setup `basename` for the router? related doc\n- Thanks, Slava. Yes, I'm using `createBrowserRouter` in react-router-dom. The `basename` I've set is `my&#47;app&#47;`. I have also tried `my&#47;app` but have the exact same issue.\n- Correct value of `basename` should be with leading slash, not trailing: `\"&#47;my&#47;app\"`. Can you see the same error locally, or only on prod/staging after deployment? If locally too, could you please add your routes configuration to the question? I suspect you just miscofngured index route.\n- Thanks, just updated with my router configuration. I will test locally tomorrow and report back here.\n- Thanks Slava - unfortunately, still no luck. I am still seeing in the Network tab that the application is looking for the js/css under the `my&#47;` directory and not `my&#47;app&#47;` when I leave off the trailing slash from the URL. With the trailing slash, it works fine.\n- you know, you might be right, `base` of vite confiuration could actually be the part of the solution: try to set it to `&#47;my&#47;app` or even `&#47;my&#47;app&#47;` and see if it make any difference with the changes i proposed earlier\n- Thanks! That did it! For what it's worth the path/index changes in the react router didn't seem to affect anything. It works with your config and my original. The fix was to add `base` with the full path to Vite config and add `basename` with the full path to react router dom. Thanks for all your help!","metadata":{"transformedAt":"2026-08-18T18:33:46.421Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":25,"totalLines":245,"estimatedTokens":1359}}354{"id":"stack-68794861","source":"stackoverflow","questionId":68794861,"title":"Vite.js not emitting HTML files in multi page app","tags":["javascript","reactjs","vite"],"text":"Title: Vite.js not emitting HTML files in multi page app\nTags: javascript, reactjs, vite\nSource: Stack Overflow\n\nQuestion:\nI have a multi page app that I'm trying to build with `Vite.js` (migrating from `Webpack`). When building the Vite + React example code I see that it emits:\n\n- `dist/index.html`\n\n- `dist/assets/`\n\nHowever, when I try to make a multi page app as shown in the docs none of the HTMLs are emitted (but the rest of the content of `/assets/` is there). Why is this?\n\n```\n// vite.config.js excerpt:\nimport { defineConfig } from 'vite'\nimport { dirname } from 'path';\nimport { fileURLToPath } from 'url';\n\nexport default defineConfig({\n root: 'client',\n build: {\n outDir: 'dist',\n rollupOptions: {\n input: {\n main: dirname(fileURLToPath(import.meta.url + 'index.html')),\n login: dirname(fileURLToPath(import.meta.url + 'login.html')),\n }\n }\n },\n});\n```\n\n========================================\n\nCode:\n```js\n// vite.config.js excerpt:\nimport { defineConfig } from 'vite'\nimport { dirname } from 'path';\nimport { fileURLToPath } from 'url';\n\nexport default defineConfig({\n  root: 'client',\n  build: {\n    outDir: 'dist',\n    rollupOptions: {\n      input: {\n        main: dirname(fileURLToPath(import.meta.url + 'index.html')),\n        login: dirname(fileURLToPath(import.meta.url + 'login.html')),\n      }\n    }\n  },\n});\n```\n\n```text\nVite.js\n```\n\n```text\nWebpack\n```\n\n```text\ndist/index.html\n```\n\n```text\ndist/assets/<various assets>\n```\n\n```text\n/assets/\n```\n\n```text\nmain: new URL('./client/index.html', import.meta.url).pathname\n```\n\n```text\nURL\n```\n\n========================================\n\nComments:\n- remove `dirname` which is removing the filename only directory names will be left out.\n- @Chandan If I remove dirname I get an error during `vite build` that says `SyntaxError: Assigning to rvalue`.\n- try `new URL(`./index.html`, import.meta.url)` as specified in the vite doc.\n- Your suggestion worked @Chandan ! Put it in an answer and I'll accept it. `main: new URL('.&#47;client&#47;index.html', import.meta.url).pathname,`","metadata":{"transformedAt":"2026-08-18T18:33:46.421Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":91,"estimatedTokens":513}}355{"id":"stack-71038134","source":"stackoverflow","questionId":71038134,"title":"VSCode - Setup a monorepo with a Deno (backend) folder and a Vite (frontend) folder","tags":["typescript","visual-studio-code","vite","deno"],"text":"Title: VSCode - Setup a monorepo with a Deno (backend) folder and a Vite (frontend) folder\nTags: typescript, visual-studio-code, vite, deno\nSource: Stack Overflow\n\nQuestion:\nI'm trying to configure a monorepo with a **back (or \"api\") folder** that uses Deno and a **front (or \"webapp\") folder** that is a react app (or actually, any framework, configured with Vite).\n\nSo the project actually mixes Deno and Node (if it's a bad idea, you can stop me right now).\nI'm might also consider using the Deno Linter and Formatter for the whole project.\n\nThe file structure would look something like that:\n\n```\nmy-monorepo/\n├── .vscode/\n│ └── settings.json\n├── back/\n│ └── index.ts\n├── front/\n│ ├── src/\n│ │ └── index.tsx\n│ ├── index.html\n│ └── vite.config.ts\n├── .gitignore\n├── deno.jsonc\n└── package.json\n```\n\nIt pretty much works but the main issue I encounters right now is with the VSCode Deno Extension.\n\n**Would it be possible to use the built-in VSCode JS and TS language services for the `front/` folder and the Deno Language Server (deno lsp) for the `back/` folder?**\nOtherwise TS gets mad (for instance the imports in `back/` must include `.ts` but in font they most no include `.ts`).\n\nFinally, if I can make it work, I would like it to be easy for anyone who clones the repo to work with it.\n\nAlo, here is the .vscode/settings.json file for the reference:\n\n```\n{\n \"deno.enable\": true,\n \"deno.config\": \"./deno.jsonc\",\n\n \"[typescript]\": {\n \"editor.defaultFormatter\": \"denoland.vscode-deno\",\n }\n}\n```\n\n========================================\n\nTop Answer:\nYou can actually tell VSCode that you are **only** going to use Deno in some specific folders, by adding this to `.vscode/settings.json`:\n\n```\n{\n // other configs...\n\n \"deno.enablePaths\": [\n \"back\" // <-- Deno will be used in \"back\", but not in \"front\"\n // additional paths can be added as well\n ]\n}\n```\n\n========================================\n\nCode:\n```text\nmy-monorepo/\n├── .vscode/\n│   └── settings.json\n├── back/\n│   └── index.ts\n├── front/\n│   ├── src/\n│   │   └── index.tsx\n│   ├── index.html\n│   └── vite.config.ts\n├── .gitignore\n├── deno.jsonc\n└── package.json\n```\n\n```json\n{\n  \"deno.enable\": true,\n  \"deno.config\": \"./deno.jsonc\",\n\n  \"[typescript]\": {\n    \"editor.defaultFormatter\": \"denoland.vscode-deno\",\n  }\n}\n```\n\n```text\nfront/\n```\n\n```text\nback/\n```\n\n```text\nback/\n```\n\n```text\n.ts\n```\n\n```text\n.ts\n```\n\n```json\n{\n  // other configs...\n\n  \"deno.enablePaths\": [\n    \"back\" // <-- Deno will be used in \"back\", but not in \"front\"\n    // additional paths can be added as well\n  ]\n}\n```\n\n```text\n.vscode/settings.json\n```\n\n========================================\n\nComments:\n- What do you mean by \"top-level scrippting with deno\"?\n- @Cohars Anything meta (related to the monorepo project itself)\n- Ok got it. I was wondering if there was something like npm scripts for deno. Turns out there is github.com/jurassiscripts/velociraptor, I'll give it a try","metadata":{"transformedAt":"2026-08-18T18:33:46.421Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":135,"estimatedTokens":731}}356{"id":"stack-77199600","source":"stackoverflow","questionId":77199600,"title":"Vite won't allow CORS (Vue3 application)","tags":["express","cors","vuejs3","vite"],"text":"Title: Vite won't allow CORS (Vue3 application)\nTags: express, cors, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI am developing a Vue3 app with Vite as the bundler. The app is served from `localhost:5173`. The app communicates with an Express.js API, which is served from `localhost:3000`. This is the request code:\n\n```\nconst req = await fetch(\"http://localhost:3000/api/book\", {\n method: \"POST\",\n body: JSON.stringify({ bookId: 4 })\n}).then(res => res.json())\n```\n\nThis is working. But when I add a `Content-Type` header, I get a CORS error:\n\n```\nconst req = await fetch(\"http://localhost:3000/api/book\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n }\n body: JSON.stringify({ bookId: 4 })\n}).then(res => res.json())\n```\n\nAccess to fetch at 'http://localhost:3000/api/book' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.\n\nTo get around this, I followed the Vite docs for enabling CORS, and here is the updated `vite.config.js`:\n\n```\nimport { fileURLToPath, URL } from 'node:url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [vue()],\n server: {\n cors: {\n origin: \"http://localhost:3000\",\n methods: [\"GET\", \"POST\"],\n allowedHeaders: [\"Content-Type\", \"Authorization\"],\n preflightContinue: true\n }\n },\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url))\n }\n }\n})\n```\n\nBut the error persists. How do I fix this?\n\n========================================\n\nCode:\n```text\nconst req = await fetch(\"http://localhost:3000/api/book\", {\n    method: \"POST\",\n    body: JSON.stringify({ bookId: 4 })\n}).then(res => res.json())\n```\n\n```text\nconst req = await fetch(\"http://localhost:3000/api/book\", {\n    method: \"POST\",\n    headers: {\n        \"Content-Type\": \"application/json\"\n    }\n    body: JSON.stringify({ bookId: 4 })\n}).then(res => res.json())\n```\n\n```text\nimport { fileURLToPath, URL } from 'node:url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue()],\n  server: {\n    cors: {\n      origin: \"http://localhost:3000\",\n      methods: [\"GET\", \"POST\"],\n      allowedHeaders: [\"Content-Type\", \"Authorization\"],\n      preflightContinue: true\n    }\n  },\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url))\n    }\n  }\n})\n```\n\n```text\nlocalhost:5173\n```\n\n```text\nlocalhost:3000\n```\n\n```text\nContent-Type\n```\n\n```text\nvite.config.js\n```\n\n```text\nimport express from 'express'\nimport cors from 'cors'\n\nconst app = express()\napp.use(cors())\n```\n\n========================================\n\nComments:\n- What does it have to do with HTTPS?\n- See MDN on CORS. CORS is essentially an authorization system and so requires SSL for a lot of it to work.\n- @WaisKamal One problem with your CORS config is that you're allowing the wrong Web origin (`http:&#47;&#47;localhost:3000`). The error message indeed indicates that your client's Web origin is `http:&#47;&#47;localhost:5173`; this is the one you should allow in your CORS config.\n- @jub0bs requests coming from `http:&#47;&#47;localhost:5173` are always same-origin relative to Vite, because that is the address from which it is serving the Vue app.\n- @WaisKamal AFAIU, your Vite server is accessible on `http:&#47;&#47;localhost:3000` and your Vue frontend is on `http:&#47;&#47;localhost:5173`. Correct? If not, please explain to me what I'm missing. But if I'm correct, you'll need to allow `http:&#47;&#47;localhost:5173` in your server's CORS configuration. Allowing all Web origins as you've done in your answer is one way of doing it, but you may want to restrict the list of allowed origins to the bare minimum.\n- No, the Vite server is serving the frontend (the Vue app) on `http:&#47;&#47;localhost:5173`, i.e. the Vite server and the frontend are running at the same origin: `http:&#47;&#47;localhost:5173`. The Express server is the one running at ` `localhost:3000``.","metadata":{"transformedAt":"2026-08-18T18:33:46.421Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":135,"estimatedTokens":1070}}357{"id":"stack-73430553","source":"stackoverflow","questionId":73430553,"title":"Vue3 Pinia Store cannot access 'store\" before initializsation","tags":["vue.js","vuejs3","vite","pinia"],"text":"Title: Vue3 Pinia Store cannot access 'store\" before initializsation\nTags: vue.js, vuejs3, vite, pinia\nSource: Stack Overflow\n\nQuestion:\nI have a UserStore which contains some information about the current user. This store also is responsible for loggin in and out.\n\nIn order to make the getters available I map the getters to my computed attribute within my Vue component.\n\nUnfortunately I get an error saying that it cannot access useUserStore before initilization.\n\nThis is my component:\n\n```\n\n //...\n\nimport {mapState} from \"pinia\"\nimport {useUserStore} from \"../../stores/UserStore.js\";\nimport LoginForm from \"../../components/forms/LoginForm.vue\";\n\nexport default {\n name: \"Login\",\n components: {LoginForm},\n computed: {\n ...mapState(useUserStore, [\"user\", \"isAuthenticated\"]) //commenting this out makes it work\n }\n}\n\n```\n\nThis is my store:\n\n```\nimport { defineStore } from 'pinia'\nimport {gameApi} from \"../plugins/gameApi.js\"\nimport {router} from \"../router.js\";\n\nexport const useUserStore = defineStore(\"UserStore\", {\n persist: true,\n state: () => ({\n authenticated: false,\n _user: null\n }),\n\n getters: {\n user: (state) => state._user,\n isAuthenticated: (state) => state.authenticated\n },\n\n actions: {\n async checkLoginState() {\n // ...\n },\n async loginUser(fields) {\n // ...\n },\n async logutUser() {\n // ...\n }\n }\n})\n```\n\nAnd my main.js\n\n```\nimport {createApp} from 'vue'\nimport App from './App.vue'\nimport gameApi from './plugins/gameApi'\nimport {router} from './router.js'\nimport store from \"./stores/index.js\";\n\ncreateApp(App)\n .use(store)\n .use(router)\n .use(gameApi)\n .mount('#app')\n```\n\nAnd finally my store configuration:\n\n```\nimport {createPinia} from \"pinia\"\nimport piniaPluginPersistedstate from 'pinia-plugin-persistedstate'\nimport {useUserStore} from \"./UserStore.js\";\n\nconst piniaStore = createPinia()\npiniaStore.use(piniaPluginPersistedstate)\n\nexport default {\n install: (app, options) => {\n app.use(piniaStore)\n\n const userStore = useUserStore()\n const gameStore = useGameStore()\n }\n}\n```\n\n========================================\n\nTop Answer:\nFirstly, I want to credit the comment by Estus Flask as the correct answer for me for this issue, and just expand on it a bit to hopefully help others.\n\nThis for me (and possibly also the OP) was caused by importing App.vue before router/store. To use the OPs code and my resolution, it would be to change:\n\n```\nimport {createApp} from 'vue'\nimport App from './App.vue'\nimport gameApi from './plugins/gameApi'\nimport {router} from './router.js'\nimport store from \"./stores/index.js\";\n\ncreateApp(App)\n .use(store)\n .use(router)\n .use(gameApi)\n .mount('#app')\n```\n\nto\n\n```\nimport {createApp} from 'vue'\nimport gameApi from './plugins/gameApi'\nimport {router} from './router.js'\nimport store from \"./stores/index.js\";\nimport App from './App.vue'\n\ncreateApp(App)\n .use(store)\n .use(router)\n .use(gameApi)\n .mount('#app')\n```\n\n========================================\n\nCode:\n```text\n<template>\n  //...\n</template>\n\n<script>\nimport {mapState} from \"pinia\"\nimport {useUserStore} from \"../../stores/UserStore.js\";\nimport LoginForm from \"../../components/forms/LoginForm.vue\";\n\nexport default {\n  name: \"Login\",\n  components: {LoginForm},\n  computed: {\n    ...mapState(useUserStore, [\"user\", \"isAuthenticated\"]) //commenting this out makes it work\n  }\n}\n</script>\n```\n\n```text\nimport { defineStore } from 'pinia'\nimport {gameApi} from \"../plugins/gameApi.js\"\nimport {router} from \"../router.js\";\n\nexport const useUserStore = defineStore(\"UserStore\", {\n    persist: true,\n    state: () => ({\n            authenticated: false,\n            _user: null\n    }),\n\n    getters: {\n        user: (state) => state._user,\n        isAuthenticated: (state) => state.authenticated\n    },\n\n    actions: {\n        async checkLoginState() {\n            // ...\n        },\n        async loginUser(fields) {\n            // ...\n        },\n        async logutUser() {\n            // ...\n        }\n    }\n})\n```\n\n```text\nimport {createApp} from 'vue'\nimport App from './App.vue'\nimport gameApi from './plugins/gameApi'\nimport {router} from './router.js'\nimport store from \"./stores/index.js\";\n\ncreateApp(App)\n    .use(store)\n    .use(router)\n    .use(gameApi)\n    .mount('#app')\n```\n\n```text\nimport {createPinia} from \"pinia\"\nimport piniaPluginPersistedstate from 'pinia-plugin-persistedstate'\nimport {useUserStore} from \"./UserStore.js\";\n\nconst piniaStore = createPinia()\npiniaStore.use(piniaPluginPersistedstate)\n\nexport default {\n    install: (app, options) => {\n        app.use(piniaStore)\n\n        const userStore = useUserStore()\n        const gameStore = useGameStore()\n    }\n}\n```\n\n```text\n<script>\nimport {useUserStore} from \"../../stores/UserStore.js\";\n\nexport default {\n  name: \"RegisterForm\",\n\n  setup() {\n    // initialize the store\n    const userStore = useUserStore()\n    return {userStore}\n  },\n\n  data() {\n    return {\n      // ...\n    }\n  },\n\n  methods: {\n    checkLoginState() {\n      this.userStore.checkLoginState()\n    }\n  }\n}\n</script>\n```\n\n```text\nsetup()\n```\n\n```text\nimport {createApp} from 'vue'\nimport App from './App.vue'\nimport gameApi from './plugins/gameApi'\nimport {router} from './router.js'\nimport store from \"./stores/index.js\";\n\ncreateApp(App)\n    .use(store)\n    .use(router)\n    .use(gameApi)\n    .mount('#app')\n```\n\n```text\nimport {createApp} from 'vue'\nimport gameApi from './plugins/gameApi'\nimport {router} from './router.js'\nimport store from \"./stores/index.js\";\nimport App from './App.vue'\n\ncreateApp(App)\n    .use(store)\n    .use(router)\n    .use(gameApi)\n    .mount('#app')\n```\n\n========================================\n\nComments:\n- The problem is likely with dependency graph. Try to move `import App` lower. Check if the use of `import LoginForm` affects this\n- Your last snippet fixed my problem. To implement the install function and implement the useStore already there. This was the hint i didn't find in the documentation. Thanks.\n- There is an open issue to fix this problem github.com/vitejs/vite/issues/3033. Some people managed to solve it by adding additional configuration in vite.config.ts plugins. With me it didn't work. Unfortunately I will be using your solution\n- This is definitely a problem with vite. My code with webpack works. What I suggest for some people is to use a vite version below 4.0.13","metadata":{"transformedAt":"2026-08-18T18:33:46.421Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":290,"estimatedTokens":1576}}358{"id":"stack-77537194","source":"stackoverflow","questionId":77537194,"title":"typescript error TS2305: Module \"constants\" has no exported member","tags":["reactjs","typescript","vite","react-typescript"],"text":"Title: typescript error TS2305: Module \"constants\" has no exported member\nTags: reactjs, typescript, vite, react-typescript\nSource: Stack Overflow\n\nQuestion:\nI have Vite + React + TypeScript app with structure\n\n```\nsrc\n constants\n a.ts\n b.ts\n index.ts\n components\n Comp.tsx\n```\n\n**tsconfig** with `\"baseUrl\": \"src\"`\n\n**a.ts** content:\n\n```\nexport const ARRAY = [1, 2, 3];\n```\n\n**b.ts** content:\n\n```\nexport const Object = { foo: 'bar' };\n```\n\n**index.ts** content:\n\n```\nexport * from './a';\nexport * from './b';\n```\n\n**Comp.tsx** content:\n\n```\nimport { ARRAY } from 'constants';\n```\n\nApp works correctly, but in the WebStorm there is an error in **Comp.tsx**:\n\n```\nTS2305: Module  \"constants\"  has no exported member  ARRAY\n```\n\nWhy? How can I fix it?\n\nI want to get rid of this error.\n\n========================================\n\nCode:\n```text\nsrc\n  constants\n    a.ts\n    b.ts\n    index.ts\n  components\n    Comp.tsx\n```\n\n```text\nexport const ARRAY = [1, 2, 3];\n```\n\n```text\nexport const Object = { foo: 'bar' };\n```\n\n```text\nexport * from './a';\nexport * from './b';\n```\n\n```text\nimport { ARRAY } from 'constants';\n```\n\n```text\nTS2305: Module  \"constants\"  has no exported member  ARRAY\n```\n\n```text\n\"baseUrl\": \"src\"\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"paths\": {\n       \"constants\": [\"./src/constants\"]\n    }\n  }\n}\n```\n\n```text\nconstants\n```\n\n```text\nnode_modules/@types/node/constants.d.ts\n```\n\n```text\nconstants\n```\n\n```text\nconstants\n```\n\n```text\nutils\n```\n\n```text\nconsts\n```\n\n```text\nlocalConstants\n```\n\n```text\nconstants\n```\n\n```text\ncompilerOptions\n```\n\n```text\ntsconfig.*\n```\n\n```text\njsconfig.*\n```\n\n========================================\n\nComments:\n- It may affiliate with the project and Typescript path setup. The `constants` itself is a reserved word for the node types lib. Therefore, it can be conflicted if you do not explicitly define the proper path to the `constants` directory in your project. The best and easiest way to solve this issue is to avoid using it directly as a directory.","metadata":{"transformedAt":"2026-08-18T18:33:46.421Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":150,"estimatedTokens":504}}359{"id":"stack-73104639","source":"stackoverflow","questionId":73104639,"title":"Cannot Initialize a Vite App due to syntax error on internal files","tags":["vite"],"text":"Title: Cannot Initialize a Vite App due to syntax error on internal files\nTags: vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to run `npm init vite` on Ubuntu 22.04 LTS and node v12.22.9, but it gaves me this error\n\n```\nfile:///home/giacomo/.npm/_npx/2c4a09cdd3a6d615/node_modules/create-vite/index.js:296\nreturn targetDir?.trim().replace(/\\/+$/g, '')\n ^\n\nSyntaxError: Unexpected token '.'\n at Loader.moduleStrategy (internal/modules/esm/translators.js:133:18)\n at async link (internal/modules/esm/module_job.js:42:21)\n npm ERR! code 1\n npm ERR! path /home/giacomo/Scrivania/html/3DWebApp\n npm ERR! command failed\n npm ERR! command sh -c create-vite\n\n npm ERR! A complete log of this run can be found in:\n npm ERR! /home/giacomo/.npm/_logs/2022-07-25T05_58_55_401Z-debug-0.log\n```\n\nI've tried other methods like `npm init @vitejs/app` or `npm create @vitejs/app` but they're deprecated.\nThere's a way i can manually fix it or there is another method to try?\n\n========================================\n\nTop Answer:\nYeah, i had the same problem while using the node version `14.19.3`..\n\nThen, i upgraded the node version to `v16.10.0` - It solved and the app is running fine now. Thanks.\n\n========================================\n\nCode:\n```text\nfile:///home/giacomo/.npm/_npx/2c4a09cdd3a6d615/node_modules/create-vite/index.js:296\nreturn targetDir?.trim().replace(/\\/+$/g, '')\n               ^\n\nSyntaxError: Unexpected token '.'\n    at Loader.moduleStrategy (internal/modules/esm/translators.js:133:18)\n    at async link (internal/modules/esm/module_job.js:42:21)\n    npm ERR! code 1\n    npm ERR! path /home/giacomo/Scrivania/html/3DWebApp\n    npm ERR! command failed\n    npm ERR! command sh -c create-vite\n\n    npm ERR! A complete log of this run can be found in:\n    npm ERR!     /home/giacomo/.npm/_logs/2022-07-25T05_58_55_401Z-debug-0.log\n```\n\n```text\nnpm init vite\n```\n\n```text\nnpm init @vitejs/app\n```\n\n```text\nnpm create @vitejs/app\n```\n\n```text\n?.\n```\n\n```text\nn\n```\n\n```text\n14.19.3\n```\n\n```text\nv16.10.0\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.421Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":81,"estimatedTokens":505}}360{"id":"stack-79346647","source":"stackoverflow","questionId":79346647,"title":"vitest with AnalogJS angular-vite-plugin | Error: No test suite found in file","tags":["angular","github-actions","vite","vitest"],"text":"Title: vitest with AnalogJS angular-vite-plugin | Error: No test suite found in file\nTags: angular, github-actions, vite, vitest\nSource: Stack Overflow\n\nQuestion:\nI have a monorepo with an Angular project and a few Node.js projects.\n\nRunning `vitest` locally, all tests are passing. However, in GitHub Actions, the Angular tests are failing.\n\n### GitHub Actions test error\n\n```\n⎯⎯⎯⎯⎯⎯ Failed Suites 1 ⎯⎯⎯⎯⎯⎯⎯\n\n FAIL |angular-project| src/app/app.component.spec.ts [ apps/angular-project/src/app/app.component.spec.ts ]\nError: No test suite found in file /home/runner/work/my-org/my-repo/apps/angular-project/src/app/app.component.spec.ts\n⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯\n\n Test Files 1 failed (1)\n Tests no tests\n Start at 15:22:08\n Duration 762ms (transform 46ms, setup 26ms, collect 16ms, tests 0ms, environment 449ms, prepare 551ms)\n\n ELIFECYCLE  Command failed with exit code 1.\n```\n\nHere is my `vitest` config:\n\n### vitest.config.mts\n\n```\n/// \n/* eslint-disable no-restricted-globals */\n\nimport angular from '@analogjs/vite-plugin-angular'\nimport path from 'node:path'\nimport { defineConfig } from 'vite'\nimport viteTsConfigPaths from 'vite-tsconfig-paths'\n\nconst PROJECT_NAME = 'angular-project'\n\ndeclare global {\n namespace NodeJS {\n interface ProcessEnv {\n GITHUB_ACTIONS?: string\n }\n }\n}\n\nexport default defineConfig({\n root: 'apps/angular-project',\n\n plugins: [\n angular(),\n viteTsConfigPaths({\n projects: ['../../tsconfig.base.json', './tsconfig.json', './tsconfig.spec.json'],\n }),\n ],\n\n test: {\n name: PROJECT_NAME,\n globals: true,\n environment: 'jsdom',\n setupFiles: ['./src/test-setup.ts'],\n include: ['./src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],\n reporters: process.env.GITHUB_ACTIONS ? ['verbose', 'github-actions'] : 'default',\n server: {\n deps: {\n inline: ['@angular/material'],\n },\n },\n env: process.env,\n coverage: {\n provider: 'v8',\n reportsDirectory: './coverage',\n },\n },\n\n define: {\n 'import.meta.vitest': true,\n },\n})\n```\n\nBy commenting out the `angular()` plugin, the error `No test suite found in file` is resolved, but then all of the tests fail, since `vitest` doesn't support Angular out of the box (as of January 2025).\n\n========================================\n\nCode:\n```bash\n⎯⎯⎯⎯⎯⎯ Failed Suites 1 ⎯⎯⎯⎯⎯⎯⎯\n\n FAIL |angular-project|  src/app/app.component.spec.ts [ apps/angular-project/src/app/app.component.spec.ts ]\nError: No test suite found in file /home/runner/work/my-org/my-repo/apps/angular-project/src/app/app.component.spec.ts\n⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯\n\n Test Files  1 failed (1)\n      Tests  no tests\n   Start at  15:22:08\n   Duration  762ms (transform 46ms, setup 26ms, collect 16ms, tests 0ms, environment 449ms, prepare 551ms)\n\n ELIFECYCLE  Command failed with exit code 1.\n```\n\n```js\n/// <reference types=\"vitest\" />\n/* eslint-disable no-restricted-globals */\n\nimport angular from '@analogjs/vite-plugin-angular'\nimport path from 'node:path'\nimport { defineConfig } from 'vite'\nimport viteTsConfigPaths from 'vite-tsconfig-paths'\n\nconst PROJECT_NAME = 'angular-project'\n\ndeclare global {\n  namespace NodeJS {\n    interface ProcessEnv {\n      GITHUB_ACTIONS?: string\n    }\n  }\n}\n\nexport default defineConfig({\n  root: 'apps/angular-project',\n\n  plugins: [\n    angular(),\n    viteTsConfigPaths({\n      projects: ['../../tsconfig.base.json', './tsconfig.json', './tsconfig.spec.json'],\n    }),\n  ],\n\n  test: {\n    name: PROJECT_NAME,\n    globals: true,\n    environment: 'jsdom',\n    setupFiles: ['./src/test-setup.ts'],\n    include: ['./src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],\n    reporters: process.env.GITHUB_ACTIONS ? ['verbose', 'github-actions'] : 'default',\n    server: {\n      deps: {\n        inline: ['@angular/material'],\n      },\n    },\n    env: process.env,\n    coverage: {\n      provider: 'v8',\n      reportsDirectory: './coverage',\n    },\n  },\n\n  define: {\n    'import.meta.vitest': true,\n  },\n})\n```\n\n```text\nvitest\n```\n\n```text\nvitest\n```\n\n```text\nangular()\n```\n\n```text\nNo test suite found in file\n```\n\n```text\nvitest\n```\n\n```js\n/// <reference types=\"vitest\" />\n/* eslint-disable no-restricted-globals */\n\nimport angular from '@analogjs/vite-plugin-angular'\nimport path from 'node:path'\nimport { defineConfig } from 'vite'\nimport viteTsConfigPaths from 'vite-tsconfig-paths'\n\nconst PROJECT_NAME = 'angular-project'\n\ndeclare global {\n  namespace NodeJS {\n    interface ProcessEnv {\n      GITHUB_ACTIONS?: string\n    }\n  }\n}\n\nexport default defineConfig({\n  root: 'apps/angular-project',\n\n  plugins: [\n    ...angular({\n      tsconfig: 'apps/angular-project/tsconfig.spec.json',\n      workspaceRoot: path.resolve(__dirname, '../../'),\n    }),\n    viteTsConfigPaths({\n      projects: ['../../tsconfig.base.json', './tsconfig.json', './tsconfig.spec.json'],\n    }),\n  ],\n\n  test: {\n    name: PROJECT_NAME,\n    globals: true,\n    environment: 'jsdom',\n    setupFiles: ['./src/test-setup.ts'],\n    include: ['./src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],\n    reporters: process.env.GITHUB_ACTIONS ? ['verbose', 'github-actions'] : 'default',\n    server: {\n      deps: {\n        inline: ['@angular/material'],\n      },\n    },\n    env: process.env,\n    coverage: {\n      provider: 'v8',\n      reportsDirectory: './coverage',\n    },\n  },\n\n  define: {\n    'import.meta.vitest': true,\n  },\n})\n```\n\n```text\ntsconfig.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\ntsconfig\n```\n\n```text\nworkspaceRoot\n```\n\n```text\nrepo_name/apps/angular-project/vitest.config.mts\n```\n\n```text\nrepo_name/apps/angular-project/tsconfig.spec.ts\n```\n\n```text\nvitest.config.mts\n```\n\n```text\n../../\n```\n\n```text\ntsconfig.spec.ts\n```\n\n```text\napps/angular-project/vitest.config.mts\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.421Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":274,"estimatedTokens":1413}}361{"id":"stack-73502963","source":"stackoverflow","questionId":73502963,"title":"Larave & Vite - Vite manifest missing odd files","tags":["laravel","vite"],"text":"Title: Larave & Vite - Vite manifest missing odd files\nTags: laravel, vite\nSource: Stack Overflow\n\nQuestion:\nhttps://i.sstatic.net/lKN1Y.png\n\nIn this image there are 5 separate images all in the same folder. When I run `npm run build` the manifest file is generated and two of the files are not entered (favicon-32x32|16x16).\n\nThe images are clearly present;\n\nhttps://i.sstatic.net/G28rl.png\n\nWhen this goes into production I get the following 500 error;\n\n```\n[2022-08-26 14:30:52] production.ERROR: Unable to locate file in Vite manifest: resources/images/favicon/favicon-32x32.png. {\"view\":{\"view\":\"/home/forge/myproject/resources/views/app.blade.php\",\"data\":[]},\"exception\":\"[object] (Spatie\\\\LaravelIgnition\\\\Exceptions\\\\ViewException(code: 0): Unable to locate file in Vite manifest: resources/images/favicon/favicon-32x32.png. at /home/forge/myproject/vendor/laravel/framework/src/Illuminate/Foundation/Vite.php:539)\n```\n\nIs there any reason why these files would not be added to the manifest?\n\n========================================\n\nCode:\n```text\n[2022-08-26 14:30:52] production.ERROR: Unable to locate file in Vite manifest: resources/images/favicon/favicon-32x32.png. {\"view\":{\"view\":\"/home/forge/myproject/resources/views/app.blade.php\",\"data\":[]},\"exception\":\"[object] (Spatie\\\\LaravelIgnition\\\\Exceptions\\\\ViewException(code: 0): Unable to locate file in Vite manifest: resources/images/favicon/favicon-32x32.png. at /home/forge/myproject/vendor/laravel/framework/src/Illuminate/Foundation/Vite.php:539)\n```\n\n```text\nnpm run build\n```\n\n```json\nbuild: { assetsInlineLimit: 0 }\n```\n\n```js\nimport.meta.glob([\n  '../images/**',\n  '../fonts/**',\n]);\n```\n\n```text\nvite.config.js\n```\n\n```text\nnpm run build\n```\n\n```text\nphp artisan view:clear\n```\n\n========================================\n\nComments:\n- Just tried the prefix to no avail. They can't be encoded because the page wont load and not in the manifest.\n- I've also tried renaming the files\n- You beauty, adding `build: { assetsInlineLimit: 0 },` to the `vite.config.js` fixed it, add it as the answer and I'll accept it!\n- This saved my life - I'd missed the import.meta.glob section ....was going mad ...... HUUUUGE thanks","metadata":{"transformedAt":"2026-08-18T18:33:46.421Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":62,"estimatedTokens":548}}362{"id":"stack-71620415","source":"stackoverflow","questionId":71620415,"title":"How do I use dayjs in Vite for Vue or React?","tags":["vite","dayjs"],"text":"Title: How do I use dayjs in Vite for Vue or React?\nTags: vite, dayjs\nSource: Stack Overflow\n\nQuestion:\nIf you attempt to import dayjs into a Vue/React app using Vite you will find it fails. Vite only works with ESM modules.\n\n========================================\n\nTop Answer:\nDayJS Docs are confusing. Vite dev working OK, BUT facing errors on vite build/preview. Problem was in my code:\n\n**WRONG**:\n\n```\nimport dayjs from \"dayjs\";\nimport * as customParseFormat from \"dayjs/plugin/customParseFormat\";\ndayjs.extend(customParseFormat);\n```\n\n**CORRECT**:\n\n```\nimport dayjs from \"dayjs\";\nimport customParseFormat from \"dayjs/plugin/customParseFormat\";\ndayjs.extend(customParseFormat);\n```\n\n========================================\n\nCode:\n```text\nimport dayjs from 'dayjs/esm/index.js'\n```\n\n```js\nimport dayjs from \"dayjs\";\nimport * as customParseFormat from \"dayjs/plugin/customParseFormat\";\ndayjs.extend(customParseFormat);\n```\n\n```js\nimport dayjs from \"dayjs\";\nimport customParseFormat from \"dayjs/plugin/customParseFormat\";\ndayjs.extend(customParseFormat);\n```\n\n```none\nexport default defineConfig({\n  // ...config\n  ssr: {\n    optimizeDeps: {\n      include: ['dayjs'],\n    },\n  },\n});\n```\n\n```text\ndayjs\n```\n\n```text\noptimizeDeps\n```\n\n```text\nvite.config.ts\n```\n\n========================================\n\nComments:\n- Very strange. How come such a modern library has an issue like that?\n- In the era of AI copilots, Stack Overflow's accepted answer green tick is still winning my heart.","metadata":{"transformedAt":"2026-08-18T18:33:46.421Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":75,"estimatedTokens":373}}363{"id":"stack-70980498","source":"stackoverflow","questionId":70980498,"title":"Disable preload in Vite","tags":["vue.js","vite"],"text":"Title: Disable preload in Vite\nTags: vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI'm migrating a big project that uses Vue 2 and Webpack to Vue 3 and Vite. Everything looks great so far, however when we released to production in our first try we noticed that there were MANY module preload tags injected and many of the files there would probably never be used.\n\nThe question is, how can I disable preload project wise? If not possible, is there a way to telling Vite some of the imports that it should never preload?\n\nA use case for not preloading is a mocker file which is dynamically imported only in development environment, however it's referred in the code. Since it's lazy loaded I wouldn't have problem with Webpack on this, but Vite is acting ahead of time with optimizations and including everything it finds.\n\nExample from our codebase:\n\n```\nexport const fetchData = createGetService({\n url: '/example-endpoint',\n mocker: async () => (await import('./example.mocker')).mockExample(),\n});\n```\n\n========================================\n\nTop Answer:\nThere's currently no official way to disable preloads in the build.\n\nA workaround is to use a Vite plugin that removes the unwanted preloads from the built `index.html` via the `transformIndexHtml` hook:\n\n```\n// plugins/removePreloads.js\nexport default ({ filter = () => false } = {}) => ({\n name: 'remove-preloads',\n enforce: 'post',\n transformIndexHtml(html) {\n return html.replace(\n /\\s*()\\s*/gi,\n\n (orig, linkStr) => {\n if (filter(linkStr)) {\n return orig\n }\n console.log('\\nremoving ' + linkStr)\n return ''\n }\n )\n },\n})\n```\n\n```\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport removePreloads from './remove-preloads'\n\nexport default defineConfig({\n plugins: [\n // remove all preloads\n removePreloads(),\n\n // Or remove specific preloads\n removePreloads({\n filter: linkStr => !linkStr.contains('someFilename')\n }),\n ⋮\n ],\n})\n```\n\ndemo\n\n========================================\n\nCode:\n```js\nexport const fetchData = createGetService({\n  url: '/example-endpoint',\n  mocker: async () => (await import('./example.mocker')).mockExample(),\n});\n```\n\n```js\n// vite.config.js\n\nimport {defineConfig} from 'vite'\n\nexport default defineConfig({\n    ...\n    build: {\n        // Disables the preload.\n        modulePreload: false,\n\n        // Or you can specify what should be preloaded.\n        modulePreload: {\n            resolveDependencies(url, deps, context) {\n                return [] // Your list of preloaded deps.\n            },\n        },\n    },\n})\n```\n\n```text\n3.1\n```\n\n```js\n// plugins/removePreloads.js\nexport default ({ filter = () => false } = {}) => ({\n  name: 'remove-preloads',\n  enforce: 'post',\n  transformIndexHtml(html) {\n    return html.replace(\n      /\\s*(<link rel=\"(?:module)?preload\".*?>)\\s*/gi,\n\n      (orig, linkStr) => {\n        if (filter(linkStr)) {\n          return orig\n        }\n        console.log('\\nremoving ' + linkStr)\n        return ''\n      }\n    )\n  },\n})\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport removePreloads from './remove-preloads'\n\nexport default defineConfig({\n  plugins: [\n    // remove all preloads\n    removePreloads(),\n\n    // Or remove specific preloads\n    removePreloads({\n      filter: linkStr => !linkStr.contains('someFilename')\n    }),\n    ⋮\n  ],\n})\n```\n\n```text\nindex.html\n```\n\n```text\ntransformIndexHtml\n```\n\n========================================\n\nComments:\n- I'm not sure what's the correct to do when the answer changes with time, should I mark yours as the answer or suggest the original one to update with yours?","metadata":{"transformedAt":"2026-08-18T18:33:46.421Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":156,"estimatedTokens":895}}364{"id":"stack-76115927","source":"stackoverflow","questionId":76115927,"title":"page not found - react/vite app not routing correctly on github pages","tags":["reactjs","single-page-application","github-pages","vite"],"text":"Title: page not found - react/vite app not routing correctly on github pages\nTags: reactjs, single-page-application, github-pages, vite\nSource: Stack Overflow\n\nQuestion:\nI deployed my app to `gh-pages` and the root works, but whenever I reroute or try and add to the root, I get a page not found error. Locally it works.\n\nI've seen people suggest changing from `` to `` but that didn't help. I've also seen, and even used, a solution for `create-react-app` or `webpack` where you add some code to the `index.html` file in the `public` directory as well as a `404.html` but the issue is `vite` has a different file structure.\n\nWhere would I put them in a `vite` application where there's nothing in the `public` directory. It does have a `dist` folder with an `index.html` but I'm not sure if that's the one.\n\nNot sure what code I would need to show, but here's my `main.jsx` and `App.jsx` files:\n\n```\nimport { BrowserRouter as Router, Routes, Route } from \"react-router-dom\";\n\nfunction App() {\n return (\n \n \n \n \n } />\n } />\n \n \n \n );\n}\n```\n\n```\nReactDOM.createRoot(document.getElementById(\"root\")).render(\n \n \n \n);\n```\n\nAgain, locally this works, and when deploying to `gh-pages` the root or home page work, but no extended routes. Like I said, I had a similar issue with `webpack` but the solution I got there didn't work since `vite` has different file structure so I was unsure how to add the correct files.\n\nEDIT: I've also seen a github issue where a user had a similar issue and the solution was to define routes in the `vite.config.js` but again the difference there is that user had multiple `index.html` files for each component/route. I just have the standard `` situation wrapping my routes.\n\n========================================\n\nTop Answer:\nThe main point here is to understand how GH pages serve static files. If there is not a file matched to a given URL, it automatically serves `404.html`. So we just need to have `404.html`, which has the same content as the `index.html` that we get from vite build.\n\n**Therefore, all you need to to is to copy `index.html` to `404.html` inside `dist` directory.**\n\nI'm not sure how you manage GH page publish.\n\nIf you use Github Actions, please add a custom step to copy `index.html` to `404.html`.\n\n```\ncp ./dist/index.html ./dist/404.html\n```\n\nIf you use `gh-pages` branch, I think you should copy `index.html` to `404.html` before you push your changes to the branch.\n\nI have created a public repo, which you can take a look for a reference.\nhttps://github.com/richard929/vite-gh-pages-example\n\nI used react-router v6, and github actions for GH pages publish. I hope you already know about `base` configuration of `vite`, when deploying Vite app to static website.\n\n========================================\n\nCode:\n```text\nimport { BrowserRouter as Router, Routes, Route } from \"react-router-dom\";\n\nfunction App() {\n  return (\n    <Router>\n      <Header />\n      <div className=\"app\">\n        <Routes>\n          <Route path=\"/\" element={<Home />} />\n          <Route path=\"/example\" element={<Example />} />\n        </Routes>\n      </div>\n    </Router>\n  );\n}\n```\n\n```text\nReactDOM.createRoot(document.getElementById(\"root\")).render(\n  <React.StrictMode>\n    <App />\n  </React.StrictMode>\n);\n```\n\n```text\ngh-pages\n```\n\n```text\n<BrowserRouter>\n```\n\n```text\n<HashRouter>\n```\n\n```text\ncreate-react-app\n```\n\n```text\nwebpack\n```\n\n```text\nindex.html\n```\n\n```text\npublic\n```\n\n```text\n404.html\n```\n\n```text\nvite\n```\n\n```text\nvite\n```\n\n```text\npublic\n```\n\n```text\ndist\n```\n\n```text\nindex.html\n```\n\n```text\nmain.jsx\n```\n\n```text\nApp.jsx\n```\n\n```text\ngh-pages\n```\n\n```text\nwebpack\n```\n\n```text\nvite\n```\n\n```text\nvite.config.js\n```\n\n```text\nindex.html\n```\n\n```text\n<BrowserRouter>\n```\n\n```text\n<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <title>Page Not Found</title>\n    <script>\n      sessionStorage.redirect = location.href;\n    </script>\n    <meta http-equiv=\"refresh\" content=\"0;URL='/'\" />\n  </head>\n  <body></body>\n</html>\n```\n\n```text\n<script>\n      (() => {\n        const redirect = sessionStorage.redirect;\n        delete sessionStorage.redirect;\n        if (redirect && redirect !== location.href) {\n          history.replaceState(null, null, redirect);\n        }\n      })();\n    </script>\n```\n\n```text\nexport default defineConfig({\n  plugins: [react()],\n  build: {\n    rollupOptions: {\n      input: {\n        main: resolve(__dirname, \"index.html\"),\n        404: resolve(__dirname, \"public/404.html\"),\n      },\n    },\n  },\n});\n```\n\n```text\n404.html\n```\n\n```text\nindex.html\n```\n\n```text\n</body>\n```\n\n```text\nvite.config.js\n```\n\n```text\ncp ./dist/index.html ./dist/404.html\n```\n\n```text\n404.html\n```\n\n```text\n404.html\n```\n\n```text\nindex.html\n```\n\n```text\nindex.html\n```\n\n```text\n404.html\n```\n\n```text\ndist\n```\n\n```text\nindex.html\n```\n\n```text\n404.html\n```\n\n```text\ngh-pages\n```\n\n```text\nindex.html\n```\n\n```text\n404.html\n```\n\n```text\nbase\n```\n\n```text\nvite\n```\n\n```text\nimport SignIn from './pages/Signin'\n\nfunction App() {\nreturn (\n  <BrowserRouter basename=\"/your-repositorie-name\">\n    <Routes>\n      <Route path=\"/\" element={<SignIn />} />\n    </Routes>\n  </BrowserRouter>\n)\n}\n\nexport default App\n```\n\n```text\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  base: '/your-repository-name/',\n})\n```\n\n========================================\n\nComments:\n- Does this answer your question? React-Router issue when deployed to Github Pages?\n- When deploying `gh-pages` it runs `npm run build` which creates a new dist folder. How can I keep this file in the folder during production\n- I think it depends on the way deploying to production. If you use pipelines, you can always extend it to add custom step. If you do this manually, then no trouble, I suppose.\n- resolve showing deprecated when doing the above - no docs anywhere for what to replace it with for vite build.... how to get update?\n- Add import for `resolve` from `path` module. `import { resolve } from 'path'`","metadata":{"transformedAt":"2026-08-18T18:33:46.421Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":46,"totalLines":326,"estimatedTokens":1528}}365{"id":"stack-72366602","source":"stackoverflow","questionId":72366602,"title":"Fetching a github repo in react gives a \"Module \"stream\" has been externalized for browser compatibility and cannot be accessed in client code\" error","tags":["reactjs","typescript","fetch","github-api","vite"],"text":"Title: Fetching a github repo in react gives a \"Module \"stream\" has been externalized for browser compatibility and cannot be accessed in client code\" error\nTags: reactjs, typescript, fetch, github-api, vite\nSource: Stack Overflow\n\nQuestion:\nI am currently stuck with a problem trying to fetch github repo data using the octokit npm package.\nI use vite to run a dev server and when I try to make a request, the error that i get is:\n\n```\nUncaught Error: Module \"stream\" has been externalized for browser compatibility and cannot be accessed in client code.\n```\n\nMy React .tsx file looks like this:\n\n```\nimport { Octokit, App } from 'octokit'\nimport React from 'react'\n\nconst key = import.meta.env.GITHUB_KEY\nconst octokit = new Octokit({\n auth: key\n })\nawait octokit.request('GET /repos/{owner}/{repo}', {\n owner: 'OWNER',\n repo: 'REPO'\n })\n \nexport default function Repos() {\n\n return (\n <>\n\n \n )\n}\n```\n\nI have redacted the information for privacy purposes.\nIf anyone knows how to resolve this issue with vite, please let me know!\n\n========================================\n\nCode:\n```text\nUncaught Error: Module \"stream\" has been externalized for browser compatibility and cannot be accessed in client code.\n```\n\n```text\nimport { Octokit, App } from 'octokit'\nimport React from 'react'\n\nconst key = import.meta.env.GITHUB_KEY\nconst octokit = new Octokit({\n    auth: key\n  })\nawait octokit.request('GET /repos/{owner}/{repo}', {\n    owner: 'OWNER',\n    repo: 'REPO'\n  })\n  \nexport default function Repos() {\n\n  return (\n    <>\n\n    </>\n  )\n}\n```\n\n```js\n// svelte.config.js\n\nconst config = {   // ...   kit: {\n    // ...\n    vite: {\n      resolve: {\n       alias: {\n         'node-fetch': 'isomorphic-fetch',\n       },\n     },\n   },\n },\n};\n\nexport default config;\n```\n\n```text\noctokit/octokit.js\n```\n\n```text\nisomorphic-fetch\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.421Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":95,"estimatedTokens":457}}366{"id":"stack-76188415","source":"stackoverflow","questionId":76188415,"title":"Vue3/Vite: module has been externalized","tags":["vue.js","vite"],"text":"Title: Vue3/Vite: module has been externalized\nTags: vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use `crypto` to hash strings in a Vue 3 app.\n\n```\nasync function hash (token) {\n const data = new TextEncoder().encode(token)\n const byteHash = await crypto.subtle.digest(\"SHA-256\", data)\n // ^ the below error is thrown here\n\n const arrayHash = Array.from(new Uint8Array(byteHash))\n const hexHash = arrayHash.map(b => b.toString(16).padStart(2, '0')).join('').toLocaleUpperCase()\n\n return hexHash\n}\n```\n\nFrom my understanding, `crypto` is available in the browser nowadays, so it needs no `browserify` replacement.\n\nNevertheless, I'm getting the following error in my browser console:\n\n```\nError: Module \"crypto\" has been externalized for browser compatibility. Cannot access \"crypto.subtle\" in client code.\n```\n\nI interpret this as \"Vite is configured to externalize the `crypto` module in the build process\". But I can see no such setting in my `vite.config.js`:\n\n```\n// Plugins:\nimport vue from '@vitejs/plugin-vue'\nimport vuetify from 'vite-plugin-vuetify'\n\n// Utilies:\nimport { defineConfig } from 'vite'\nimport { fileURLToPath, URL } from 'node:url'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n vue(),\n // https://github.com/vuetifyjs/vuetify-loader/tree/next/packages/vite-plugin\n vuetify({\n autoImport: true\n })\n ],\n define: { 'process.env': {} },\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url))\n },\n extensions: ['.js', '.json', '.jsx', '.mjs', '.ts', '.tsx', '.vue']\n },\n server: {\n port: 3000\n },\n test: {\n setupFiles: ['../vuetify.config.js'],\n deps: {\n inline: ['vuetify']\n },\n globals: true\n }\n})\n```\n\nAre there any \"baked in\" Vite default settings, that could cause this? Is this configured somewere else? How can I fix this issue and use the `crypto` module in my app?\n\n========================================\n\nCode:\n```js\nasync function hash (token) {\n    const data = new TextEncoder().encode(token)\n    const byteHash = await crypto.subtle.digest(\"SHA-256\", data)\n    //                            ^ the below error is thrown here\n\n    const arrayHash = Array.from(new Uint8Array(byteHash))\n    const hexHash = arrayHash.map(b => b.toString(16).padStart(2, '0')).join('').toLocaleUpperCase()\n\n    return hexHash\n}\n```\n\n```js\nError: Module \"crypto\" has been externalized for browser compatibility. Cannot access \"crypto.subtle\" in client code.\n```\n\n```js\n// Plugins:\nimport vue from '@vitejs/plugin-vue'\nimport vuetify from 'vite-plugin-vuetify'\n\n// Utilies:\nimport { defineConfig } from 'vite'\nimport { fileURLToPath, URL } from 'node:url'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    vue(),\n    // https://github.com/vuetifyjs/vuetify-loader/tree/next/packages/vite-plugin\n    vuetify({\n      autoImport: true\n    })\n  ],\n  define: { 'process.env': {} },\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url))\n    },\n    extensions: ['.js', '.json', '.jsx', '.mjs', '.ts', '.tsx', '.vue']\n  },\n  server: {\n    port: 3000\n  },\n  test: {\n    setupFiles: ['../vuetify.config.js'],\n    deps: {\n      inline: ['vuetify']\n    },\n    globals: true\n  }\n})\n```\n\n```text\ncrypto\n```\n\n```text\ncrypto\n```\n\n```text\nbrowserify\n```\n\n```text\ncrypto\n```\n\n```text\nvite.config.js\n```\n\n```text\ncrypto\n```\n\n```js\nfunction getCrypto() {\n  try {\n    return window.crypto;\n  } catch {\n    return crypto;\n  }\n}\n```\n\n```js\nasync function hash(token) {\n  const compatibleCrypto = getCrypto();\n\n  const data = new TextEncoder().encode(token);\n  const byteHash = await compatibleCrypto.subtle.digest('SHA-256', data);\n\n  const arrayHash = Array.from(new Uint8Array(byteHash));\n  const hexHash = arrayHash\n    .map(b => b.toString(16).padStart(2, '0'))\n    .join('')\n    .toLocaleUpperCase();\n\n  return hexHash;\n}\n```\n\n```text\ncrypto\n```\n\n```text\nwindow\n```\n\n```text\nwindow\n```\n\n```text\ncrypto\n```\n\n```text\nwindow.crypto\n```\n\n```text\nvite.config.js\n```\n\n========================================\n\nComments:\n- What is `comp`?\n- @mikemaccana \"compatibility\" I guess\n- It's just a variable name, but it stands for `compatibleCrypto`. I changed it.\n- How do you do the import of `crypto`?","metadata":{"transformedAt":"2026-08-18T18:33:46.421Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":210,"estimatedTokens":1053}}367{"id":"stack-75738867","source":"stackoverflow","questionId":75738867,"title":"Lingui map translated content not showing","tags":["reactjs","typescript","translation","vite","linguijs"],"text":"Title: Lingui map translated content not showing\nTags: reactjs, typescript, translation, vite, linguijs\nSource: Stack Overflow\n\nQuestion:\nI am using Lingui for translation from English to Arabic. I am using an array of objects to display my content. The issue I have is that the Arabic translation for the mapped array is not showing. The codes are in separate files.\n\n```\nimport { t } from \"@lingui/macro\";\nexport const Courses = [\n {\n id: 0,\n name: t`Unlock the secrets of Open Science.`,\n description: t`A beginner-friendly course to introduce the concepts and practices of Open Science.`,\n icon: Github,\n },\n {\n id: 2,\n name: t`Your Open Science Journey Begins Here.`,\n description: t`Learn the basics of Open Science and start your journey towards more open and transparent research and education.`,\n icon: JavaScript,\n },\n];\n\n \n\n{Courses.map(({ id, name, icon, description }) => (\n \n \n \n \n \n {name}\n \n \n {description}\n \n\n \n ))}\n```\n\n`i18n.ts` file:\n\n```\nimport { i18n } from \"@lingui/core\";\nimport { en, ar} from \"make-plural/plurals\";\n\nexport const locales = {\n en: \"English\",\n ar: \"Arabic\",\n};\nexport const defaultLocale = \"en\";\n\ni18n.loadLocaleData({\n en: { plurals: en },\n ar: { plurals: ar },\n});\n\ni18n.load(defaultLocale, {});\ni18n.activate(defaultLocale);\n\nexport async function dynamicActivate(locale: string) {\n const { messages } = await import(`./locales/${locale}/messages.ts`);\n i18n.load(locale, messages);\n i18n.activate(locale);\n}\n```\n\nThe `.linguirc` config\n\n```\n{\n \"locales\": [\"en\", \"ar\"],\n \"sourceLocale\": \"en\",\n \"catalogs\": [{\n \"path\": \"src/locales/{locale}/messages\",\n \"include\": [\"src\"]\n }],\n \"format\": \"minimal\",\n \"compileNamespace\": \"ts\"\n}\n```\n\n========================================\n\nTop Answer:\nUsage of `t` macro outside of function is not going to work. Solution proposed Elias Schablowski would work, but there is better solution\n\n```\nexport const Courses = [\n {\n id: 0,\n name: msg`Unlock the secrets of Open Science.`,\n description: msg`A beginner-friendly course to introduce the concepts and practices of Open Science.`,\n icon: Github,\n },\n {\n id: 2,\n name: msg`Your Open Science Journey Begins Here.`,\n description: msg`Learn the basics of Open Science and start your journey towards more open and transparent research and education.`,\n icon: JavaScript,\n },\n];\n\nconst {i18n} = useLingui();\n\n{Courses.map(({ id, name, icon, description }) => (\n \n \n \n \n \n {i18n._(name)}\n \n \n {i18n._(description)}\n \n\n \n))}\n```\n\nDocs: https://js-lingui-git-next-lingui.vercel.app/tutorials/react-patterns\n\n========================================\n\nCode:\n```js\nimport { t } from \"@lingui/macro\";\nexport const Courses = [\n  {\n    id: 0,\n    name: t`Unlock the secrets of Open Science.`,\n    description: t`A beginner-friendly course to introduce the concepts and practices of Open Science.`,\n    icon: Github,\n  },\n  {\n    id: 2,\n    name: t`Your Open Science Journey Begins Here.`,\n    description: t`Learn the basics of Open Science and start your journey towards more open and transparent research and education.`,\n    icon: JavaScript,\n  },\n];\n\n \n\n{Courses.map(({ id, name, icon, description }) => (\n            <div key={id} className=\"courses-section__container-course\">\n              <div className=\"courses-section__container-course__icon-content\">\n                <img\n                  src={icon}\n                  className=\"courses-section__container-course__icon-content-icon\"\n                  alt={`${name} icon`}\n                />\n              </div>\n              <h3 className=\"courses-section__container-course__name\">\n             {name}\n              </h3>\n              <p className=\"courses-section__container-course__description\">\n                {description}\n              </p>\n            </div>\n          ))}\n```\n\n```js\nimport { i18n } from \"@lingui/core\";\nimport { en, ar} from \"make-plural/plurals\";\n\nexport const locales = {\n  en: \"English\",\n  ar: \"Arabic\",\n};\nexport const defaultLocale = \"en\";\n\ni18n.loadLocaleData({\n  en: { plurals: en },\n  ar: { plurals: ar },\n});\n\ni18n.load(defaultLocale, {});\ni18n.activate(defaultLocale);\n\nexport async function dynamicActivate(locale: string) {\n  const { messages } = await import(`./locales/${locale}/messages.ts`);\n  i18n.load(locale, messages);\n  i18n.activate(locale);\n}\n```\n\n```json\n{\n  \"locales\": [\"en\", \"ar\"],\n  \"sourceLocale\": \"en\",\n  \"catalogs\": [{\n    \"path\": \"src/locales/{locale}/messages\",\n    \"include\": [\"src\"]\n  }],\n  \"format\": \"minimal\",\n  \"compileNamespace\": \"ts\"\n}\n```\n\n```text\ni18n.ts\n```\n\n```text\n.linguirc\n```\n\n```js\nimport { t } from \"@lingui/macro\";\n\nexport const Courses = [\n  {\n    id: 0,\n    name: () => t`Unlock the secrets of Open Science.`,\n    description: () => t`A beginner-friendly course to introduce the concepts and practices of Open Science.`,\n    icon: Github,\n  },\n  {\n    id: 2,\n    name: () => t`Your Open Science Journey Begins Here.`,\n    description: () => t`Learn the basics of Open Science and start your journey towards more open and transparent research and education.`,\n    icon: JavaScript,\n  },\n];\n\n\n{Courses.map(({ id, name, icon, description }) => (\n  <div key={id} className=\"courses-section__container-course\">\n    <div className=\"courses-section__container-course__icon-content\">\n      <img\n        src={icon}\n        className=\"courses-section__container-course__icon-content-icon\"\n        alt={`${name} icon`}\n      />\n    </div>\n    <h3 className=\"courses-section__container-course__name\">\n   {name()}\n    </h3>\n    <p className=\"courses-section__container-course__description\">\n      {description()}\n    </p>\n  </div>\n))}\n```\n\n```text\nt\n```\n\n```text\nexport const Courses = [\n  {\n    id: 0,\n    name: msg`Unlock the secrets of Open Science.`,\n    description: msg`A beginner-friendly course to introduce the concepts and practices of Open Science.`,\n    icon: Github,\n  },\n  {\n    id: 2,\n    name: msg`Your Open Science Journey Begins Here.`,\n    description: msg`Learn the basics of Open Science and start your journey towards more open and transparent research and education.`,\n    icon: JavaScript,\n  },\n];\n\n\nconst {i18n} = useLingui();\n\n{Courses.map(({ id, name, icon, description }) => (\n  <div key={id} className=\"courses-section__container-course\">\n    <div className=\"courses-section__container-course__icon-content\">\n      <img\n        src={icon}\n        className=\"courses-section__container-course__icon-content-icon\"\n        alt={`${name} icon`}\n      />\n    </div>\n    <h3 className=\"courses-section__container-course__name\">\n   {i18n._(name)}\n    </h3>\n    <p className=\"courses-section__container-course__description\">\n      {i18n._(description)}\n    </p>\n  </div>\n))}\n```\n\n```text\nt\n```\n\n========================================\n\nComments:\n- Could you please also provide the code that loads the translations, as the code you provided doesn't have any glaring issues\n- I have included the i18n.ts and linguric config files\n- It looks good as far as I can tell, the only reasons I can think of is 1. not running `lingui extract` and `lingui compile` 2. Not activating the locale (easy check is to rebuild with the default locale set to arabic) or 3. a caching issue/build path issue. (this is actually simpler than some of my designs with lingui)\n- There are other contents on the page and they perfectly displayed its Arabic text, it's only the mapped data that is not displaying the Arabic text","metadata":{"transformedAt":"2026-08-18T18:33:46.421Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":303,"estimatedTokens":1842}}368{"id":"stack-72099549","source":"stackoverflow","questionId":72099549,"title":"How add not imported image to output build with vite?","tags":["vite"],"text":"Title: How add not imported image to output build with vite?\nTags: vite\nSource: Stack Overflow\n\nQuestion:\nI have an `app` folder with some images that are used by the external script and I need to include those images in the dist build folder.\n\nI tried to log files that go to output and those images are not included. I tried to add `assetsInclude` property but seems that property is not for that purpose.\n\nHow can I include some specific images in `dist` folder that aren't imported explicitly ?\nHere is my `vite.config.js` file.\n\n```\nimport { resolve, parse } from 'path';\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n base: '/',\n root: resolve(__dirname, 'app'),\n\n assetsInclude: ['/app/images/externalImage.png'],\n\n build: {\n emptyOutDir: true,\n \n rollupOptions: {\n output: {\n dir: './dist',\n assetFileNames: (asset) => {\n console.log(parse(asset.name).name);\n if (parse(asset.name).name === 'externalImage') {\n return \"images/src/[name][extname]\";\n }\n return \"assets/[name].[hash][extname]\";\n }\n },\n },\n },\n});\n```\n\n========================================\n\nTop Answer:\nAccording to the documentation you can\nplace the asset in a special `public` directory under your project root. Assets in this directory will be served at root path `/` during dev, and copied to the root of the dist directory as-is.\n\nThe directory defaults to `/public`, but can be configured via the `publicDir` option.\n\n**Note that:**\n\n- You should always reference public assets using root absolute path - for example, `public/icon.png` should be referenced in source code as `/icon.png`.\n\n- Assets in `public` cannot be imported from JavaScript.\n\n========================================\n\nCode:\n```js\nimport { resolve, parse } from 'path';\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n  base: '/',\n  root: resolve(__dirname, 'app'),\n\n  assetsInclude: ['/app/images/externalImage.png'],\n\n  build: {\n    emptyOutDir: true,\n    \n    rollupOptions: {\n      output: {\n        dir: './dist',\n        assetFileNames: (asset) => {\n          console.log(parse(asset.name).name);\n          if (parse(asset.name).name === 'externalImage') {\n            return \"images/src/[name][extname]\";\n          }\n          return \"assets/[name].[hash][extname]\";\n        }\n      },\n    },\n  },\n});\n```\n\n```text\napp\n```\n\n```text\nassetsInclude\n```\n\n```text\ndist\n```\n\n```text\nvite.config.js\n```\n\n```js\nnew URL(\"../images/src/externalImage.png\", import.meta.url);\n```\n\n```js\nimport { resolve, parse } from 'path';\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n  base: '/',\n  root: resolve(__dirname, 'app'),\n\n  build: {\n    outDir: '../dist',\n    emptyOutDir: true,\n    \n    rollupOptions: {\n      output: {\n        assetFileNames: (asset) => {\n          if (parse(asset.name).name === 'externalImage') {\n            return \"images/src/[name][extname]\";\n          }\n          return \"assets/[name].[hash][extname]\";\n        }\n      },\n    },\n  },\n});\n```\n\n```text\napp/js/app.js\n```\n\n```text\noutDir\n```\n\n```text\npublic\n```\n\n```text\n/\n```\n\n```text\n<root>/public\n```\n\n```text\npublicDir\n```\n\n```text\npublic/icon.png\n```\n\n```text\n/icon.png\n```\n\n```text\npublic\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.421Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":168,"estimatedTokens":796}}369{"id":"stack-75414297","source":"stackoverflow","questionId":75414297,"title":"Vite Vue Welcome App production sourcemaps are incomplete","tags":["vue.js","vuejs3","vite","rollup"],"text":"Title: Vite Vue Welcome App production sourcemaps are incomplete\nTags: vue.js, vuejs3, vite, rollup\nSource: Stack Overflow\n\nQuestion:\nSee EDIT below for steps to reproduce.\n\nI am trying to generate sourcemaps for a production build for the HelloWorld App for Vite+Vue. Unfortunately it does not show all the components (only shows the WelcomeItem component). See snaphot from chrome devtools below:\n\nhttps://i.sstatic.net/EJq9m.png\n\nWhen you inspect the sourcemap files, you see that it does not add App.vue, Helloworld.vue and TheWelcome.vue to sources:\n\n```\n{\n \"version\": 3,\n \"file\": \"index-ecfc4d4f.js\",\n \"sources\": [\n \"../../node_modules/@vue/shared/dist/shared.esm-bundler.js\",\n \"../../node_modules/@vue/reactivity/dist/reactivity.esm-bundler.js\",\n \"../../node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js\",\n \"../../node_modules/@vue/runtime-dom/dist/runtime-dom.esm-bundler.js\",\n \"../../src/assets/logo.svg\",\n \"../../src/components/WelcomeItem.vue\",\n \"../../src/components/icons/IconDocumentation.vue\",\n \"../../src/components/icons/IconTooling.vue\",\n \"../../src/components/icons/IconEcosystem.vue\",\n \"../../src/components/icons/IconCommunity.vue\",\n \"../../src/components/icons/IconSupport.vue\",\n \"../../src/main.js\"\n ],\n \"sourcesContent\": [ ...\n ], ...\n}\n```\n\nThe dev mode is working OK, I can see my source code.\n\nHere is my config. All I did was add build.sourcemap=true.\n\n```\nexport default defineConfig({\n plugins: [vue()],\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url))\n }\n },\n build: {\n sourcemap: true\n }\n})\n```\n\nEDIT: Steps to reproduce\n\n```\nnpm init vue@latest\n// pick No everywhere\ncd vue-project\nnpm install\n// add build.sourcemap = true in the vite.config.js file as shown above\nnpm run build\nnpm run preview\n```\n\n========================================\n\nCode:\n```text\n{\n    \"version\": 3,\n    \"file\": \"index-ecfc4d4f.js\",\n    \"sources\": [\n        \"../../node_modules/@vue/shared/dist/shared.esm-bundler.js\",\n        \"../../node_modules/@vue/reactivity/dist/reactivity.esm-bundler.js\",\n        \"../../node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js\",\n        \"../../node_modules/@vue/runtime-dom/dist/runtime-dom.esm-bundler.js\",\n        \"../../src/assets/logo.svg\",\n        \"../../src/components/WelcomeItem.vue\",\n        \"../../src/components/icons/IconDocumentation.vue\",\n        \"../../src/components/icons/IconTooling.vue\",\n        \"../../src/components/icons/IconEcosystem.vue\",\n        \"../../src/components/icons/IconCommunity.vue\",\n        \"../../src/components/icons/IconSupport.vue\",\n        \"../../src/main.js\"\n    ],\n    \"sourcesContent\": [ ...\n    ], ...\n}\n```\n\n```text\nexport default defineConfig({\n  plugins: [vue()],\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url))\n    }\n  },\n  build: {\n    sourcemap: true\n  }\n})\n```\n\n```text\nnpm init vue@latest\n// pick No everywhere\ncd vue-project\nnpm install\n// add build.sourcemap = true in the vite.config.js file as shown above\nnpm run build\nnpm run preview\n```\n\n```text\n<script setup>\nimport HelloWorld from './components/HelloWorld.vue'\nimport TheWelcome from './components/TheWelcome.vue'\n\nconsole.log(\"Test\");\n</script>\n...\n```\n\n```text\nscript\n```\n\n```text\nApp.vue\n```\n\n```text\nApp.vue\n```\n\n========================================\n\nComments:\n- confirmed, this works, all components show up this way. Not sure if that's a feature or a bug. Thanks!\n- This is one of the weirdest bugs I've ever seen... I can confirm that the solution works! Adding an empty `console.log()` makes the File appear among the sources. Also, just for adding some more info... The missing sourcemaps files are the ones that contains `import` statement. If the file does not contain any import, it appears among the other sourcemaps files (no need for a console.log on these files)\n- thank you, using console.debug() worked for me as well","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":144,"estimatedTokens":973}}370{"id":"stack-74183472","source":"stackoverflow","questionId":74183472,"title":"How to run Vite with a different entry point than index.html","tags":["vite"],"text":"Title: How to run Vite with a different entry point than index.html\nTags: vite\nSource: Stack Overflow\n\nQuestion:\nWould like to run vite from the cli and use a different entry point than ./index.html like so:\n\n```\nvite -entrypoint ./gallery/slider.html\n```\n\nI cannot find a cli option and also no config option that allows a different entry point.\n\nI am concerned about dev serving not about the build phase.\n\n========================================\n\nCode:\n```text\nvite -entrypoint ./gallery/slider.html\n```\n\n```text\nvite serve ./gallery/\n```\n\n========================================\n\nComments:\n- How do you run Vite with a *file* as the entry point? Parcel can simply do `parcel test.html`.","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":30,"estimatedTokens":173}}371{"id":"stack-71581549","source":"stackoverflow","questionId":71581549,"title":"I can't import qs in vite","tags":["vuejs3","vite"],"text":"Title: I can't import qs in vite\nTags: vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI use vite, ts and vue3. Now I want to use qs.stringfy() to build a url's query, but it panic.\n\nI use `yarn add @types/qs` to add qs.\n\nMy code like this\n\n```\nimport qs from \"qs\";\n \n qs.stringify(data)\n```\n\nthe error is\n\n```\n[plugin:vite:import-analysis] Failed to resolve import \"qs\" from \"src\\tools\\oauth.ts\". Does the file exist?\n```\n\nHow can I resolve is?\n\n========================================\n\nCode:\n```text\nimport qs from \"qs\";\n    \n    qs.stringify(data)\n```\n\n```text\n[plugin:vite:import-analysis] Failed to resolve import \"qs\" from \"src\\tools\\oauth.ts\". Does the file exist?\n```\n\n```text\nyarn add @types/qs\n```\n\n```text\n@types/qs\n```\n\n```text\nqs\n```\n\n```text\n@types/qs\n```\n\n========================================\n\nComments:\n- Did you also install `qs`?\n- I finaly write a function to immplate `qs.stringify(data)` as I just want to get an redirect url.\n- same problem for me with `svelte` + `vite`. I installed qs by `npm install --save @types&#47;qs`","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":60,"estimatedTokens":263}}372{"id":"stack-73686454","source":"stackoverflow","questionId":73686454,"title":"Owl-carousel is not working after build the project using vite","tags":["javascript","jquery","tailwind-css","owl-carousel","vite"],"text":"Title: Owl-carousel is not working after build the project using vite\nTags: javascript, jquery, tailwind-css, owl-carousel, vite\nSource: Stack Overflow\n\nQuestion:\nI use vite to build this project.\nwhen I use owl-carousel from node_modules it works in development mode but after build, the carousel stops working and gets this error\n\n```\nUncaught TypeError: Cannot read properties of undefined (reading 'fn')\n at index.781bd673.js:4:36786\n at index.781bd673.js:4:37392\n```\n\nso I used it from CDN.\n\n```\n\n // CDN --> working after build \n // import 'https://code.jquery.com/jquery-3.2.1.slim.min.js';\n // import 'https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js';\n\n // node_modules --> not working after build\n import './node_modules/jquery/dist/jquery.slim.min.js';\n import './node_modules/owl.carousel/dist/owl.carousel.min.js';\n\n // customize owl carousel\n import './src/js/owl-carousel.js';\n\n```\n\nHow to use it from node_modules without that error??\n\n========================================\n\nTop Answer:\nThe below answer from @Asmaa Mahmoud did not work for me. Below is my solution. I hope this will help someone else struggling with the same issue.\n\nvite.config.js file:\n\n```\nimport { defineConfig } from 'vite';\nimport inject from '@rollup/plugin-inject';\nimport htmlPurge from 'vite-plugin-purgecss';\n\nexport default defineConfig({\n plugins: [\n inject({\n $: 'jquery',\n jQuery: 'jquery',\n 'window.jQuery': 'jquery',\n }),\n htmlPurge(),\n ],\n css: {\n devSourcemap: true,\n },\n});\n```\n\napp.js file:\n\n```\nimport './app.scss';\nimport 'owl.carousel/dist/assets/owl.carousel.css';\nimport $ from 'jquery';\nimport 'lazysizes';\nimport 'owl.carousel';\n\n$(function(){\n $('.owl-carousel').owlCarousel({});\n});\n```\n\n========================================\n\nCode:\n```text\nUncaught TypeError: Cannot read properties of undefined (reading 'fn')\n    at index.781bd673.js:4:36786\n    at index.781bd673.js:4:37392\n```\n\n```text\n<script type=\"module\">\n  // CDN --> working after build \n  // import 'https://code.jquery.com/jquery-3.2.1.slim.min.js';\n  // import 'https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js';\n\n  // node_modules --> not working after build\n  import './node_modules/jquery/dist/jquery.slim.min.js';\n  import './node_modules/owl.carousel/dist/owl.carousel.min.js';\n\n  // customize owl carousel\n  import './src/js/owl-carousel.js';\n</script>\n```\n\n```text\n// jquery.js file \n\nimport $ from 'jquery'; // from node_modules\nwindow.jQuery = $;\nexport default $;\n```\n\n```text\n// owl-carousel.js file\n\nimport $ from './jquery.js';\nimport 'owl.carousel'; // from node_modules\n\n$(document).ready(function () {\n  $('.owl-carousel').owlCarousel({\n    loop: true,\n    margin: 20,\n    autoplay: true,\n    responsive: {\n      0: {\n        items: 1,\n      },\n      600: {\n        items: 2,\n      },\n      1000: {\n        items: 3,\n      },\n    },\n  });\n});\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport inject from '@rollup/plugin-inject';\nimport htmlPurge from 'vite-plugin-purgecss';\n\nexport default defineConfig({\n  plugins: [\n    inject({\n      $: 'jquery',\n      jQuery: 'jquery',\n      'window.jQuery': 'jquery',\n    }),\n    htmlPurge(),\n  ],\n  css: {\n    devSourcemap: true,\n  },\n});\n```\n\n```text\nimport './app.scss';\nimport 'owl.carousel/dist/assets/owl.carousel.css';\nimport $ from 'jquery';\nimport 'lazysizes';\nimport 'owl.carousel';\n\n$(function(){\n  $('.owl-carousel').owlCarousel({});\n});\n```\n\n========================================\n\nComments:\n- stackoverflow.com/questions/28070885/&hellip;\n- @MuhammadMahfuzurRahman It's not my problem here. It's working in dev mode but stops after the build","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":169,"estimatedTokens":916}}373{"id":"stack-77002714","source":"stackoverflow","questionId":77002714,"title":"React + vite don't recognize and not load file css","tags":["reactjs","vite"],"text":"Title: React + vite don't recognize and not load file css\nTags: reactjs, vite\nSource: Stack Overflow\n\nQuestion:\nI have a problem with my react-vite project.\nVite doesn't recognize my style.css file\n\nThis is my configuration file.\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n})\n```\n\nSomebody can help me?\n\n========================================\n\nTop Answer:\nI had a similar issue, Vite v5.4.14 was loading old css file and any change to the stylesheet was causing all classes being removed from DOM. Updating config to:\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n css:{\n modules:{\n localsConvention:\"camelCase\",\n generateScopedName:\"[local]_[hash:base64:2]\"\n }\n\n }\n\n})\n```\n\nworked for me as well, thanks!\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n})\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  css:{\n    modules:{\n      localsConvention:\"camelCase\",\n      generateScopedName:\"[local]_[hash:base64:2]\"\n    }\n\n  }\n\n})\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  css:{\n    modules:{\n      localsConvention:\"camelCase\",\n      generateScopedName:\"[local]_[hash:base64:2]\"\n    }\n\n  }\n\n})\n```\n\n========================================\n\nComments:\n- Did you import your css in your component?","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":100,"estimatedTokens":471}}374{"id":"stack-72772752","source":"stackoverflow","questionId":72772752,"title":"Importing tensorflow in vite","tags":["javascript","typescript","tensorflow","npm","vite"],"text":"Title: Importing tensorflow in vite\nTags: javascript, typescript, tensorflow, npm, vite\nSource: Stack Overflow\n\nQuestion:\nApologies in advance as I'm sure these are rather trivial matters - I am in the \"hello world\" phase of learning front-end development.\n\nI have a hello-world vite app, which I created and ran simply via:\n\n```\nnpm init @vitejs/app\ncd hello-vite\nnpm install npm run dev\n```\n\nI'm able to view the outputted `localhost` url in my browser.\n\nI also have a simple script that imports tensorflow and does something with it:\n\n```\n$ cat test.mjs \nimport * as tf from '@tensorflow/tfjs-node'\n\nconst a = tf.tensor([[1, 2], [3, 4]]);\na.print();\n\n$ node test.mjs \n2022-06-27 22:04:16.968270: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 AVX512F FMA\nTo enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.\nTensor\n [[1, 2],\n [3, 4]]\n```\n\nNow I want to get this `test.mjs` behavior within my `hello-vite` app. So I tried something like:\n\n```\n$ cat main.ts \nimport './style.css'\nimport * as tf from '@tensorflow/tfjs-node'\n\nconst a = tf.tensor([[1, 2], [3, 4]]);\na.print();\n\ndocument.querySelector('#app').innerHTML = `\n \n\n### Hello Vite!!!\n\n Documentation\n`\n```\n\nBut when I run `npm run dev`, it doesn't seem happy, and spouts seemingly unrelated complaints about aws stuff:\n\n```\n$ npm run dev\n\n> hello-vite@0.0.0 dev\n> vite\n\n vite v2.9.12 dev server running at:\n\n > Local: http://localhost:3000/\n > Network: use `--host` to expose\n\n ready in 112ms.\n\n✘ [ERROR] Could not resolve \"mock-aws-s3\"\n\n node_modules/@mapbox/node-pre-gyp/lib/util/s3_setup.js:43:28:\n 43 │ const AWSMock = require('mock-aws-s3');\n ╵ ~~~~~~~~~~~~~\n\n You can mark the path \"mock-aws-s3\" as external to exclude it from the bundle, which will remove\n this error. You can also surround this \"require\" call with a try/catch block to handle this\n failure at run-time instead of bundle-time.\n\n✘ [ERROR] Could not resolve \"aws-sdk\"\n\n node_modules/@mapbox/node-pre-gyp/lib/util/s3_setup.js:76:22:\n 76 │ const AWS = require('aws-sdk');\n ╵ ~~~~~~~~~\n\n You can mark the path \"aws-sdk\" as external to exclude it from the bundle, which will remove this\n error. You can also surround this \"require\" call with a try/catch block to handle this failure at\n run-time instead of bundle-time.\n\n✘ [ERROR] Could not resolve \"nock\"\n\n node_modules/@mapbox/node-pre-gyp/lib/util/s3_setup.js:112:23:\n 112 │ const nock = require('nock');\n ╵ ~~~~~~\n\n You can mark the path \"nock\" as external to exclude it from the bundle, which will remove this\n error. You can also surround this \"require\" call with a try/catch block to handle this failure at\n run-time instead of bundle-time.\n\n10:06:42 PM [vite] error while updating dependencies:\nError: Build failed with 3 errors:\nnode_modules/@mapbox/node-pre-gyp/lib/util/s3_setup.js:43:28: ERROR: Could not resolve \"mock-aws-s3\"\nnode_modules/@mapbox/node-pre-gyp/lib/util/s3_setup.js:76:22: ERROR: Could not resolve \"aws-sdk\"\nnode_modules/@mapbox/node-pre-gyp/lib/util/s3_setup.js:112:23: ERROR: Could not resolve \"nock\"\n at failureErrorWithLog (/home/dshin/vite_scratch/hello-vite/node_modules/esbuild/lib/main.js:1605:15)\n at /home/dshin/vite_scratch/hello-vite/node_modules/esbuild/lib/main.js:1251:28\n at runOnEndCallbacks (/home/dshin/vite_scratch/hello-vite/node_modules/esbuild/lib/main.js:1034:63)\n at buildResponseToResult (/home/dshin/vite_scratch/hello-vite/node_modules/esbuild/lib/main.js:1249:7)\n at /home/dshin/vite_scratch/hello-vite/node_modules/esbuild/lib/main.js:1358:14\n at /home/dshin/vite_scratch/hello-vite/node_modules/esbuild/lib/main.js:666:9\n at handleIncomingPacket (/home/dshin/vite_scratch/hello-vite/node_modules/esbuild/lib/main.js:763:9) \n at Socket.readFromStdout (/home/dshin/vite_scratch/hello-vite/node_modules/esbuild/lib/main.js:632:7)\n at Socket.emit (events.js:314:20)\n at addChunk (_stream_readable.js:297:12)\nVite Error, /node_modules/.vite/deps/@tensorflow_tfjs-node.js?v=0ea0383e optimized info should be defined\n```\n\nIf I comment out the `print()` call and the line before it, the errors disappear.\n\nWhat am I doing wrong? How do I make sense of these errors?\n\n========================================\n\nCode:\n```text\nnpm init @vitejs/app\ncd hello-vite\nnpm install npm run dev\n```\n\n```text\n$ cat test.mjs \nimport * as tf from '@tensorflow/tfjs-node'\n\nconst a = tf.tensor([[1, 2], [3, 4]]);\na.print();\n\n$ node test.mjs \n2022-06-27 22:04:16.968270: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 AVX512F FMA\nTo enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.\nTensor\n    [[1, 2],\n     [3, 4]]\n```\n\n```text\n$ cat main.ts \nimport './style.css'\nimport * as tf from '@tensorflow/tfjs-node'\n\nconst a = tf.tensor([[1, 2], [3, 4]]);\na.print();\n\ndocument.querySelector('#app').innerHTML = `\n  <h1>Hello Vite!!!</h1>\n  <a href=\"https://vitejs.dev/guide/features.html\" target=\"_blank\">Documentation</a>\n`\n```\n\n```text\n$ npm run dev\n\n> hello-vite@0.0.0 dev\n> vite\n\n\n  vite v2.9.12 dev server running at:\n\n  > Local: http://localhost:3000/\n  > Network: use `--host` to expose\n\n  ready in 112ms.\n\n✘ [ERROR] Could not resolve \"mock-aws-s3\"\n\n    node_modules/@mapbox/node-pre-gyp/lib/util/s3_setup.js:43:28:\n      43 │     const AWSMock = require('mock-aws-s3');\n         ╵                             ~~~~~~~~~~~~~\n\n  You can mark the path \"mock-aws-s3\" as external to exclude it from the bundle, which will remove\n  this error. You can also surround this \"require\" call with a try/catch block to handle this\n  failure at run-time instead of bundle-time.\n\n✘ [ERROR] Could not resolve \"aws-sdk\"\n\n    node_modules/@mapbox/node-pre-gyp/lib/util/s3_setup.js:76:22:\n      76 │   const AWS = require('aws-sdk');\n         ╵                       ~~~~~~~~~\n\n  You can mark the path \"aws-sdk\" as external to exclude it from the bundle, which will remove this\n  error. You can also surround this \"require\" call with a try/catch block to handle this failure at\n  run-time instead of bundle-time.\n\n✘ [ERROR] Could not resolve \"nock\"\n\n    node_modules/@mapbox/node-pre-gyp/lib/util/s3_setup.js:112:23:\n      112 │   const nock = require('nock');\n          ╵                        ~~~~~~\n\n  You can mark the path \"nock\" as external to exclude it from the bundle, which will remove this\n  error. You can also surround this \"require\" call with a try/catch block to handle this failure at\n  run-time instead of bundle-time.\n\n10:06:42 PM [vite] error while updating dependencies:\nError: Build failed with 3 errors:\nnode_modules/@mapbox/node-pre-gyp/lib/util/s3_setup.js:43:28: ERROR: Could not resolve \"mock-aws-s3\"\nnode_modules/@mapbox/node-pre-gyp/lib/util/s3_setup.js:76:22: ERROR: Could not resolve \"aws-sdk\"\nnode_modules/@mapbox/node-pre-gyp/lib/util/s3_setup.js:112:23: ERROR: Could not resolve \"nock\"\n    at failureErrorWithLog (/home/dshin/vite_scratch/hello-vite/node_modules/esbuild/lib/main.js:1605:15)\n    at /home/dshin/vite_scratch/hello-vite/node_modules/esbuild/lib/main.js:1251:28\n    at runOnEndCallbacks (/home/dshin/vite_scratch/hello-vite/node_modules/esbuild/lib/main.js:1034:63)\n    at buildResponseToResult (/home/dshin/vite_scratch/hello-vite/node_modules/esbuild/lib/main.js:1249:7)\n    at /home/dshin/vite_scratch/hello-vite/node_modules/esbuild/lib/main.js:1358:14\n    at /home/dshin/vite_scratch/hello-vite/node_modules/esbuild/lib/main.js:666:9\n    at handleIncomingPacket (/home/dshin/vite_scratch/hello-vite/node_modules/esbuild/lib/main.js:763:9) \n    at Socket.readFromStdout (/home/dshin/vite_scratch/hello-vite/node_modules/esbuild/lib/main.js:632:7)\n    at Socket.emit (events.js:314:20)\n    at addChunk (_stream_readable.js:297:12)\nVite Error, /node_modules/.vite/deps/@tensorflow_tfjs-node.js?v=0ea0383e optimized info should be defined\n```\n\n```text\nlocalhost\n```\n\n```text\ntest.mjs\n```\n\n```text\nhello-vite\n```\n\n```text\nnpm run dev\n```\n\n```text\nprint()\n```\n\n```text\nnode-pre-gyp\n```\n\n```text\nnpm install mock-aws-s3\n```\n\n========================================\n\nComments:\n- Thanks, it was as simple as replacing `@tensorflow&#47;tfjs-node` with `@tensorflow&#47;tfjs`. It would still be nice to understand the stack trace, but simply understanding that npm packages can be node-only (or browser-only) is quite helpful. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":252,"estimatedTokens":2147}}375{"id":"stack-70634999","source":"stackoverflow","questionId":70634999,"title":"Using VITE + Vue3 - [Vue warn]: Component is missing template or render function","tags":["vue.js","templates","render","vite"],"text":"Title: Using VITE + Vue3 - [Vue warn]: Component is missing template or render function\nTags: vue.js, templates, render, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use VueThreeSixty ( https://github.com/rajeevgade/vue-360 ) component in my Vue3 + Vite project.\n\nI imported everything, added VueThreeSixty to my components object, but it looks like I'm still missing something, can u help me figure out what?\n\n```\n[Vue warn]: Component is missing template or render function.\n```\n\nHere's my code.\n\n```\n\n \n \n\n \n \n \n \n \n \n Sound\n \n \n\n \n import Navigation from \"../components/Navigation.vue\";\n import Footer from \"../components/Footer.vue\";\n import VueThreeSixty from 'vue-360'\n\n import \"vue-360/dist/css/style.css\";\n\n export default {\n data() {},\n components: {\n Navigation,\n Footer,\n VueThreeSixty\n },\n };\n \n```\n\nmain.js\n\n```\nimport { createApp } from 'vue'\n import Home from './views/Home.vue'\n import Navigation from './components/Navigation.vue'\n import Footer from './components/Footer.vue'\n import App from './App.vue'\n import VueThreeSixty from 'vue-360'\n\n import 'vue-360/dist/css/style.css'\n\n import './main.css'\n import './typo.css'\n \n createApp(App)\n .use(VueThreeSixty)\n .mount('#app')\n```\n\n========================================\n\nCode:\n```text\n[Vue warn]: Component is missing template or render function.\n```\n\n```html\n<template>\n    <Navigation></Navigation>\n    <div class=\"tb_header\">\n\n    </div>\n    <div class=\"container\">\n        <div class=\"row\">\n            <div class=\"w-2/5\">\n                <VueThreeSixty\n                    :amount=\"36\"\n                    imagePath=\"https://scaleflex.cloudimg.io/width/600/q35/https://scaleflex.ultrafast.io/https://scaleflex.airstore.io/demo/chair-360-36\"\n                    fileName=\"chair_{index}.jpg?v1\"\n                />\n            </div>\n            <div class=\"w-3/5\">Sound</div>\n        </div>\n    </div> <template>\n\n     <script>\n     import Navigation from \"../components/Navigation.vue\";\n     import Footer from \"../components/Footer.vue\";\n     import VueThreeSixty from 'vue-360'\n\n     import \"vue-360/dist/css/style.css\";\n\n     export default {\n     data() {},\n     components: {\n        Navigation,\n        Footer,\n        VueThreeSixty\n    },\n    };\n    </script>\n```\n\n```js\nimport { createApp } from 'vue'\n    import Home from './views/Home.vue'\n    import Navigation from './components/Navigation.vue'\n    import Footer from './components/Footer.vue'\n    import App from './App.vue'\n    import VueThreeSixty from 'vue-360'\n\n    import 'vue-360/dist/css/style.css'\n\n    import './main.css'\n    import './typo.css'\n    \n    createApp(App)\n    .use(VueThreeSixty)\n    .mount('#app')\n```\n\n```text\nvue-three-sixty\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":133,"estimatedTokens":676}}376{"id":"stack-68032254","source":"stackoverflow","questionId":68032254,"title":"How to stop Tailwind CSS from purging the classes in local development environment?","tags":["vue.js","tailwind-css","vite"],"text":"Title: How to stop Tailwind CSS from purging the classes in local development environment?\nTags: vue.js, tailwind-css, vite\nSource: Stack Overflow\n\nQuestion:\nI am `vite.js` build tool, `vue.js` and `tailwindcss: ^2.1.4`\n\nEverything was working normal before but now I am not sure what I did, purge is not working as expected. Tailwind class started purging even in my development environment. It was suppose to purge only when I build project for production.\n\nSay that I applied `mb-10 pt-10` to div, to see this in effect, I need to do one of two things:\n\n- Restart vite.js, Or\n\n- In css file define: `.cust-class { @apply mb-10 pt-10 }` then `mb-10 pt-10` classes will work (together or individually)\n\nHere is my `tailwind.config.js`\n\n```\nmodule.exports = {\n purge: ['./index.html', './src/**/*.{vue,js}'],\n darkMode: false, // or 'media' or 'class'\n theme: {\n colors: {\n transparent: 'transparent',\n current: 'currentColor',\n black: '#000',\n white: '#fff',\n },\n extend: {},\n },\n variants: {\n extend: {\n backgroundColor: ['active'],\n },\n },\n plugins: [],\n};\n```\n\nI never had issue with same configuration in other projects.\n\nThanks for your help.\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n  purge: ['./index.html', './src/**/*.{vue,js}'],\n  darkMode: false, // or 'media' or 'class'\n  theme: {\n    colors: {\n      transparent: 'transparent',\n      current: 'currentColor',\n      black: '#000',\n      white: '#fff',\n    },\n    extend: {},\n  },\n  variants: {\n    extend: {\n      backgroundColor: ['active'],\n    },\n  },\n  plugins: [],\n};\n```\n\n```text\nvite.js\n```\n\n```text\nvue.js\n```\n\n```text\ntailwindcss: ^2.1.4\n```\n\n```text\nmb-10 pt-10\n```\n\n```text\n.cust-class { @apply mb-10 pt-10 }\n```\n\n```text\nmb-10 pt-10\n```\n\n```text\ntailwind.config.js\n```\n\n```text\nNODE_ENV=production\n```\n\n```text\nNODE_ENV=development\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":103,"estimatedTokens":462}}377{"id":"stack-70420749","source":"stackoverflow","questionId":70420749,"title":"Storybook with Vite error: fn.apply is not a function","tags":["reactjs","storybook","vite"],"text":"Title: Storybook with Vite error: fn.apply is not a function\nTags: reactjs, storybook, vite\nSource: Stack Overflow\n\nQuestion:\nI'm refactoring a React webapp from CRA to using Vite and having issues with Storybook. The storybook's GUI opens, and I see a list of stories on the left panel. But whichever story I choose I get an error `TypeError: fn.apply is not a function` in Canvas tab like shown here:\nhttps://i.sstatic.net/CGXvG.png\n\nI found a similar issue on Storybook's GitHub, and tried to change names `StorybookName` to `storybookName` in all the stories, also checked all the React components in the stories to make sure all of them are correctly defined as functions.\n\nWhen it was using CRA storybook worked fine, but with Vite it's not working. Maybe I'm missing some configuration for Vite, so here's my `vite.config.js` as well:\n\n```\nimport react from '@vitejs/plugin-react';\nimport { defineConfig } from 'vite';\nimport svgrPlugin from 'vite-plugin-svgr';\n\nconst path = require('path');\n\nexport default defineConfig({\n esbuild: {\n jsxFactory: 'jsx',\n jsxInject: `import { jsx } from '@emotion/react'`,\n },\n optimizeDeps: {\n include: ['@emotion/react'],\n },\n plugins: [\n react({\n jsxImportSource: '@emotion/react',\n babel: {\n plugins: ['@emotion/babel-plugin'],\n },\n }),\n svgrPlugin({\n svgrOptions: {\n icon: true,\n },\n }),\n ],\n});\n```\n\nAnd here's `main.js` from storybook:\n\n```\nconst path = require('path');\nconst svgrPlugin = require('vite-plugin-svgr');\n\nmodule.exports = {\n core: {\n builder: 'storybook-builder-vite',\n },\n stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],\n addons: ['@storybook/addon-links', '@storybook/addon-essentials'],\n viteFinal: (config) => {\n return {\n ...config,\n plugins: [\n ...config.plugins,\n svgrPlugin({\n svgrOptions: {\n icon: true,\n },\n }),\n ],\n };\n },\n};\n```\n\nIn Chrome Dev Tools I get this error:\nhttps://i.sstatic.net/pIobj.png\n\n========================================\n\nCode:\n```text\nimport react from '@vitejs/plugin-react';\nimport { defineConfig } from 'vite';\nimport svgrPlugin from 'vite-plugin-svgr';\n\nconst path = require('path');\n\nexport default defineConfig({\n  esbuild: {\n    jsxFactory: 'jsx',\n    jsxInject: `import { jsx } from '@emotion/react'`,\n  },\n  optimizeDeps: {\n    include: ['@emotion/react'],\n  },\n  plugins: [\n    react({\n      jsxImportSource: '@emotion/react',\n      babel: {\n        plugins: ['@emotion/babel-plugin'],\n      },\n    }),\n    svgrPlugin({\n      svgrOptions: {\n        icon: true,\n      },\n    }),\n  ],\n});\n```\n\n```text\nconst path = require('path');\nconst svgrPlugin = require('vite-plugin-svgr');\n\nmodule.exports = {\n  core: {\n    builder: 'storybook-builder-vite',\n  },\n  stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],\n  addons: ['@storybook/addon-links', '@storybook/addon-essentials'],\n  viteFinal: (config) => {\n    return {\n      ...config,\n      plugins: [\n        ...config.plugins,\n        svgrPlugin({\n          svgrOptions: {\n            icon: true,\n          },\n        }),\n      ],\n    };\n  },\n};\n```\n\n```text\nTypeError: fn.apply is not a function\n```\n\n```text\nStorybookName\n```\n\n```text\nstorybookName\n```\n\n```text\nvite.config.js\n```\n\n```text\nmain.js\n```\n\n```text\nundefined\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":157,"estimatedTokens":810}}378{"id":"stack-77149709","source":"stackoverflow","questionId":77149709,"title":"How to preserve a database connection pool in hooks.server.js during hot reload in SvelteKit with Vite.js and mariadb?","tags":["javascript","node.js","vite","sveltekit"],"text":"Title: How to preserve a database connection pool in hooks.server.js during hot reload in SvelteKit with Vite.js and mariadb?\nTags: javascript, node.js, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am using SvelteKit, Vite.js, and the `mariadb` package with Node.js in my application. I have the following code in the `db.js` file:\n\n```\nimport mariadb from 'mariadb';\n\nconst databaseConnectionPoolConfig = {\n ...\n};\n\nlet databaseConnectionPool = undefined;\n\nexport function createDatabaseConnectionPool() {\n return databaseConnectionPool ??= mariadb.createPool(databaseConnectionPoolConfig);\n}\n```\n\nInside the `hooks.server.js` file, I have the following code:\n\n```\nimport { createDatabaseConnectionPool } from '$lib/db';\n\ncreateDatabaseConnectionPool();\n```\n\nWhen a hot reload is performed, the `databaseConnectionPool` is reset to undefined, but the connections in the pool are not closed, and new ones are created. I checked this by running the following query:\n\n```\nSHOW STATUS LIKE 'Threads_connected';\n```\n\nWhich increases each time a hot reload is performed by the number of connections specified by the `databaseConnectionPoolConfig.connectionLimit` property.\n\nHow can I prevent this from happening?\n\n========================================\n\nCode:\n```js\nimport mariadb from 'mariadb';\n\nconst databaseConnectionPoolConfig = {\n  ...\n};\n\nlet databaseConnectionPool = undefined;\n\nexport function createDatabaseConnectionPool() {\n  return databaseConnectionPool ??= mariadb.createPool(databaseConnectionPoolConfig);\n}\n```\n\n```js\nimport { createDatabaseConnectionPool } from '$lib/db';\n\ncreateDatabaseConnectionPool();\n```\n\n```sql\nSHOW STATUS LIKE 'Threads_connected';\n```\n\n```text\nmariadb\n```\n\n```text\ndb.js\n```\n\n```text\nhooks.server.js\n```\n\n```text\ndatabaseConnectionPool\n```\n\n```text\ndatabaseConnectionPoolConfig.connectionLimit\n```\n\n```js\n// hooks.server.js\n\nglobalThis.databaseConnectionPool ??= mariadb.createPool(databaseConnectionPoolConfig);\n```\n\n```text\nglobalThis\n```\n\n```text\nglobalThis\n```\n\n========================================\n\nComments:\n- Do you mean `globalThis`? Global is legacy. See my updated answer below.\n- @VonC Thanks for pointing that out. I have updated my code accordingly.","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":105,"estimatedTokens":554}}379{"id":"stack-72857855","source":"stackoverflow","questionId":72857855,"title":"Vue 3 vite ignore errors during build","tags":["typescript","vue.js","npm","eslint","vite"],"text":"Title: Vue 3 vite ignore errors during build\nTags: typescript, vue.js, npm, eslint, vite\nSource: Stack Overflow\n\nQuestion:\nI am getting the error \"TS2322: Type 'number' is not assignable to type 'string'.\"\n\nI wanted to just disable this rather than fix it in the code.\nI am using \"vue-tsc --noEmit && vite build\" for my build in package.json\n\nCurrently running vue 3 / vite with latest in a Dockerfile.\n\n========================================\n\nTop Answer:\nIf you're unable to fix the code for some reason, you could suppress the error with a preceding comment, containing `@ts-expect-error`:\n\n```\n// @ts-expect-error\nconst s: string = 123\n```\n\nOr `@ts-ignore`:\n\n```\n// @ts-ignore\nconst s: string = 123\n```\n\nFrom `@ts-ignore` or `@ts-expect-error`?:\n\nPick `ts-expect-error` if:\n\n- you’re writing test code where you actually want the type system to error on an operation\n\n- you expect a fix to be coming in fairly quickly and you just need a quick workaround\n\n- you’re in a reasonably-sized project with a proactive team that wants to remove suppression comments as soon affected code is valid again\n\nPick `ts-ignore` if:\n\n- you have a larger project and new errors have appeared in code with no clear owner\n\n- you are in the middle of an upgrade between two different versions of TypeScript, and a line of code errors in one version but not another.\n\n- you honestly don’t have the time to decide which of these options is better.\n\ndemo\n\n========================================\n\nCode:\n```js\n// @ts-expect-error\nconst s: string = 123\n```\n\n```js\n// @ts-ignore\nconst s: string = 123\n```\n\n```text\n@ts-expect-error\n```\n\n```text\n@ts-ignore\n```\n\n```text\n@ts-ignore\n```\n\n```text\n@ts-expect-error\n```\n\n```text\nts-expect-error\n```\n\n```text\nts-ignore\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":85,"estimatedTokens":437}}380{"id":"stack-68807596","source":"stackoverflow","questionId":68807596,"title":"How to resolve Vue 3 custom renderer error","tags":["javascript","vue.js","vuejs3","custom-renderer","vite"],"text":"Title: How to resolve Vue 3 custom renderer error\nTags: javascript, vue.js, vuejs3, custom-renderer, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to build a custom renderer using Vue 3 and Vite. The renderer is working in its original repo (clone that repo, `npm install`, and `npm run dev`), but failing when I publish that renderer and install on another project.\n\nTo recreate, either:\n\n- Clone, install, and run this repo, or\n\n- Create a Vue 3 project, npm install `mvp-renderer`, and import `{ createApp }` from `mvp-renderer` instead of `vue`.\n\nThe working custom renderer adds the class `custom-renderer` to every DOM element; in the broken version, nothing renders to the DOM and I see the following error when the `mount` function is called:\n\n```\n[Vue warn]: resolveComponent can only be used in render() or setup().\n```\n\nAny thoughts on how to fix?\n\n========================================\n\nCode:\n```text\n[Vue warn]: resolveComponent can only be used in render() or setup().\n```\n\n```text\nnpm install\n```\n\n```text\nnpm run dev\n```\n\n```text\nmvp-renderer\n```\n\n```text\n{ createApp }\n```\n\n```text\nmvp-renderer\n```\n\n```text\nvue\n```\n\n```text\ncustom-renderer\n```\n\n```text\nmount\n```\n\n```text\nbuild:renderer\n```\n\n```text\nnpm install mvp-renderer@latest\n```\n\n```text\nnpm run dev\n```\n\n========================================\n\nComments:\n- I spent to much time on this, without any luck... But I think the mvp-renderer uses some builtin code of Vue (like ensureRenderer()) and probably there will be 2 Vue renderers active at the same time while in DEV mode. Maybe the Vite Vue plugin adds a Vue renderer. The problem with this setup is that the internal Vue variable 'currentRenderingInstance' is null somehow and this could probably mean the 'createApp' function is missing some critical functionality.\n- @FerryKranenburg Thanks for checking it out! That definitely gives me a bit more to go on - I ran into a similar question here but wasn't sure where to start to find that duplicate instance. I'll dig more into it and see what I can find.","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":77,"estimatedTokens":512}}381{"id":"stack-75635346","source":"stackoverflow","questionId":75635346,"title":"How to do a reactjs horizontal scroll webpage","tags":["reactjs","tailwind-css","vite"],"text":"Title: How to do a reactjs horizontal scroll webpage\nTags: reactjs, tailwind-css, vite\nSource: Stack Overflow\n\nQuestion:\nI’m building a React.js Webpage, built with Vite and using Tailwind.\nI want the page to scroll horizontal. I’ve tried some react libraries like `npm react-horizontal-scroll` and others but nothing works and I don't know how to do it.\n\nI want the page to scrolls everything horizontal with the mouse wheel and with a scrolling bar, except the header and the footer that will be static.\n\n========================================\n\nTop Answer:\nYou can make custom hook for site components needs horizontal scroll. Use useRef hook (or createRef in class-based components):\n\n```\nconst useHorizontalScroll = () => {\n const scrollRef = useRef();\n\n const onWheel = (e) => {\n if (e.deltaY === 0) return;\n e.preventDefault();\n scrollRef.current.scrollTo({\n left: scrollRef.current.scrollLeft + e.deltaY,\n behavior: 'smooth',\n });\n };\n\n useEffect(() => {\n // Store the ref value to unsubscribe from event during componentWillUnmount\n let refValueHolder = null;\n if (scrollRef) {\n refValueHolder = scrollRef.current;\n refValueHolder.addEventListener('wheel', onWheel);\n }\n return () => {\n refValueHolder.removeEventListener('wheel', onWheel);\n };\n }, []);\n\n return scrollRef;\n};\n```\n\n...and add it in the app:\n\n```\nconst App:FC = () => {\n const scrollRef = useHorizontalScroll();\n ...\n return (\n \n \n ...\n \n \n );\n};\n```\n\n========================================\n\nCode:\n```text\nnpm react-horizontal-scroll\n```\n\n```text\n.container {\n  display: flex;\n  flex-wrap: nowrap;\n  overflow-x: scroll;\n}\n```\n\n```text\n.item {\n  width: 100vw;\n}\n```\n\n```text\nimport React from 'react';\n\nfunction App() {\n  const handleScroll = (event) => {\n    const container = event.target;\n    const scrollAmount = event.deltaY;\n    container.scrollTo({\n      top: 0,\n      left: container.scrollLeft + scrollAmount,\n      behavior: 'smooth'\n    });\n  };\n\n  return (\n    <div>\n      <header>\n        {/* Header content */}\n      </header>\n      <div className=\"container\" onWheel={handleScroll}>\n        <div className=\"item\">\n          {/* Item content */}\n        </div>\n        <div className=\"item\">\n          {/* Item content */}\n        </div>\n        <div className=\"item\">\n          {/* Item content */}\n        </div>\n      </div>\n      <footer>\n        {/* Footer content */}\n      </footer>\n    </div>\n  );\n}\n```\n\n```text\n.container::-webkit-scrollbar {\n  height: 8px;\n}\n\n.container::-webkit-scrollbar-thumb {\n  background-color: gray;\n  border-radius: 10px;\n}\n\n.container::-webkit-scrollbar-track {\n  background-color: white;\n  border-radius: 10px;\n}\n```\n\n```text\nconst useHorizontalScroll = () => {\n  const scrollRef = useRef();\n\n  const onWheel = (e) => {\n    if (e.deltaY === 0) return;\n    e.preventDefault();\n    scrollRef.current.scrollTo({\n    left: scrollRef.current.scrollLeft + e.deltaY,\n    behavior: 'smooth',\n    });\n  };\n\n  useEffect(() => {\n  // Store the ref value to unsubscribe from event during componentWillUnmount\n    let refValueHolder = null;\n    if (scrollRef) {\n      refValueHolder = scrollRef.current;\n      refValueHolder.addEventListener('wheel', onWheel);\n    }\n    return () => {\n    refValueHolder.removeEventListener('wheel', onWheel);\n    };\n  }, []);\n\n  return scrollRef;\n};\n```\n\n```text\nconst App:FC = () => {\n  const scrollRef = useHorizontalScroll();\n  ...\n  return (\n    <Header />\n    <Body ref={scrollRef}>\n      ...\n    </Body>\n    <Footer />\n  );\n};\n```\n\n========================================\n\nComments:\n- Hi! Thanks for the answer, everything is working except the function to scroll with the mouse, i'm trying to rewrite the function and lets see if this works.\n- event.target.parentElement for this case but this solution still make vertical scroll.","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":183,"estimatedTokens":948}}382{"id":"stack-71164127","source":"stackoverflow","questionId":71164127,"title":"Vue3 webcomponents production build problem","tags":["vue.js","vuejs2","vuejs3","vue-cli","vite"],"text":"Title: Vue3 webcomponents production build problem\nTags: vue.js, vuejs2, vuejs3, vue-cli, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to migrate my vue2 webcomponent to vue3, although the problem comes when i'm creating a build for production.\n\nI was using the vue-cli with `--target wc` which now displays an error stating that vue3 webcomponent support is still under development.\n\nRemoving the `--target` option my build files are way different, i was relying on the .min files that without this option are not builded.\n\nWhat alternative I have? Does vite provide the same build outputs that previously vue-cli gave with vue2?\n\n========================================\n\nCode:\n```text\n--target wc\n```\n\n```text\n--target\n```\n\n```js\nif (vueMajor === 3) {\n    abort(`Vue 3 support of the web component target is still under development.`)\n  }\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":29,"estimatedTokens":213}}383{"id":"stack-71633327","source":"stackoverflow","questionId":71633327,"title":"Referencing TailwindCSS config from JavaScript in SvelteKit","tags":["javascript","tailwind-css","vite","sveltekit"],"text":"Title: Referencing TailwindCSS config from JavaScript in SvelteKit\nTags: javascript, tailwind-css, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm using SvelteKit, which uses Vite and the setup instructions calls for CommonJS config files:\nhttps://tailwindcss.com/docs/guides/sveltekit\n\nHowever, the guide for referencing the configuration in JavaScript requires ESM.\nhttps://tailwindcss.com/docs/configuration#referencing-in-java-script\n\nAttempting to change the `tailwind.config.cjs` to ESM doesn't work (I get errors from other libraries trying to `require()` it as CJS).\n\nDoes anyone know how I can either get a working ESM `tailwind.config.js` in SvelteKit or a different better method to reference the tailwind config?\n\n========================================\n\nTop Answer:\nSince tailwind v3.3 you can write your config file using ESM or Typescript.\n\n```\nnpx tailwindcss init --esm\n```\n\n```\nnpx tailwindcss init --ts\n```\n\nI converted my config into ts, then I did\n\n```\nimport tailwindConfig from '../../tailwind.config'; // Change path accordingly\nimport resolveConfig from 'tailwindcss/resolveConfig'\nconst fullConfig = resolveConfig(tailwindConfig)\n```\n\nSource example from the docs\n\n========================================\n\nCode:\n```text\ntailwind.config.cjs\n```\n\n```text\nrequire()\n```\n\n```text\ntailwind.config.js\n```\n\n```text\n.json\n```\n\n```text\njson\n```\n\n```text\nnpx tailwindcss init --esm\n```\n\n```text\nnpx tailwindcss init --ts\n```\n\n```text\nimport tailwindConfig from '../../tailwind.config'; // Change path accordingly\nimport resolveConfig from 'tailwindcss/resolveConfig'\nconst fullConfig = resolveConfig(tailwindConfig)\n```\n\n========================================\n\nComments:\n- I'm wanting the same. the maintainer of `svelte-add` will be implementing it soon hopefully. i think cjs was used because of postcss not handling esm..but they recently added it github.com/svelte-add/svelte-add/issues/209","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":79,"estimatedTokens":480}}384{"id":"stack-69938184","source":"stackoverflow","questionId":69938184,"title":"Npm not running in terminal vite","tags":["javascript","node.js","npm","server","vite"],"text":"Title: Npm not running in terminal vite\nTags: javascript, node.js, npm, server, vite\nSource: Stack Overflow\n\nQuestion:\nWhat I typed:\n\n```\nnpm run dev\n```\n\n**Error**:\n\n```\nnpm ERR! Missing script: \"dev\"\nnpm ERR!\nnpm ERR! To see a list of scripts, run:\nnpm ERR! npm run\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! C:\\Users\\andre\\AppData\\Local\\npm-cache\\_logs\\2021-11-12T04_58_51_898Z-debug.log\n```\n\n**Json:**\n\n```\n{\n \"name\": \"port\",\n \"version\": \"0.0.0\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"serve\": \"vite preview\"\n },\n \"devDependencies\": {\n \"vite\": \"^2.6.4\"\n },\n \"dependencies\": {\n \"three\": \"^0.134.0\"\n }\n}\n```\n\n========================================\n\nCode:\n```text\nnpm run dev\n```\n\n```bash\nnpm ERR! Missing script: \"dev\"\nnpm ERR!\nnpm ERR! To see a list of scripts, run:\nnpm ERR!   npm run\nnpm ERR! A complete log of this run can be found in:\nnpm ERR!  C:\\Users\\andre\\AppData\\Local\\npm-cache\\_logs\\2021-11-12T04_58_51_898Z-debug.log\n```\n\n```json\n{\n  \"name\": \"port\",\n  \"version\": \"0.0.0\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"serve\": \"vite preview\"\n  },\n  \"devDependencies\": {\n    \"vite\": \"^2.6.4\"\n  },\n  \"dependencies\": {\n    \"three\": \"^0.134.0\"\n  }\n}\n```\n\n```text\ncd your-project-name\n```\n\n```text\nnpm run dev\n```\n\n========================================\n\nComments:\n- Can you a link to a reproduction?","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":88,"estimatedTokens":343}}385{"id":"stack-79432568","source":"stackoverflow","questionId":79432568,"title":"ESLint Not Working Properly in Vite + React + TypeScript","tags":["reactjs","visual-studio-code","vite","eslint","prettier"],"text":"Title: ESLint Not Working Properly in Vite + React + TypeScript\nTags: reactjs, visual-studio-code, vite, eslint, prettier\nSource: Stack Overflow\n\nQuestion:\nI'm working on a Vite + React + TypeScript project and using ESLint with the following configuration:\n\n**Relevant ESLint Config** (.eslintrc.json)\n\n```\n{\n \"extends\": [\n \"eslint:recommended\",\n \"airbnb/hooks\",\n \"airbnb-typescript\",\n \"plugin:react/recommended\",\n \"plugin:@typescript-eslint/recommended\",\n \"plugin:prettier/recommended\"\n ],\n \"parserOptions\": {\n \"project\": \"./tsconfig.json\"\n },\n \"rules\": {\n \"react-hooks/exhaustive-deps\": \"off\",\n \"@typescript-eslint/no-explicit-any\": \"off\",\n \"import/order\": [\n \"error\",\n {\n \"groups\": [[\"external\", \"builtin\"], \"internal\", \"parent\", \"sibling\", \"index\"],\n \"alphabetize\": { \"order\": \"asc\", \"caseInsensitive\": true }\n }\n ]\n },\n \"settings\": {\n \"import/resolver\": {\n \"typescript\": { \"project\": \"./tsconfig.json\" }\n }\n }\n}\n```\n\n### **Issue:**\n\nWhen I run ESLint (`eslint . --ext .ts,.tsx`), I get **no errors**, but some of my teammates (who are on Windows) see multiple linting errors.\n\n### **Environment Differences:**\n\n**Me:** macOS (No ESLint errors)\n\n**Teammates:** Windows (Seeing ESLint errors)\n\nCould this be an issue with **path resolution, line endings (`LF` vs. `CRLF`), or case sensitivity**? Any insights would be helpful!\n\n### **What I’ve Tried:**\n\nEnsured all teammates have the same `node_modules` and `eslint` version.\n\nDeleted `node_modules` and `package-lock.json`, then reinstalled (`npm install`).\n\nChecked global ESLint settings (disabled global ESLint).\n\nUsing **VS Code** with only ESLint and Prettier enabled.\n\nRunning ESLint manually (outside VS Code).\n\n========================================\n\nCode:\n```text\n{\n  \"extends\": [\n    \"eslint:recommended\",\n    \"airbnb/hooks\",\n    \"airbnb-typescript\",\n    \"plugin:react/recommended\",\n    \"plugin:@typescript-eslint/recommended\",\n    \"plugin:prettier/recommended\"\n  ],\n  \"parserOptions\": {\n    \"project\": \"./tsconfig.json\"\n  },\n  \"rules\": {\n    \"react-hooks/exhaustive-deps\": \"off\",\n    \"@typescript-eslint/no-explicit-any\": \"off\",\n    \"import/order\": [\n      \"error\",\n      {\n        \"groups\": [[\"external\", \"builtin\"], \"internal\", \"parent\", \"sibling\", \"index\"],\n        \"alphabetize\": { \"order\": \"asc\", \"caseInsensitive\": true }\n      }\n    ]\n  },\n  \"settings\": {\n    \"import/resolver\": {\n      \"typescript\": { \"project\": \"./tsconfig.json\" }\n    }\n  }\n}\n```\n\n```text\neslint . --ext .ts,.tsx\n```\n\n```text\nLF\n```\n\n```text\nCRLF\n```\n\n```text\nnode_modules\n```\n\n```text\neslint\n```\n\n```text\nnode_modules\n```\n\n```text\npackage-lock.json\n```\n\n```text\nnpm install\n```\n\n```text\n\"lint\": \"tsc --noEmit && eslint \\\"src/**/*.{ts,tsx}\\\" --cache --max-warnings=0\",\n```\n\n========================================\n\nComments:\n- What kind of linting errors do they see?","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":140,"estimatedTokens":704}}386{"id":"stack-75048603","source":"stackoverflow","questionId":75048603,"title":"Vue / Vite v3.2.5 - Invalid value \"umd\" for option \"output.format\"","tags":["vuejs2","vite"],"text":"Title: Vue / Vite v3.2.5 - Invalid value \"umd\" for option \"output.format\"\nTags: vuejs2, vite\nSource: Stack Overflow\n\nQuestion:\nI use Vue2 with Vite v3.2.5 and when I run npm run build I get this error: ***Invalid value \"umd\" for option \"output.format\" - UMD and IIFE output formats are not supported for code-splitting builds.***\n\nThat's my vite.config.js\n\n```\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\nimport vue from '@vitejs/plugin-vue2';\nconst path = require('path')\nimport { resolve } from 'path'\n\nexport default defineConfig({\n plugins: [\n laravel({\n hotFile: 'public/widget.hot',\n input: [\n 'resources/js/app.js',\n 'resources/scss/app.scss',\n 'resources/scss/index.scss'\n ],\n refresh: true,\n }),\n vue({\n template: {\n transformAssetUrls: {\n base: null,\n includeAbsolute: false,\n },\n },\n }),\n ],\n resolve: {\n alias: {\n vue: 'vue/dist/vue.esm.js',\n },\n dedupe: [\n 'vue'\n ]\n },\n alias: {\n '~bootstrap': path.resolve(__dirname, 'node_modules/bootstrap'),\n },\n build: {\n cssCodeSplit: true,\n lib: {\n input: {\n app: \"./resources/js/app.js\"\n },\n entry: resolve(__dirname, 'resources/js/app.js'),\n output: {\n path: path.resolve(__dirname, 'dist'),\n filename: 'bundle.js',\n },\n name: 'bundle',\n fileName: 'app'\n },\n rollupOptions: {\n external: ['vue'],\n output: {\n globals: {\n vue: 'Vue',\n },\n format: \"esm\",\n inlineDynamicImports: false,\n },\n },\n },\n});\n```\n\nDoes anyone know what's the problem here? My output.format value is \"esm\" and not \"umd\" ?!\nThanks for help!\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\nimport vue from '@vitejs/plugin-vue2';\nconst path = require('path')\nimport { resolve } from 'path'\n\nexport default defineConfig({\n    plugins: [\n        laravel({\n            hotFile: 'public/widget.hot',\n            input: [\n                'resources/js/app.js',\n                'resources/scss/app.scss',\n                'resources/scss/index.scss'\n            ],\n            refresh: true,\n        }),\n        vue({\n            template: {\n                transformAssetUrls: {\n                    base: null,\n                    includeAbsolute: false,\n                },\n            },\n        }),\n    ],\n    resolve: {\n        alias: {\n            vue: 'vue/dist/vue.esm.js',\n        },\n        dedupe: [\n            'vue'\n        ]\n    },\n    alias: {\n        '~bootstrap': path.resolve(__dirname, 'node_modules/bootstrap'),\n    },\n    build: {\n        cssCodeSplit: true,\n        lib: {\n            input: {\n                app: \"./resources/js/app.js\"\n            },\n            entry: resolve(__dirname, 'resources/js/app.js'),\n            output: {\n                path: path.resolve(__dirname, 'dist'),\n                filename: 'bundle.js',\n            },\n            name: 'bundle',\n            fileName: 'app'\n        },\n        rollupOptions: {\n            external: ['vue'],\n            output: {\n                globals: {\n                    vue: 'Vue',\n                },\n                format: \"esm\",\n                inlineDynamicImports: false,\n            },\n        },\n    },\n});\n```\n\n```text\nlib: {\n            input: {\n                app: \"./resources/js/app.js\"\n            },\n            formats: ['es'],\n            entry: resolve(__dirname, 'resources/js/app.js'),\n            output: {\n                path: path.resolve(__dirname, 'dist'),\n                filename: 'bundle.js',\n            },\n            name: 'bundle',\n            fileName: 'app'\n        },\n```\n\n```text\nlib\n```\n\n```text\nes\n```\n\n```text\numd\n```\n\n```text\nformats\n```\n\n```text\nbuild.lib\n```\n\n========================================\n\nComments:\n- Have you tried specifying `format: esm` inside the `build.lib.output` object?\n- Yes, but it's not working. Then I get the same error\n- Glad I could help! It'd be great if you could mark my answer as accepted :)","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":189,"estimatedTokens":975}}387{"id":"stack-71486252","source":"stackoverflow","questionId":71486252,"title":"Vitest integration with Quasar","tags":["vue.js","quasar-framework","vite","quasar","vitest"],"text":"Title: Vitest integration with Quasar\nTags: vue.js, quasar-framework, vite, quasar, vitest\nSource: Stack Overflow\n\nQuestion:\nI have been trying to integrate Vitest with a project that implements Quasar but I have not succeed doing so. The main problem that I am facing when testing is that quasar components are not rendering in HTML elements, so when I try to set a text on an element vitest does not identify it as an HTML element and I get the next error:\n\n```\nError: wrapper.setValue() cannot be called on Q-INPUT\n ❯ DOMWrapper.setValue node_modules/@vue/test-utils/dist/vue-test-utils.cjs.js:7417:19\n ❯ src/modules/Auth/LoginView.spec.ts:8:60\n 6| const wrapper = mount(LoginView)\n 7| test('should render correctly', async() => {\n 8| const inputEmail = await wrapper.get('[label=\"Email\"]').setValue('andres@correo.com')\n |\n```\n\nI tried a `console.log(wrapper.get('[label=\"Email\"]').html())` and I got the :\n\n```\n val &amp;&amp; val.length > 0 || \"El correo es obligatorio\",(val) => {\n const emailPattern = /^(?=[a-zA-Z0-9@._%+-]{6,254}$)[a-zA-Z0-9._%+-]{1,64}@(?:[a-zA-Z0-9-]{1,63}\\.){1,8}[a-zA-Z]{2,63}$/;\n return emailPattern.test(val) || \"No es un correo valido\";\n}\" data-v-5d16ad28=\"\">\n```\n\nAs you can see the element is not being \"transformed\" to an HTML tag. Is it possible an integration of quasar with vitest? If it is, could you please let me know how it should be ?\n\nTIA\n\n========================================\n\nCode:\n```text\nError: wrapper.setValue() cannot be called on Q-INPUT\n ❯ DOMWrapper.setValue node_modules/@vue/test-utils/dist/vue-test-utils.cjs.js:7417:19\n ❯ src/modules/Auth/LoginView.spec.ts:8:60\n      6|   const wrapper = mount(LoginView)\n      7|   test('should render correctly', async() => {\n      8|     const inputEmail = await wrapper.get('[label=\"Email\"]').setValue('andres@correo.com')\n       |\n```\n\n```text\n<q-input type=\"text\" filled=\"\" label=\"Email\" placeholder=\"correo@correo.com\" lazy-rules=\"\" modelvalue=\"\" rules=\"(val) => val &amp;&amp; val.length > 0 || &quot;El correo es obligatorio&quot;,(val) => {\n  const emailPattern = /^(?=[a-zA-Z0-9@._%+-]{6,254}$)[a-zA-Z0-9._%+-]{1,64}@(?:[a-zA-Z0-9-]{1,63}\\.){1,8}[a-zA-Z]{2,63}$/;\n  return emailPattern.test(val) || &quot;No es un correo valido&quot;;\n}\" data-v-5d16ad28=\"\"></q-input>\n```\n\n```text\nconsole.log(wrapper.get('[label=\"Email\"]').html())\n```\n\n```text\nimport { defineConfig } from 'vitest/config'\nimport vue from '@vitejs/plugin-vue'\nimport { quasar, transformAssetUrls } from '@quasar/vite-plugin'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  test: {\n    environment: 'jsdom'\n  },\n  plugins: [\n    vue({\n      template: { transformAssetUrls }\n    }),\n    quasar({\n      sassVariables: 'src/quasar-variables.sass'\n    })\n  ],\n})\n```\n\n```text\nimport { test, expect, describe } from 'vitest'\nimport { mount } from '@vue/test-utils'\nimport { Quasar } from 'quasar'\n\nimport HelloWorld from \"../components/HelloWorld.vue\"\n\nconst wrapperFactory = () => mount(HelloWorld, {\n  global: {\n    plugins: [Quasar]\n  },\n})\n\ntest('mount component', () => {\n  expect(HelloWorld).toBeTruthy();\n  const wrapper = wrapperFactory();\n\n  console.log(wrapper.html());\n})\n```\n\n========================================\n\nComments:\n- For me only importing `Quasar` and using it in global did the trick, no need to change vitest config file","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":100,"estimatedTokens":833}}388{"id":"stack-70998491","source":"stackoverflow","questionId":70998491,"title":"Why is '.vue' loader not found by Vite when using Vue 3 migration build?","tags":["javascript","vue.js","vuejs2","vuejs3","vite"],"text":"Title: Why is '.vue' loader not found by Vite when using Vue 3 migration build?\nTags: javascript, vue.js, vuejs2, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI'm attempting to upgrade a Vue 2 project to Vue 3 using the migration build and vite (https://v3-migration.vuejs.org/breaking-changes/migration-build.html#overview)\n\nI've done steps 1-4 (though skipped 4, since not using typescript). At this point, I get the following error:\n\n```\nsrc/main.js:3:16: error: No loader is configured for \".vue\" files: src/App.vue\n```\n\nDespite the message, the issue appears to be with the @ alias, because if I change `import App from '@/App.vue';` to `import App from './App.vue';` in `main.js` it works fine. Any ideas? I have tried changing the alias to `/src/` as well.\n\nOn the one hand, that seems like an easy fix, but on the other there are a bunch of other imports throughout the project that would have to be rewritten.\n\n**main.js:**\n\n```\nimport Vue from 'vue';\nimport App from '@/App.vue';\n\nVue.config.productionTip = false;\n\nlet app = new Vue({\n render: h => h(App)\n}).$mount('#app');\n```\n\n**vite.config.js**\n\n```\nimport { defineConfig } from 'vite';\nimport createVuePlugin from '@vitejs/plugin-vue';\nimport path from 'path';\n\nexport default defineConfig({\n plugins: [ \n createVuePlugin({\n template: {\n compilerOptions: {\n compatConfig: {\n MODE: 2\n }\n }\n }\n }),\n ],\n resolve: {\n alias: {\n '@/': path.resolve(__dirname, './src/'),\n 'vue': '@vue/compat',\n },\n },\n});\n```\n\n**package.json**\n\n```\n{\n \"name\": \"xxx\",\n \"version\": \"0.1.0\",\n \"dependencies\": {\n \"@vue/compat\": \"^3.1.0\",\n \"vue\": \"^3.1.0\"\n },\n \"devDependencies\": {\n \"@vitejs/plugin-vue\": \"^1.2.2\",\n \"@vue/compiler-sfc\": \"^3.1.0\",\n \"vite\": \"^2.4.1\"\n }\n}\n```\n\nI was unable to get a reproduction running in codesandbox (it doesn't appear to like the alias statements in `vite.config.js` at all). But this repo shows the behavior: https://github.com/dovrosenberg/vite-vue-alias-issue\n\nThe error changes sometimes (for no reason apparent to me) when using this repo to:\n`Internal server error: Failed to resolve import \"@/App.vue\" from \"src/main.js\". Does the file exist?'`\n\n========================================\n\nCode:\n```text\nsrc/main.js:3:16: error: No loader is configured for \".vue\" files: src/App.vue\n```\n\n```text\nimport Vue from 'vue';\nimport App from '@/App.vue';\n\nVue.config.productionTip = false;\n\nlet app = new Vue({\n  render: h => h(App)\n}).$mount('#app');\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport createVuePlugin from '@vitejs/plugin-vue';\nimport path from 'path';\n\nexport default defineConfig({\n  plugins: [ \n      createVuePlugin({\n        template: {\n          compilerOptions: {\n            compatConfig: {\n              MODE: 2\n            }\n          }\n        }\n      }),\n    ],\n  resolve: {\n    alias: {\n      '@/': path.resolve(__dirname, './src/'),\n      'vue': '@vue/compat',\n    },\n  },\n});\n```\n\n```text\n{\n  \"name\": \"xxx\",\n  \"version\": \"0.1.0\",\n  \"dependencies\": {\n    \"@vue/compat\": \"^3.1.0\",\n    \"vue\": \"^3.1.0\"\n  },\n  \"devDependencies\": {\n    \"@vitejs/plugin-vue\": \"^1.2.2\",\n    \"@vue/compiler-sfc\": \"^3.1.0\",\n    \"vite\": \"^2.4.1\"\n  }\n}\n```\n\n```text\nimport App from '@/App.vue';\n```\n\n```text\nimport App from './App.vue';\n```\n\n```text\nmain.js\n```\n\n```text\n/src/\n```\n\n```text\nvite.config.js\n```\n\n```text\nInternal server error: Failed to resolve import \"@/App.vue\" from \"src/main.js\". Does the file exist?'\n```\n\n```js\nimport { defineConfig } from 'vite';\nimport path from 'path';\n\nexport default defineConfig({\n  ⋮\n  resolve: {\n    alias: {\n      // '@/': path.resolve(__dirname, './src/'), ❌\n      '@': path.resolve(__dirname, './src/'), ✅\n      ⋮\n    },\n  },\n});\n```\n\n```text\nresolve.alias\n```\n\n```text\n@\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.422Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":188,"estimatedTokens":927}}389{"id":"stack-72405593","source":"stackoverflow","questionId":72405593,"title":"Vue3 and Vue-Select: How to emit child data to parent when using taggable prop?","tags":["javascript","vue.js","vuejs3","vite","vue-select"],"text":"Title: Vue3 and Vue-Select: How to emit child data to parent when using taggable prop?\nTags: javascript, vue.js, vuejs3, vite, vue-select\nSource: Stack Overflow\n\nQuestion:\nI am using the Vue-Select library with Vue3. My objective is to let the user choose tags from an options list and also be able to create new tags if the tags do not exist in the options list.\n\nThis works fine in a child component, **but I am having trouble passing/emitting the data up to the parent component.** I need the data in the parent because I am going to package it up for form processing later.\n\n**How can I successfully get the tags from the child component and into the parent component's `formData.tags` property?**\n\nThe code and sandbox link:\n\n`components/PostEditorTags.vue`:\n\n```\n\n ({ label: tag, value: tag })\"\n v-model=\"selected\"\n :options=\"options\"\n multiple\n taggable\n @input=\"$emit('input', selected)\"\n placeholder=\"add a tag\"\n >\n \n\n child component data:\n {{ selected }}\n\nimport { ref } from 'vue';\nimport vSelect from 'vue-select';\nimport 'vue-select/dist/vue-select.css';\n\ndefineEmits(['input']);\n\nconst options = [\n { value: 'one', label: 'One' },\n { value: 'two', label: 'Two' },\n { value: 'three', label: 'Three' },\n { value: 'four', label: 'Four' },\n { value: 'five', label: 'Five' },\n { value: 'six', label: 'Six' },\n { value: 'seven', label: 'Seven' },\n { value: 'eight', label: 'Eight' },\n { value: 'nine', label: 'Nine' },\n { value: 'ten', label: 'Ten' },\n];\n\nlet selected = ref([]);\n\n```\n\n`components/Parent.vue:`\n\n```\n\n \n\n### Post Tags\n\n \n \n\n \n\n parent component data:\n {{ formData.tags }}\n\nimport PostEditorTags from './PostEditorTags.vue';\n\nconst formData = {\n // title: '',\n // content: '',\n tags: null,\n};\n\nfunction setTagsArr(x) {\n formData.tags = x;\n}\n\n```\n\n========================================\n\nCode:\n```text\n<template>\n  <v-select\n    :create-option=\"(tag) => ({ label: tag, value: tag })\"\n    v-model=\"selected\"\n    :options=\"options\"\n    multiple\n    taggable\n    @input=\"$emit('input', selected)\"\n    placeholder=\"add a tag\"\n  ></v-select>\n  <br />\n  child component data:\n  <pre>{{ selected }}</pre>\n</template>\n\n<script setup>\nimport { ref } from 'vue';\nimport vSelect from 'vue-select';\nimport 'vue-select/dist/vue-select.css';\n\ndefineEmits(['input']);\n\nconst options = [\n  { value: 'one', label: 'One' },\n  { value: 'two', label: 'Two' },\n  { value: 'three', label: 'Three' },\n  { value: 'four', label: 'Four' },\n  { value: 'five', label: 'Five' },\n  { value: 'six', label: 'Six' },\n  { value: 'seven', label: 'Seven' },\n  { value: 'eight', label: 'Eight' },\n  { value: 'nine', label: 'Nine' },\n  { value: 'ten', label: 'Ten' },\n];\n\nlet selected = ref([]);\n</script>\n```\n\n```text\n<template>\n  <h1>Post Tags</h1>\n  <PostEditorTags @input=\"setTagsArr\" />\n  <br />\n  <br />\n  parent component data:\n  <pre>{{ formData.tags }}</pre>\n</template>\n\n<script setup>\nimport PostEditorTags from './PostEditorTags.vue';\n\nconst formData = {\n  // title: '',\n  // content: '',\n  tags: null,\n};\n\nfunction setTagsArr(x) {\n  formData.tags = x;\n}\n</script>\n```\n\n```text\nformData.tags\n```\n\n```text\ncomponents/PostEditorTags.vue\n```\n\n```text\ncomponents/Parent.vue:\n```\n\n```js\n<template>\n  <v-select\n    :create-option=\"(tag) => ({ label: tag, value: tag })\"\n    v-model=\"selected\"\n    :options=\"options\"\n    multiple\n    taggable\n    placeholder=\"add a tag\"\n  ></v-select>\n  <br />\n  child component data:\n  <pre>{{ selected }}</pre>\n</template>\n\n<script setup>\nimport { ref, defineEmits, watch } from 'vue';\nimport vSelect from 'vue-select';\nimport 'vue-select/dist/vue-select.css';\n\nconst options = [{ value: 'one', label: 'One' }, { value: 'two', label: 'Two' }, { value: 'three', label: 'Three' }, { value: 'four', label: 'Four' }, { value: 'five', label: 'Five' }, { value: 'six', label: 'Six' }, { value: 'seven', label: 'Seven' }, { value: 'eight', label: 'Eight' }, { value: 'nine', label: 'Nine' }, { value: 'ten', label: 'Ten' },];\n\nlet selected = ref([]);\n\nwatch(\n  () => selected.value,\n  (newValue, oldValue) => {\n    act(newValue);\n  }\n);\n\nconst emit = defineEmits(['input'])\nconst act = (val) => emit('input', val);\n</script>\n```\n\n```text\n<template>\n  <h1>Post Tags</h1>\n  <PostEditorTags @input=\"setTagsArr\" />\n  <br />\n  <br />\n  parent component data:\n  <pre>{{ formData.tags }}</pre>\n</template>\n\n<script setup>\nimport { reactive } from 'vue'\nimport PostEditorTags from './PostEditorTags.vue';\n\nconst formData = reactive({\n  // title: '',\n  // content: '',\n  tags: null,\n});\n\nfunction setTagsArr(x) {\n  formData.tags = x;\n}\n</script>\n```\n\n```text\ncomponents/PostEditorTags.vue:\n```\n\n```text\ncomponents/Parent.vue:\n```\n\n========================================\n\nComments:\n- That works! I always have trouble with watchers. Thanks for the help.","metadata":{"transformedAt":"2026-08-18T18:33:46.423Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":237,"estimatedTokens":1192}}390{"id":"stack-73951817","source":"stackoverflow","questionId":73951817,"title":"How to connect mobile device to vite with php dev server? (exposing host)","tags":["laravel","vue.js","localhost","vite","inertiajs"],"text":"Title: How to connect mobile device to vite with php dev server? (exposing host)\nTags: laravel, vue.js, localhost, vite, inertiajs\nSource: Stack Overflow\n\nQuestion:\n### Solution:\n\nThanks to **@parastoo** it works now. I had to spin up the dev server like so (2 different terminal tabs):\n\n```\nvite --host=HOST_IP\nphp artisan serve --host=HOST_IP\n```\n\nthen connect with your mobile device (which is connected to your wifi) to:\n\n```\nhttp://HOST_IP:PORT\n```\n\n**HOST_IP** can be seen in the terminal when you run `vite --host`\n\n**PORT** can be configured by adding `--port=8000` to the artisan command.\n\nNo additional entry in `vite.config.js` was required.\n\n### Original Question\n\nI'm using inertia, a monolithic approach to develop apps with a frontend framework like `vue` and `laravel` as backend. I'm trying to connect a mobile device from my network to my development server, which uses `vite` with `php server`:\n\n- run vite:\n\n```\nvite\n```\n\n- run php server:\n\n```\nphp artisan serve\n```\n\nThe site is served from `http://localhost:8000`. From How to expose 'host' for external device display? #3396 I read, that you can do something like this:\n\n```\nvite --host\n```\n\nwhich should expose your network:\n\n```\nvite v2.9.13 dev server running at:\n\n > Local: http://localhost:3000/\n > Network: http://192.xxxxxxxxx:3000/\n\n ready in 419ms.\n```\n\nbut when I try to connect to the network url on my phone, `this page can't be found`. I've also tried to connect with port `8000` which shows `this site can't be reached`.\n\nAny way to make it work?\n\n========================================\n\nTop Answer:\n### *** Clarification\n\nGiven all the answers, I couldn't figure out why hot reload didn't always work. With this answer, I'd like to clarify some steps.\n\nFor a mobile device to see the page, it has to be served on a local network starting with `192.*.*.*` (e.g. `192.168.1.130`).\n\n**In the first terminal**\n\n```\nphp artisan serve --host=192.168.1.130 --port=5173\n```\n\nNow you should be able to connect to the server from your mobile with `http://192.168.1.130:5173`. However, the hot reload doesn't work yet. For that, let's start the Vite dev server.\n\n**In the second terminal**\n\n```\nnpm run dev -- --host=192.168.1.130\n```\n\nThis will start the Vite development server on the same network, but it will use a different port (in my case it was `5174`) which is fine because the hot reload works as expected.\n\nCAVEAT: if you run commands the other way round, `php artisan serve` either can't connect to the same port, or if it connects, the hot reload doesn't work.\n\n**\n\n### *** Improving Workflow (optional)\n\nI was annoyed every time typing `--host` and `--port` commands so I made some changes to the `.ENV` and `package.json` files.\n\n**.ENV**\n\n```\nSERVER_HOST=192.168.1.130\nSERVER_PORT=5173\n```\n\n**package.json**\n\n```\n\"scripts\": {\n \"dev\": \"vite --host=192.168.1.130\",\n},\n```\n\nNow to start the workflow, just open two terminals and type `php artisan serve` and `npm run dev`\n\n========================================\n\nCode:\n```text\nvite --host=HOST_IP\nphp artisan serve --host=HOST_IP\n```\n\n```text\nhttp://HOST_IP:PORT\n```\n\n```text\nvite\n```\n\n```text\nphp artisan serve\n```\n\n```text\nvite --host\n```\n\n```text\nvite v2.9.13 dev server running at:\n\n  > Local:    http://localhost:3000/\n  > Network:  http://192.xxxxxxxxx:3000/\n\n  ready in 419ms.\n```\n\n```text\nvite --host\n```\n\n```text\n--port=8000\n```\n\n```text\nvite.config.js\n```\n\n```text\nvue\n```\n\n```text\nlaravel\n```\n\n```text\nvite\n```\n\n```text\nphp server\n```\n\n```text\nhttp://localhost:8000\n```\n\n```text\nthis page can't be found\n```\n\n```text\n8000\n```\n\n```text\nthis site can't be reached\n```\n\n```text\nPHP artisan serve --host=xx.xx.xx.xx --port=xxxx\n```\n\n```text\nserver: {\n        host: true\n      }\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\nimport vue from '@vitejs/plugin-vue';\n\n    export default defineConfig({\n        plugins: [\n            vue(),\n            laravel({\n                input: ['resources/js/app.js'],\n                refresh: true,\n            }),\n        ],\n        server: {\n            host: true\n          }\n    });\n```\n\n```text\nnpm run dev -- --host=xx.xx.xx.xx\n```\n\n```text\nPHP artisan serve --host=xx.xx.xx.xx --port=xxxx\nnpm run dev -- --host=xx.xx.xx.xx\n```\n\n```text\nvite.config.js\n```\n\n```text\nphp artisan serve --host=192.XXXXXXXX\n```\n\n```text\nphp artisan serve --host=192.168.1.130 --port=5173\n```\n\n```text\nnpm run dev -- --host=192.168.1.130\n```\n\n```text\nSERVER_HOST=192.168.1.130\nSERVER_PORT=5173\n```\n\n```text\n\"scripts\": {\n    \"dev\": \"vite --host=192.168.1.130\",\n},\n```\n\n```text\n192.*.*.*\n```\n\n```text\n192.168.1.130\n```\n\n```text\nhttp://192.168.1.130:5173\n```\n\n```text\n5174\n```\n\n```text\nphp artisan serve\n```\n\n```text\n--host\n```\n\n```text\n--port\n```\n\n```text\n.ENV\n```\n\n```text\npackage.json\n```\n\n```text\nphp artisan serve\n```\n\n```text\nnpm run dev\n```\n\n========================================\n\nComments:\n- When I want to check out how the page would look like in a mobile device, I just replace `npm run dev` for `npm run build`, but not changing the `php artisan serve`. But I guess there is a way to run your frontend as dev mode.\n- I can run `vite build` but I don't know how to connect the device to the php server\n- You need to be on the same network for this to work, like wifi. Then you enter the local IP address starting with 192 (that you don't need to hide here btw) on your phone and it should be good. If you want to access it from outside your home, you will need to use a public IP address and make some port forwarding with your router.\n- An alternative for this is ngrok.com Once installed, run the `ngrok http 8000` command and the service will create a temporary public address for you\n- You don't need to do that since it's already done. But yeah, if you want to try with a module you can either use ngrok or another one similar, forgot the name but it can be found on modules.nuxtjs.org. Again, probably not needed in your case.\n- @kissu This is how it's supposed to work but it doesn't for me. I don't know why.\n- Hard to say without more debugging/info from your side there.\n- Can you show us the configuration concerning vite. You should not be needed to run vite server as you are serving it through laravel. Did you run npm ?\n- Please don't edit answers into questions. If you want to self-answer then *post an answer*.\n- Both devices are on the same wifi network, still not working. Should I not connect to port `8000` (php) ?\n- @ArturM&#252;llerRomanov first step would be to check your local network to find out what you do have on your network. Check your router or any software that is able to map it properly. Then of course, you need to connect to the software exposed on a given IP + port. If you're trying to reach a Vue app running on port 3000 but just reaching the IP, you will not have anything relevant (on port 80).\n- The connection seems to be established (php server shows in console: `2022-10-16 16:00:00 &#47;favicon.ico ...... ~ 0s` but the mobile device only shows a white screen. I've tested on android and iphone and both show the same behaviour.\n- The connection seems to be established (php server shows in console: `2022-10-16 16:00:00 &#47;favicon.ico ...... ~ 0s` but the mobile device only shows a white screen. I've tested on android and iphone and both show the same behaviour.\n- Updated please check it @ArturM&#252;llerRomanov\n- Hey it works! Turns out I had to add thee `--host` parameter to `vite` command with a specific `ip`.\n- It can be `192.168` or `10.0` too. Depends of your local network.\n- In my opinion, it's important to note that you should not navigate to the URL provided by Vite, as it has a different port. Instead, you should navigate to `http:&#47;&#47;192.168.1.10:5173`. This distinction may not be immediately obvious, as Vite suggests a new URL that isn't functional with a different port. In this particular case, Vite is only used to compile the sources but not to serve the page.","metadata":{"transformedAt":"2026-08-18T18:33:46.423Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":39,"totalLines":319,"estimatedTokens":1995}}391{"id":"stack-69010248","source":"stackoverflow","questionId":69010248,"title":"Publishing a component library with Vite, Vue 3 and Typescript to npm","tags":["typescript","vue.js","npm","vuejs3","vite"],"text":"Title: Publishing a component library with Vite, Vue 3 and Typescript to npm\nTags: typescript, vue.js, npm, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI'm attempting to publish a Vue 3 component library with Vite. I've written it in Typescript. However, I'm running into an issue whereby my type definitions aren't being carried across to the package.\n\nWhen importing the component in another project, I am seeing the following issue:\n\n```\nTry `npm i --save-dev @types/repo__mypackagename` if it exists or add a new declaration (.d.ts) file containing `declare module '@repo/mypackagename';\n```\n\nI get that I need to provide a declaration file, but I'm wondering how the is achieved specifically with Vite & Vue 3...\n\nUseful parts of my `package.json` file:\n\n```\n{\n ...\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/celestia-vue.umd.js\",\n \"module\": \"./dist/celestia-vue.es.js\",\n \"exports\": {\n \".\": {\n \"import\": \"./dist/celestia-vue.es.js\",\n \"require\": \"./dist/celestia-vue.umd.js\"\n }\n },\n \"unpkg\": \"./dist/celestia-vue.umd.js\",\n \"jsdelivr\": \"./dist/celestia-vue.umd.js\",\n \"scripts\": {\n \"vite:dev\": \"vite\",\n \"serve\": \"vue-cli-service serve\",\n \"vite:serve\": \"vite preview\",\n \"build\": \"vue-cli-service build\",\n \"vite:build\": \"vue-tsc --noEmit && vite build\",\n \"test:unit\": \"vue-cli-service test:unit\",\n \"lint\": \"vue-cli-service lint\"\n },\n ...\n}\n```\n\nMy `tsconfig.json`:\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"esnext\",\n \"module\": \"esnext\",\n \"lib\": [\n \"es6\",\n \"esnext\",\n \"es2016\",\n \"dom\",\n \"dom.iterable\",\n \"scripthost\"\n ],\n \"allowJs\": true,\n \"declaration\": true,\n \"sourceMap\": false,\n \"outDir\": \"dist\",\n \"rootDir\": \"\",\n \"importHelpers\": true,\n \"strict\": true,\n \"noImplicitAny\": true,\n \"moduleResolution\": \"node\",\n \"baseUrl\": \".\",\n \"paths\": {\n \"@/*\": [\n \"src/*\"\n ]\n },\n \"types\": [\n \"webpack-env\",\n \"jest\"\n ],\n \"allowSyntheticDefaultImports\": true,\n \"resolveJsonModule\": true,\n \"skipLibCheck\": true,\n \"forceConsistentCasingInFileNames\": true\n },\n \"include\": [\n \"src/**/*.ts\",\n \"src/**/*.tsx\",\n \"src/**/*.vue\",\n \"tests/**/*.ts\",\n \"tests/**/*.tsx\"\n ],\n \"exclude\": [\n \"node_modules\",\n \"dist\",\n \"test\"\n ]\n}\n```\n\nI also have the following `vite.config.ts` file:\n\n```\nimport { defineConfig } from 'vite'\n\nimport vue from '@vitejs/plugin-vue'\nimport typescript from '@rollup/plugin-typescript';\n\nimport { resolve } from 'path'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n {\n ...typescript({ tsconfig: './tsconfig.json' }),\n apply: 'build',\n declaration: true,\n declarationDir: 'types/',\n rootDir: '/'\n },\n vue()\n ],\n resolve: {\n alias: {\n '@': resolve(__dirname, '/src'),\n },\n },\n build: {\n lib: {\n entry: resolve(__dirname, 'src/index.ts'),\n name: 'celestia-vue',\n },\n rollupOptions: {\n external: ['vue'],\n output: {\n sourcemap: false,\n // Provide global variables to use in the UMD build\n // for externalized deps\n globals: {\n vue: 'Vue'\n }\n }\n }\n }\n})\n```\n\nThe output of the build process is into the dist folder:\n\nhttps://i.sstatic.net/lOocZ.png\n\nI'm hoping there is something simple I am missing ... maybe in the `vite.config.ts` file, or elsewhere in my code.\n\nN.B. The organisation of my Vue 3 component library is as follows if helpful:\n\nhttps://i.sstatic.net/vo1rV.png\n\n========================================\n\nCode:\n```text\nTry `npm i --save-dev @types/repo__mypackagename` if it exists or add a new declaration (.d.ts) file containing `declare module '@repo/mypackagename';\n```\n\n```json\n{\n  ...\n  \"files\": [\n    \"dist\"\n  ],\n  \"main\": \"./dist/celestia-vue.umd.js\",\n  \"module\": \"./dist/celestia-vue.es.js\",\n  \"exports\": {\n    \".\": {\n      \"import\": \"./dist/celestia-vue.es.js\",\n      \"require\": \"./dist/celestia-vue.umd.js\"\n    }\n  },\n  \"unpkg\": \"./dist/celestia-vue.umd.js\",\n  \"jsdelivr\": \"./dist/celestia-vue.umd.js\",\n  \"scripts\": {\n    \"vite:dev\": \"vite\",\n    \"serve\": \"vue-cli-service serve\",\n    \"vite:serve\": \"vite preview\",\n    \"build\": \"vue-cli-service build\",\n    \"vite:build\": \"vue-tsc --noEmit && vite build\",\n    \"test:unit\": \"vue-cli-service test:unit\",\n    \"lint\": \"vue-cli-service lint\"\n  },\n  ...\n}\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"target\": \"esnext\",\n    \"module\": \"esnext\",\n    \"lib\": [\n      \"es6\",\n      \"esnext\",\n      \"es2016\",\n      \"dom\",\n      \"dom.iterable\",\n      \"scripthost\"\n    ],\n    \"allowJs\": true,\n    \"declaration\": true,\n    \"sourceMap\": false,\n    \"outDir\": \"dist\",\n    \"rootDir\": \"\",\n    \"importHelpers\": true,\n    \"strict\": true,\n    \"noImplicitAny\": true,\n    \"moduleResolution\": \"node\",\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@/*\": [\n        \"src/*\"\n      ]\n    },\n    \"types\": [\n      \"webpack-env\",\n      \"jest\"\n    ],\n    \"allowSyntheticDefaultImports\": true,\n    \"resolveJsonModule\": true,\n    \"skipLibCheck\": true,\n    \"forceConsistentCasingInFileNames\": true\n  },\n  \"include\": [\n    \"src/**/*.ts\",\n    \"src/**/*.tsx\",\n    \"src/**/*.vue\",\n    \"tests/**/*.ts\",\n    \"tests/**/*.tsx\"\n  ],\n  \"exclude\": [\n    \"node_modules\",\n    \"dist\",\n    \"test\"\n  ]\n}\n```\n\n```js\nimport { defineConfig } from 'vite'\n\nimport vue from '@vitejs/plugin-vue'\nimport typescript from '@rollup/plugin-typescript';\n\nimport { resolve } from 'path'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    {\n      ...typescript({ tsconfig: './tsconfig.json' }),\n      apply: 'build',\n      declaration: true,\n      declarationDir: 'types/',\n      rootDir: '/'\n    },\n    vue()\n  ],\n  resolve: {\n    alias: {\n      '@': resolve(__dirname, '/src'),\n    },\n  },\n  build: {\n    lib: {\n      entry: resolve(__dirname, 'src/index.ts'),\n      name: 'celestia-vue',\n    },\n    rollupOptions: {\n      external: ['vue'],\n      output: {\n        sourcemap: false,\n        // Provide global variables to use in the UMD build\n        // for externalized deps\n        globals: {\n          vue: 'Vue'\n        }\n      }\n    }\n  }\n})\n```\n\n```text\npackage.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\nvite.config.ts\n```\n\n```text\nvite.config.ts\n```\n\n========================================\n\nComments:\n- Thanks for your help! This fixed that particular issue. However, I'm seeing a new error - `TS2305: Module '\"@observerly&#47;celestia-vue\"' has no exported member 'CelestiaSkyViewer'.` Do you know where I should look to fix this?\n- I see you actually have two .d.ts files - main.d.ts (the main.ts APp that you'd use if you were writing a spa) and index.d.ts which is probably the entrypoint of your lib. Are you using index.d.ts or main.d.ts in the types property?\n- If I the chain up, my build process is not building .vue component files ... ?\n- In fact, I have added the following as my types: `\"types\": \".&#47;dist&#47;src&#47;types&#47;index.d.ts\",`","metadata":{"transformedAt":"2026-08-18T18:33:46.423Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":313,"estimatedTokens":1654}}392{"id":"stack-72660014","source":"stackoverflow","questionId":72660014,"title":"How to make Vue and Vite work with web components?","tags":["javascript","vue.js","vite","custom-element","lit"],"text":"Title: How to make Vue and Vite work with web components?\nTags: javascript, vue.js, vite, custom-element, lit\nSource: Stack Overflow\n\nQuestion:\nI want to migrate my **Vue 2** project from webpack to Vite.\nAnd have to use 3rd party web components that built with lit-element.\n\nThose components throws errors during the runtime (by vue):\n\nUnknown custom element: - did you register the\ncomponent correctly? For recursive components, make sure to provide\nthe \"name\" option.\n\nAnd also (by lit-element)\n\nFailed to set the 'adoptedStyleSheets' property on 'ShadowRoot':\nFailed to convert value to 'CSSStyleSheet'.\n\nAs far as I can see those 3rd party web components do only this in theirs index files (inside `node_modules`):\n\n```\nimport FooComponent from './FooComponent';\ncustomElements.define('foo-component', FooComponent);\n```\n\nSo before (with webpack setup) I just imported them and everything used to work. Well, actually for webpack `lit-scss-loader` was used also for those components.\n\nI assume that Vite perhaps needs some additional configuration, or maybe something similar to \"webpack\" loader is needed here, but not sure what direction I have to move.\n\nWhat I'm doing wrong?\n\n========================================\n\nTop Answer:\nConfigure `@vite/plugin-vue` to ignore Lit elements, e.g., elements starting with `my-lit` in their registered name:\n\n```\n// vite.config.js\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n plugins: [\n vue({\n template: {\n compilerOptions: {\n // treat all components starting with `my-lit` as custom elements\n isCustomElement: tag => tag.startsWith('my-lit'),\n },\n },\n }),\n ],\n})\n```\n\ndemo\n\n========================================\n\nCode:\n```js\nimport FooComponent from './FooComponent';\ncustomElements.define('foo-component', FooComponent);\n```\n\n```text\nnode_modules\n```\n\n```text\nlit-scss-loader\n```\n\n```text\n//vite.config.ts\n\nimport postcssLit from 'rollup-plugin-postcss-lit';\n\nexport default defineConfig({\n  plugins: [\n    vue(\n      {\n        template: {\n          compilerOptions: {\n            // 1. Tell Vite that all components starting with \"foo-\" are webcomponents\n            isCustomElement: (tag) => tag.startsWith('foo-')\n          }\n        }\n      }\n    ),\n    vueJsx(),\n    // 2. This \"postcssLit\" plugin helps prepare CSS for the webcomponents\n    postcssLit()\n  ],\n  resolve: {\n    alias: {\n      // 3. Tell Vite how to treat CSS paths for webcomponents\n      '~@foo': fileURLToPath(new URL('./node_modules/@foo', import.meta.url))\n    }\n  }\n});\n```\n\n```text\nnode_modules/@foo\n```\n\n```text\nisCustomElement: (tag) => tag.startsWith('foo-')\n```\n\n```text\n'~@foo': fileURLToPath(new URL('./node_modules/@foo', import.meta.url))\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  plugins: [\n    vue({\n      template: {\n        compilerOptions: {\n          // treat all components starting with `my-lit` as custom elements\n          isCustomElement: tag => tag.startsWith('my-lit'),\n        },\n      },\n    }),\n  ],\n})\n```\n\n```text\n@vite/plugin-vue\n```\n\n```text\nmy-lit\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.423Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":140,"estimatedTokens":773}}393{"id":"stack-73879189","source":"stackoverflow","questionId":73879189,"title":"Append 'build' in url laravel 9 vite after vite build command","tags":["vuejs3","vue-router","vite","laravel-9"],"text":"Title: Append 'build' in url laravel 9 vite after vite build command\nTags: vuejs3, vue-router, vite, laravel-9\nSource: Stack Overflow\n\nQuestion:\nLaravel 9\nUsing vite\nVue 3, Vue-router\nRun command vite build and turn off vite server, all links in browser url get '/build/'\n\nIn code\n\n```\nIndex\nMain\n\n```\n\nIn browser\nhttps://i.sstatic.net/gHCDY.jpg\n\nVite config\n\n```\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\nimport vue from '@vitejs/plugin-vue'\n\nexport default defineConfig({\n plugins: [\n vue(),\n laravel({\n input: ['resources/css/app.css', 'resources/js/app.js'],\n refresh: true,\n }),\n ],\n});\n```\n\nBlade\n\n```\n\ngetLocale()) }}\">\n \n \n \n\n Laravel\n\n \n \n\n @vite(['resources/css/app.css', 'resources/js/app.js'])\n \n \n /*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}a{background-color:transparent}[hidden]{display:none}html{font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;line-height:1.5}*,:after,:before{box-sizing:border-box;border:0 solid #e2e8f0}a{color:inherit;text-decoration:inherit}svg,video{display:block;vertical-align:middle}video{max-width:100%;height:auto}.bg-white{--bg-opacity:1;background-color:#fff;background-color:rgba(255,255,255,var(--bg-opacity))}.bg-gray-100{--bg-opacity:1;background-color:#f7fafc;background-color:rgba(247,250,252,var(--bg-opacity))}.border-gray-200{--border-opacity:1;border-color:#edf2f7;border-color:rgba(237,242,247,var(--border-opacity))}.border-t{border-top-width:1px}.flex{display:flex}.grid{display:grid}.hidden{display:none}.items-center{align-items:center}.justify-center{justify-content:center}.font-semibold{font-weight:600}.h-5{height:1.25rem}.h-8{height:2rem}.h-16{height:4rem}.text-sm{font-size:.875rem}.text-lg{font-size:1.125rem}.leading-7{line-height:1.75rem}.mx-auto{margin-left:auto;margin-right:auto}.ml-1{margin-left:.25rem}.mt-2{margin-top:.5rem}.mr-2{margin-right:.5rem}.ml-2{margin-left:.5rem}.mt-4{margin-top:1rem}.ml-4{margin-left:1rem}.mt-8{margin-top:2rem}.ml-12{margin-left:3rem}.-mt-px{margin-top:-1px}.max-w-6xl{max-width:72rem}.min-h-screen{min-height:100vh}.overflow-hidden{overflow:hidden}.p-6{padding:1.5rem}.py-4{padding-top:1rem;padding-bottom:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.pt-8{padding-top:2rem}.fixed{position:fixed}.relative{position:relative}.top-0{top:0}.right-0{right:0}.shadow{box-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px 0 rgba(0,0,0,.06)}.text-center{text-align:center}.text-gray-200{--text-opacity:1;color:#edf2f7;color:rgba(237,242,247,var(--text-opacity))}.text-gray-300{--text-opacity:1;color:#e2e8f0;color:rgba(226,232,240,var(--text-opacity))}.text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}.text-gray-500{--text-opacity:1;color:#a0aec0;color:rgba(160,174,192,var(--text-opacity))}.text-gray-600{--text-opacity:1;color:#718096;color:rgba(113,128,150,var(--text-opacity))}.text-gray-700{--text-opacity:1;color:#4a5568;color:rgba(74,85,104,var(--text-opacity))}.text-gray-900{--text-opacity:1;color:#1a202c;color:rgba(26,32,44,var(--text-opacity))}.underline{text-decoration:underline}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.w-5{width:1.25rem}.w-8{width:2rem}.w-auto{width:auto}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}@media (min-width:640px){.sm\\:rounded-lg{border-radius:.5rem}.sm\\:block{display:block}.sm\\:items-center{align-items:center}.sm\\:justify-start{justify-content:flex-start}.sm\\:justify-between{justify-content:space-between}.sm\\:h-20{height:5rem}.sm\\:ml-0{margin-left:0}.sm\\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\\:pt-0{padding-top:0}.sm\\:text-left{text-align:left}.sm\\:text-right{text-align:right}}@media (min-width:768px){.md\\:border-t-0{border-top-width:0}.md\\:border-l{border-left-width:1px}.md\\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media (min-width:1024px){.lg\\:px-8{padding-left:2rem;padding-right:2rem}}@media (prefers-color-scheme:dark){.dark\\:bg-gray-800{--bg-opacity:1;background-color:#2d3748;background-color:rgba(45,55,72,var(--bg-opacity))}.dark\\:bg-gray-900{--bg-opacity:1;background-color:#1a202c;background-color:rgba(26,32,44,var(--bg-opacity))}.dark\\:border-gray-700{--border-opacity:1;border-color:#4a5568;border-color:rgba(74,85,104,var(--border-opacity))}.dark\\:text-white{--text-opacity:1;color:#fff;color:rgba(255,255,255,var(--text-opacity))}.dark\\:text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}.dark\\:text-gray-500{--tw-text-opacity:1;color:#6b7280;color:rgba(107,114,128,var(--tw-text-opacity))}}\n \n\n \n body {\n font-family: 'Nunito', sans-serif;\n }\n \n \n \n \n \n \n\n```\n\napp.js\n\n```\nimport './bootstrap';\nimport {createApp} from 'vue'\nimport App from './App.vue'\nimport router from './router'\n\nconst app = createApp(App)\napp.use(router)\napp.mount(\"#app\")\n```\n\nSo i want to get in browser like this\n\n```\nhttp://localhost:8000/\nhttp://localhost:8000/index\n```\n\nWithout \"build\"\nWhen i user working server vite with php artisan serve, all work fine, but when i want to prepare data for deploing, so do vite build, and turn off vite server, so append this work in url, but i dont want this word there.\n\n========================================\n\nTop Answer:\nFor me working when i remove **import.meta.env.BASE_URL** from\n\nBefor\n\n```\nconst router = createRouter({\n history: createWebHistory(**import.meta.env.BASE_URL**), \n routes \n});\n```\n\nAfter\n\n```\nconst router = createRouter({\n history: createWebHistory(), \n routes \n});\n```\n\n========================================\n\nCode:\n```text\n<router-link to=\"/index\">Index</router-link>\n<router-link to=\"/\">Main</router-link>\n<router-view></router-view>\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\nimport vue from '@vitejs/plugin-vue'\n\nexport default defineConfig({\n    plugins: [\n        vue(),\n        laravel({\n            input: ['resources/css/app.css', 'resources/js/app.js'],\n            refresh: true,\n        }),\n    ],\n});\n```\n\n```text\n<!DOCTYPE html>\n<html lang=\"{{ str_replace('_', '-', app()->getLocale()) }}\">\n    <head>\n        <meta charset=\"utf-8\">\n        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\n        <title>Laravel</title>\n\n        <!-- Fonts -->\n        <link href=\"https://fonts.bunny.net/css2?family=Nunito:wght@400;600;700&display=swap\" rel=\"stylesheet\">\n\n        @vite(['resources/css/app.css', 'resources/js/app.js'])\n        <!-- Styles -->\n        <style>\n            /*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}a{background-color:transparent}[hidden]{display:none}html{font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;line-height:1.5}*,:after,:before{box-sizing:border-box;border:0 solid #e2e8f0}a{color:inherit;text-decoration:inherit}svg,video{display:block;vertical-align:middle}video{max-width:100%;height:auto}.bg-white{--bg-opacity:1;background-color:#fff;background-color:rgba(255,255,255,var(--bg-opacity))}.bg-gray-100{--bg-opacity:1;background-color:#f7fafc;background-color:rgba(247,250,252,var(--bg-opacity))}.border-gray-200{--border-opacity:1;border-color:#edf2f7;border-color:rgba(237,242,247,var(--border-opacity))}.border-t{border-top-width:1px}.flex{display:flex}.grid{display:grid}.hidden{display:none}.items-center{align-items:center}.justify-center{justify-content:center}.font-semibold{font-weight:600}.h-5{height:1.25rem}.h-8{height:2rem}.h-16{height:4rem}.text-sm{font-size:.875rem}.text-lg{font-size:1.125rem}.leading-7{line-height:1.75rem}.mx-auto{margin-left:auto;margin-right:auto}.ml-1{margin-left:.25rem}.mt-2{margin-top:.5rem}.mr-2{margin-right:.5rem}.ml-2{margin-left:.5rem}.mt-4{margin-top:1rem}.ml-4{margin-left:1rem}.mt-8{margin-top:2rem}.ml-12{margin-left:3rem}.-mt-px{margin-top:-1px}.max-w-6xl{max-width:72rem}.min-h-screen{min-height:100vh}.overflow-hidden{overflow:hidden}.p-6{padding:1.5rem}.py-4{padding-top:1rem;padding-bottom:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.pt-8{padding-top:2rem}.fixed{position:fixed}.relative{position:relative}.top-0{top:0}.right-0{right:0}.shadow{box-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px 0 rgba(0,0,0,.06)}.text-center{text-align:center}.text-gray-200{--text-opacity:1;color:#edf2f7;color:rgba(237,242,247,var(--text-opacity))}.text-gray-300{--text-opacity:1;color:#e2e8f0;color:rgba(226,232,240,var(--text-opacity))}.text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}.text-gray-500{--text-opacity:1;color:#a0aec0;color:rgba(160,174,192,var(--text-opacity))}.text-gray-600{--text-opacity:1;color:#718096;color:rgba(113,128,150,var(--text-opacity))}.text-gray-700{--text-opacity:1;color:#4a5568;color:rgba(74,85,104,var(--text-opacity))}.text-gray-900{--text-opacity:1;color:#1a202c;color:rgba(26,32,44,var(--text-opacity))}.underline{text-decoration:underline}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.w-5{width:1.25rem}.w-8{width:2rem}.w-auto{width:auto}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}@media (min-width:640px){.sm\\:rounded-lg{border-radius:.5rem}.sm\\:block{display:block}.sm\\:items-center{align-items:center}.sm\\:justify-start{justify-content:flex-start}.sm\\:justify-between{justify-content:space-between}.sm\\:h-20{height:5rem}.sm\\:ml-0{margin-left:0}.sm\\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\\:pt-0{padding-top:0}.sm\\:text-left{text-align:left}.sm\\:text-right{text-align:right}}@media (min-width:768px){.md\\:border-t-0{border-top-width:0}.md\\:border-l{border-left-width:1px}.md\\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media (min-width:1024px){.lg\\:px-8{padding-left:2rem;padding-right:2rem}}@media (prefers-color-scheme:dark){.dark\\:bg-gray-800{--bg-opacity:1;background-color:#2d3748;background-color:rgba(45,55,72,var(--bg-opacity))}.dark\\:bg-gray-900{--bg-opacity:1;background-color:#1a202c;background-color:rgba(26,32,44,var(--bg-opacity))}.dark\\:border-gray-700{--border-opacity:1;border-color:#4a5568;border-color:rgba(74,85,104,var(--border-opacity))}.dark\\:text-white{--text-opacity:1;color:#fff;color:rgba(255,255,255,var(--text-opacity))}.dark\\:text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}.dark\\:text-gray-500{--tw-text-opacity:1;color:#6b7280;color:rgba(107,114,128,var(--tw-text-opacity))}}\n        </style>\n\n        <style>\n            body {\n                font-family: 'Nunito', sans-serif;\n            }\n        </style>\n    </head>\n    <body>\n    <div id=\"app\">\n    </div>\n    </body>\n</html>\n```\n\n```text\nimport './bootstrap';\nimport {createApp} from 'vue'\nimport App from './App.vue'\nimport router from './router'\n\nconst app = createApp(App)\napp.use(router)\napp.mount(\"#app\")\n```\n\n```text\nhttp://localhost:8000/\nhttp://localhost:8000/index\n```\n\n```text\nconst router = createRouter({\n    history: createWebHistory(),\n    routes\n});\n```\n\n```text\nimport.meta.env.BASE_URL\n```\n\n```text\ncreateWebHistory()\n```\n\n```text\n/resources/js/router/index.js\n```\n\n```text\nconst router = createRouter({\n history: createWebHistory(**import.meta.env.BASE_URL**), \n routes \n});\n```\n\n```text\nconst router = createRouter({\n history: createWebHistory(), \n routes \n});\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.423Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":222,"estimatedTokens":2905}}394{"id":"stack-76573766","source":"stackoverflow","questionId":76573766,"title":"How to properly create wp enqueue and functions script to run vite frontend","tags":["php","wordpress","vite"],"text":"Title: How to properly create wp enqueue and functions script to run vite frontend\nTags: php, wordpress, vite\nSource: Stack Overflow\n\nQuestion:\nI am running twenty-twentythreetheme of WordPress at the moment I have created a default vite Vue project inside my themes folder. I have not found much tutorials online that match my use case.\n\nI want to run the vite frontend on my WordPress website. The following is my enqueue script and functions.php\n\nFunctions.php\n\n```\n\n```\n\nenqueue-scripts.php\n\n```\nfunction enqueue_vue_assets() {\n wp_enqueue_script( 'app', get_template_directory_uri() . '/example/dist/assets/index-ec461b82.js', array(), '1.0', true );\n wp_enqueue_style( 'app', get_template_directory_uri() . '/example/dist/assets/index-fc5f319f.css', array(), '1.0' );\n}\nadd_action( 'wp_enqueue_scripts', 'enqueue_vue_assets' );\n\n?>\n```\n\nThese files are inside my twenty-twentythreetheme folder. The example is my vite project. I have not made any configurations in vite. Do I need to make any? What changes do I need to make in my enqueue script and functions script.\n\nAlso the twentytwentythree theme has mostly .html files on its frontend which I have wiped and added div id=app that should come from the app.vue.\n\n========================================\n\nTop Answer:\nI just want to add this answer for anyone else coming here after April/May 2024. I used the accepted answer to get everything up and running in my theme, however I found that a fair few issues started happening after updating to Vite v5 and also using laravel-vite-plugin v1.0 - the styles would reload fine with HMR however all JavaScript failed to load and just broke everything.\n\nAfter trying for quite a while to find a work around, I eventually found a post from a company called SouthcoastWeb who have forked the laravel-vite-plugin and made a WordPress version. I followed their instructions (with a few modifications, I'll show those below) and now everything works smoothly - https://southcoastweb.co.uk/open-source-software/wp-vite/\n\nEdit 4th June 2025:\n\nThe above link doesn't appear to work anymore, however you can find similar instructions here - https://evomark.co.uk/open-source-software/wordpress-vite/\n\nThe steps I took:\n\nFirstly, I decided to fork their WordPress plugin and install it from my own GitHub via composer as a `must-use` plugin. I then installed the NPM package as directed on their instructions.\n\nNext, I set my `vite.config.mjs` file up like this. You'll notice I have some extra bits in with `dotenv` etc. - this is because I'm using Roots/Bedrock and wanted to read my URL from the `.env`:\n\n```\nimport { defineConfig } from \"vite\";\nimport { wordpress } from \"wordpress-vite-plugin\";\nimport path from 'path'\nimport vue from '@vitejs/plugin-vue'\nimport dotenv from 'dotenv'\n\ndotenv.config({\n path: path.resolve(__dirname, '../../../../.env')\n});\n\nconst domain = process.env.WP_HOME.replace(/^https?:\\/\\//i, '');\nconst domainName = domain.split('/')[0];\n\nexport default defineConfig(() => ({\n plugins: [\n wordpress({\n input: [\n 'resources/js/app.js',\n 'resources/css/app.css',\n 'resources/css/editor-style.css'\n ],\n refresh: [\n '**.php',\n '**.vue',\n '**.css',\n ],\n namespace: \"theme-vite\",\n }),\n vue({\n template: {\n transformAssetUrls: {\n base: false,\n includeAbsolute: false\n }\n }\n })\n ],\n server: {\n https: false,\n host: domainName,\n },\n optimizeDeps: {\n include: [\n 'vue',\n ]\n },\n}));\n```\n\nFrom here, I then set up a `vite.php` file inside a `functions` subdirectory and then injected it into my main `functions.php` file using `require_once(__DIR__ . '/functions/vite.php');` - I only do this to keep things separated, but here's the code:\n\n```\nenqueue([\n 'input' => ['resources/js/app.js', 'resources/css/app.css'],\n 'namespace' => 'theme-vite'\n]);\n\n$wpViteAdmin->enqueue([\n 'input' => ['resources/css/editor-style.css'],\n 'namespace' => 'theme-vite',\n 'admin' => true,\n]);\n```\n\nYou'll notice that I've instantiated two instances of the `WpVite` class; one for frontend files and one for the admin styles. This is mainly because the static usage (`WpVite::enqueue`) in their example wasn't working for me for some reason (PHP 8.2) so I decided to go down this route which works absolutely fine.\n\nAnd in terms of the scripts inside `package.json`, I just added a couple extra to account for other instances that people may have used over different tools/setups:\n\n```\n\"scripts\": {\n \"dev\": \"vite\",\n \"watch\": \"npm run dev\",\n \"build\": \"vite build\",\n \"production\": \"vite build\"\n},\n```\n\nI hope this helps someone! Like I say, the original answer worked brilliantly, however I think there must be some breaking changes in Vite v5 and laravel-vite-plugin v1 that just don't work well with those instructions anymore.\n\nAndy\n\n========================================\n\nCode:\n```text\n<?php\n/**\n * Vue Twenty Seventeen Child Theme Functions and Definitions.\n * Requires Twenty Seventeen and only works in WordPress 4.7 or later.\n *\n * @package WordPress\n */\n\n // includes for the callbacks.\ninclude_once( get_stylesheet_directory() . '/enqueue-scripts.php' );\n\n/* hooks and filters */\n\n?>\n```\n\n```text\nfunction enqueue_vue_assets() {\n wp_enqueue_script( 'app', get_template_directory_uri() . '/example/dist/assets/index-ec461b82.js', array(), '1.0', true );\n wp_enqueue_style( 'app', get_template_directory_uri() . '/example/dist/assets/index-fc5f319f.css', array(), '1.0' );\n}\nadd_action( 'wp_enqueue_scripts', 'enqueue_vue_assets' );\n\n?>\n```\n\n```php\n<?php\n\nclass Vite {\n\n    /**\n     * Flag to determine whether hot server is active.\n     * Calculated when Vite::initialise() is called.\n     *\n     * @var bool\n     */\n    private static bool $isHot = false;\n\n    /**\n     * The URI to the hot server. Calculated when\n     * Vite::initialise() is called.\n     *\n     * @var string\n     */\n    private static string $server;\n\n    /**\n     * The path where compiled assets will go.\n     *\n     * @var string\n     */\n    private static string $buildPath = 'build';\n\n    /**\n     * Manifest file contents. Initialised\n     * when Vite::initialise() is called.\n     *\n     * @var array\n     */\n    private static array $manifest = [];\n\n    /**\n     * To be run in the header.php file, will check for the presence of a hot file.\n     *\n     * @param  string|null  $buildPath\n     * @param  bool  $output  Whether to output the Vite client.\n     *\n     * @return string|null\n     * @throws Exception\n     */\n    public static function init(string $buildPath = null, bool $output = true): string|null\n    {\n\n        static::$isHot = file_exists(static::hotFilePath());\n\n        // have we got a build path override?\n        if ($buildPath) {\n            static::$buildPath = $buildPath;\n        }\n\n        // are we running hot?\n        if (static::$isHot) {\n            static::$server = file_get_contents(static::hotFilePath());\n            $client = static::$server . '/@vite/client';\n\n            // if output\n            if ($output) {\n                printf(/** @lang text */ '<script type=\"module\" src=\"%s\"></script>', $client);\n            }\n\n            return $client;\n        }\n\n        // we must have a manifest file...\n        if (!file_exists($manifestPath = static::buildPath() . '/manifest.json')) {\n            throw new Exception('No Vite Manifest exists. Should hot server be running?');\n        }\n\n        // store our manifest contents.\n        static::$manifest = json_decode(file_get_contents($manifestPath), true);\n\n        return null;\n    }\n\n    /**\n     * Enqueue the module\n     *\n     * @param string|null $buildPath\n     *\n     * @return void\n     * @throws Exception\n     */\n    public static function enqueue_module(string $buildPath = null): void\n    {\n        // we only want to continue if we have a client.\n        if (!$client = Vite::init($buildPath, false)) {\n            return;\n        }\n\n        // enqueue our client script\n        wp_enqueue_script('vite-client',$client,[],null);\n\n        // update html script type to module wp hack\n        Vite::script_type_module('vite-client');\n\n    }\n\n    /**\n     * Return URI path to an asset.\n     *\n     * @param $asset\n     *\n     * @return string\n     * @throws Exception\n     */\n    public static function asset($asset): string\n    {\n        if (static::$isHot) {\n            return static::$server . '/' . ltrim($asset, '/');\n        }\n\n        if (!array_key_exists($asset, static::$manifest)) {\n            throw new Exception('Unknown Vite build asset: ' . $asset);\n        }\n\n        return implode('/', [ get_stylesheet_directory_uri(), static::$buildPath, static::$manifest[$asset]['file'] ]);\n    }\n\n    /**\n     * Internal method to determine hotFilePath.\n     *\n     * @return string\n     */\n    private static function hotFilePath(): string\n    {\n        return implode('/', [static::buildPath(), 'hot']);\n    }\n\n    /**\n     * Internal method to determine buildPath.\n     *\n     * @return string\n     */\n    private static function buildPath(): string\n    {\n        return implode('/', [get_stylesheet_directory(), static::$buildPath]);\n    }\n\n    /**\n     * Return URI path to an image.\n     *\n     * @param $img\n     *\n     * @return string|null\n     * @throws Exception\n     */\n    public static function img($img): ?string\n    {\n\n        try {\n\n            // set the asset path to the image.\n            $asset = 'resources/img/' . ltrim($img, '/');\n\n            // if we're not running hot, return the asset.\n            return static::asset($asset);\n\n        } catch (Exception $e) {\n\n            // handle the exception here or log it if needed.\n            // you can also return a default image or null in case of an error.\n            return $e->getMessage(); // optionally, you can retrieve the error message\n\n        }\n\n    }\n\n    /**\n     * Update html script type to module wp hack.\n     *\n     * @param $scriptHandle bool|string\n     * @return mixed\n     */\n    public static function script_type_module(bool|string $scriptHandle = false): string\n    {\n\n        // change the script type to module\n        add_filter('script_loader_tag', function ($tag, $handle, $src) use ($scriptHandle) {\n\n            if ($scriptHandle !== $handle) {\n                return $tag;\n            }\n\n            // return the new script module type tag\n            return '<script type=\"module\" src=\"' . esc_url($src) . '\" id=\"' . $handle . '-js\"></script>';\n\n        }, 10, 3);\n\n        // return false\n        return false;\n\n    }\n\n}\n```\n\n```php\n<?php\n\nclass Theme {\n\n    public function __construct()\n    {\n        \n        // enqueue admin styles scripts\n        add_action('wp_enqueue_scripts', [ $this, 'enqueue_styles_scripts' ], 20);\n        \n    }\n    \n    /**\n     * @return void\n     * @throws Exception\n     */\n    public function enqueue_styles_scripts(): void\n    {\n\n        // enqueue the Vite module\n        Vite::enqueue_module();\n\n        // register theme-style-css\n        $filename = Vite::asset('resources/scss/theme.scss');\n\n        // enqueue theme-style-css into our head\n        wp_enqueue_style('theme-style', $filename, [], null, 'screen');\n\n        // register theme-script-js\n        $filename = Vite::asset('resources/js/theme.js');\n\n        // enqueue theme-script-js into our head (change false to true for footer)\n        wp_enqueue_script('theme-script', $filename, [], null, false);\n\n        // update html script type to module wp hack\n        Vite::script_type_module('theme-script');\n\n    }\n\n}\n\nnew Theme();\n```\n\n```php\n<?php\n\n// require libs\nrequire_once(__DIR__ . '/lib/Vite.lib.php');\nrequire_once(__DIR__ . '/lib/Theme.lib.php');\n```\n\n```json\n{\n  \"private\": true,\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"watch\": \"npm run dev\",\n    \"build\": \"vite build\",\n    \"production\": \"vite build\"\n  },\n  \"devDependencies\": {\n    \"sass\": \"^1.63.6\",\n    \"vite\": \"^4.4.3\",\n    \"laravel-vite-plugin\": \"^0.7.8\"\n  },\n  \"dependencies\": {\n\n  }\n}\n```\n\n```js\nimport {defineConfig} from \"vite\";\nimport laravel from 'laravel-vite-plugin';\n\nexport default defineConfig(() => ({\n    base: '',\n    build: {\n        emptyOutDir: true,\n        manifest: true,\n        outDir: 'build',\n        assetsDir: 'assets'\n    },\n    plugins: [\n        laravel({\n            publicDirectory: 'build',\n            input: [\n                'resources/js/theme.js',\n                'resources/scss/theme.scss'\n            ],\n            refresh: [\n                '**.php'\n            ]\n        })\n    ],\n    resolve: {\n        alias: [\n            {\n                find: /~(.+)/,\n                replacement: process.cwd() + '/node_modules/$1'\n            },\n        ]\n    }\n}));\n```\n\n```shell\nnpm install\n```\n\n```shell\nnpm run build\n```\n\n```html\n<link href=\"http://localhost/wp-content/themes/vite-wordpress/build/assets/theme-716126ae.css\" rel=\"stylesheet\" id=\"theme-style-css\" type=\"text/css\" media=\"screen\">\n```\n\n```html\n<script src=\"http://localhost/wp-content/themes/vite-wordpress/build/assets/theme-13161a16.js\" type=\"module\" id=\"theme-script-js\"></script>\n```\n\n```shell\nnpm run dev\n```\n\n```html\n<link href=\"http://127.0.0.1:5173/resources/scss/theme.scss\" rel=\"stylesheet\" id=\"theme-style-css\" type=\"text/css\" media=\"screen\">\n```\n\n```html\n<script src=\"http://127.0.0.1:5173/resources/js/theme.js\" type=\"module\" id=\"theme-script-js\"></script>\n```\n\n```html\n<script src=\"http://127.0.0.1:5173/@vite/client\" type=\"module\" id=\"vite-client-js\"></script>\n```\n\n```php\n<img src=\"<?=Vite::img('example.png')?>\" alt=\"Example\" />\n```\n\n```css\nBODY {\n  background-image: url(../img/example.png);\n}\n```\n\n```text\nhot\n```\n\n```text\ntwentytwentythree\n```\n\n```text\nVite.lib.php\n```\n\n```text\nVite.lib.php\n```\n\n```text\nlib\n```\n\n```text\ntwentytwentythree\n```\n\n```text\nVite.lib.php\n```\n\n```text\nfunctions.php\n```\n\n```text\nTheme.lib.php\n```\n\n```text\nfunction.php\n```\n\n```text\nTheme.lib.php\n```\n\n```text\nVite.lib.php\n```\n\n```text\npackage.json\n```\n\n```text\npackage.json\n```\n\n```text\nlaravel-vite-plugin\n```\n\n```text\npackage.json\n```\n\n```text\nvite.config.js\n```\n\n```text\nvite.config.js\n```\n\n```text\ntheme.css\n```\n\n```text\ntheme.js\n```\n\n```text\nvite.config.js\n```\n\n```text\npackage.json\n```\n\n```text\nresources\n```\n\n```text\nresources\n```\n\n```text\nimg, scss, js\n```\n\n```text\ntheme.scss, theme.js\n```\n\n```text\npackage.json\n```\n\n```text\nnode_modules\n```\n\n```text\npackage-lock.json\n```\n\n```text\nmanifest.json\n```\n\n```text\nresources\n```\n\n```text\nbuild/assets\n```\n\n```text\nnpm run build\n```\n\n```text\nbuild\n```\n\n```text\nbuild/manifest.json\n```\n\n```text\nbuild/assets/..\n```\n\n```text\nnpm run build\n```\n\n```text\nmanifest.json\n```\n\n```text\nnpm run build\n```\n\n```text\ntheme.css\n```\n\n```text\ntheme.js\n```\n\n```text\ntheme.css\n```\n\n```text\ntheme.js\n```\n\n```text\nstaging\n```\n\n```text\nproduction\n```\n\n```text\nhot\n```\n\n```text\nhot\n```\n\n```text\nbuild\n```\n\n```text\nhot\n```\n\n```text\nhot\n```\n\n```text\nbuild\n```\n\n```text\ntheme.css\n```\n\n```text\ntheme.js\n```\n\n```text\n<head>\n```\n\n```text\nhot\n```\n\n```text\ntheme.css\n```\n\n```text\ntheme.js\n```\n\n```text\nnpm run build\n```\n\n```text\nbuild\n```\n\n```text\nbuild\n```\n\n```text\nstaging\n```\n\n```text\nproduction\n```\n\n```text\nfunctions.php\n```\n\n```text\nVite.lib.php\n```\n\n```text\nTheme.lib.php\n```\n\n```text\nstaging\n```\n\n```text\nproduction\n```\n\n```text\nbuild/assets\n```\n\n```text\nresources/img\n```\n\n```text\nbuild\n```\n\n```text\nresources/img\n```\n\n```text\nbuild/assets\n```\n\n```text\nphp\n```\n\n```text\nscss\n```\n\n```text\nnpm run build\n```\n\n```text\n<img src=\"<?=Vite::img('example.png')?>\" alt=\"Example\" />\n```\n\n```text\nimport.meta.glob([ '../img/**', ]);\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport { wordpress } from \"wordpress-vite-plugin\";\nimport path from 'path'\nimport vue from '@vitejs/plugin-vue'\nimport dotenv from 'dotenv'\n\ndotenv.config({\n    path: path.resolve(__dirname, '../../../../.env')\n});\n\nconst domain = process.env.WP_HOME.replace(/^https?:\\/\\//i, '');\nconst domainName = domain.split('/')[0];\n\nexport default defineConfig(() => ({\n    plugins: [\n        wordpress({\n            input: [\n                'resources/js/app.js',\n                'resources/css/app.css',\n                'resources/css/editor-style.css'\n            ],\n            refresh: [\n                '**.php',\n                '**.vue',\n                '**.css',\n            ],\n            namespace: \"theme-vite\",\n        }),\n        vue({\n            template: {\n                transformAssetUrls: {\n                    base: false,\n                    includeAbsolute: false\n                }\n            }\n        })\n    ],\n    server: {\n        https: false,\n        host: domainName,\n    },\n    optimizeDeps: {\n        include: [\n            'vue',\n        ]\n    },\n}));\n```\n\n```text\n<?php\n\nuse EvoMark\\WpVite\\WpVite;\n\n$wpVite = new WpVite();\n$wpViteAdmin = new WpVite();\n\n$wpVite->enqueue([\n    'input' => ['resources/js/app.js', 'resources/css/app.css'],\n    'namespace' => 'theme-vite'\n]);\n\n$wpViteAdmin->enqueue([\n    'input' => ['resources/css/editor-style.css'],\n    'namespace' => 'theme-vite',\n    'admin' => true,\n]);\n```\n\n```text\n\"scripts\": {\n    \"dev\": \"vite\",\n    \"watch\": \"npm run dev\",\n    \"build\": \"vite build\",\n    \"production\": \"vite build\"\n},\n```\n\n```text\nmust-use\n```\n\n```text\nvite.config.mjs\n```\n\n```text\ndotenv\n```\n\n```text\n.env\n```\n\n```text\nvite.php\n```\n\n```text\nfunctions\n```\n\n```text\nfunctions.php\n```\n\n```text\nrequire_once(__DIR__ . '/functions/vite.php');\n```\n\n```text\nWpVite\n```\n\n```text\nWpVite::enqueue\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- Brilliant mate I was able to run it by enquueueing the build files of vite and div id app on index.php but this is gold\n- @artistAhmed Nice man, did you get Vite local js server and hot file running using `npm run dev` after initial `npm run build`? This Vite dev is a game changer for live rendering development!\n- Only build files at the moment I will be trying your method soon on a different example\n- Nice! Report back when you do 👍🏼 it's pretty sick\n- I will building a plugin soon which is pretty much gonna enqueue a Vue project and upload it as a zip\n- This is quite possibly the most useful, well-organized, helpful stackoverflow answer I have encountered in my over a decade of web development. Thank you from the bottom of my heart.","metadata":{"transformedAt":"2026-08-18T18:33:46.423Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":108,"totalLines":951,"estimatedTokens":4537}}395{"id":"stack-77383551","source":"stackoverflow","questionId":77383551,"title":"VITE.JS SSR Not Working with react-router-dom","tags":["reactjs","node.js","react-router","react-router-dom","vite"],"text":"Title: VITE.JS SSR Not Working with react-router-dom\nTags: reactjs, node.js, react-router, react-router-dom, vite\nSource: Stack Overflow\n\nQuestion:\nI been trying to create template with `Vite SSR` with `react-router-dom` for my requirements.\ni know `Next JS` is better alternative for `Vite SSR`.\n\nheare i have some configs that i made for this template.\n\n### Vite.config.ts\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\nimport path from 'path'\n\nexport default defineConfig({\n plugins: [react()],\n ssr: {\n external: [\n 'react-router-dom'\n ]\n },\n\n resolve: {\n alias: {\n \"@App\": path.resolve(process.cwd(), \"src\"),\n \"@Components\": path.resolve(process.cwd(), \"src/Components\"),\n \"@Pages\": path.resolve(process.cwd(), \"src/pages\"),\n \"@Styles\": path.resolve(process.cwd(), \"src/Styles\"),\n \"@Public\": path.resolve(process.cwd(), \"public\")\n },\n },\n})\n```\n\n### Src/App.tsx\n\n```\nimport { BrowserRouter } from \"react-router-dom\";\n\nfunction Application() {\n return (\n \n HI\n \n );\n}\n\nexport default Application;\n```\n\n### Console\n\nhttps://i.sstatic.net/1FUvS.png\n\n### How to Reproduce this template\n\n```\nyarn create vite\n```\n\nSelect Others\nSelect ssr-react\nSelect typescript+swc\n\nReplace src/App.tsx to upper file\n\nRun\n\n```\nyarn dev\n```\n\n### Tags\n\n`vite` `vitejs` `vitejs ssr` `react` `react-router` `react-router-dom` `ssr` `js dom` `vite config`\n\nI Expected to working React application with `react-router-dom`.\n\n========================================\n\nTop Answer:\nIn vite react-ssr app, When I import `StaticRouter` component and other components like `Link` from **react-router-dom** package, I get this error saying,\n\n```\nSyntaxError: [vite] Named export 'StaticRouter' not found. The requested module 'react-router-dom' is a CommonJS module, which may not support all module.exports as named exports.\n```\n\nYou can fix this by simply using **react-router** package instead of **react-router-dom**.\n\n### Files\n\nsrc/entry-server.tsx\n\n```\nimport { StrictMode } from \"react\";\nimport { renderToString } from \"react-dom/server\";\nimport { StaticRouter } from \"react-router\";\nimport Router from \"./Router\";\n\nexport function render(url: string) {\n const html = renderToString(\n \n \n \n \n \n );\n return { html };\n}\n```\n\nsrc/entry-client.tsx\n\n```\nimport { StrictMode } from \"react\";\nimport { hydrateRoot } from \"react-dom/client\";\nimport { BrowserRouter } from \"react-router\";\nimport Router from \"./Router\";\n\nhydrateRoot(\n document.getElementById(\"root\") as HTMLElement,\n \n \n \n \n \n);\n```\n\nsrc/Router.tsx\n\n```\nimport { Route, Routes } from \"react-router\";\n\nimport CategoriesPage from \"./pages/CategoriesPage\";\nimport HomePage from \"./pages/HomePage\";\nimport NotFound from \"./pages/NotFound\";\n\nfunction Router() {\n return (\n \n } />\n } />\n } />\n \n );\n}\n\nexport default Router;\n```\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\nimport path from 'path'\n\nexport default defineConfig({\n    plugins: [react()],\n    ssr: {\n        external: [\n            'react-router-dom'\n        ]\n    },\n\n    resolve: {\n        alias: {\n            \"@App\": path.resolve(process.cwd(), \"src\"),\n            \"@Components\": path.resolve(process.cwd(), \"src/Components\"),\n            \"@Pages\": path.resolve(process.cwd(), \"src/pages\"),\n            \"@Styles\": path.resolve(process.cwd(), \"src/Styles\"),\n            \"@Public\": path.resolve(process.cwd(), \"public\")\n        },\n    },\n})\n```\n\n```text\nimport { BrowserRouter } from \"react-router-dom\";\n\n\nfunction Application() {\n    return (\n        <BrowserRouter>\n            HI\n        </BrowserRouter>\n    );\n}\n\nexport default Application;\n```\n\n```bash\nyarn create vite\n```\n\n```bash\nyarn dev\n```\n\n```text\nVite SSR\n```\n\n```text\nreact-router-dom\n```\n\n```text\nNext JS\n```\n\n```text\nVite SSR\n```\n\n```text\nvite\n```\n\n```text\nvitejs\n```\n\n```text\nvitejs ssr\n```\n\n```text\nreact\n```\n\n```text\nreact-router\n```\n\n```text\nreact-router-dom\n```\n\n```text\nssr\n```\n\n```text\njs dom\n```\n\n```text\nvite config\n```\n\n```text\nreact-router-dom\n```\n\n```text\nyarn create vite\n```\n\n```bash\nyarn add compression cross-env sirv express react-router-dom\n```\n\n```js\nimport fs from \"node:fs/promises\";\nimport path from \"path\";\nimport express from \"express\";\nimport { createServer as createViteServer } from \"vite\";\n\nconst isProduction = process.env.NODE_ENV === \"production\";\nconst Port = process.env.PORT || 3000;\nconst Base = process.env.BASE || \"/\";\n\nconst templateHtml = isProduction\n    ? await fs.readFile(\"./dist/client/index.html\", \"utf-8\")\n    : \"\";\n\n    const ssrManifest = isProduction\n    ? await fs.readFile(\"./dist/client/.vite/ssr-manifest.json\", \"utf-8\")\n    : undefined;\n\nconst app = express();\nlet vite;\n\n// ? Add vite or respective production middlewares\nif (!isProduction) {\n    vite = await createViteServer({\n        server: { middlewareMode: true },\n        appType: \"custom\",\n    });\n\n    app.use(vite.middlewares);\n} else {\n    const sirv = (await import(\"sirv\")).default;\n    const compression = (await import(\"compression\")).default;\n    app.use(compression());\n    app.use(Base, sirv(\"./dist/client\", {\n        extensions: [],\n        gzip: true,\n    }));\n}\n\n// ? Add Your Custom Routers & Middlewares heare\napp.use(express.static(\"public\"));\napp.use(express.json());\napp.use(express.urlencoded({ extended: true }));\napp.get(\"/api\", (req, res) => {\n    res.json({ message: \"Hello World\" });\n});\n\n// ? SSR Render - Rendring Middleware\napp.use(\"*\", async (req, res, next) => {\n\n    // ! Favicon Fix\n    if (req.originalUrl === \"/favicon.ico\") {\n        return res.sendFile(path.resolve(\"./public/vite.svg\"));\n    }\n\n    // ! SSR Render - Do not Edit if you don't know what heare whats going on\n    let template, render;\n\n    try {\n        if (!isProduction) {\n            template = await fs.readFile('./index.html', 'utf-8');\n            template = await vite.transformIndexHtml(req.originalUrl, template);\n            render = (await vite.ssrLoadModule(\"/src/entry-server.tsx\")).render;\n        } else {\n            template = templateHtml;\n            render = (await import(\"./dist/server/entry-server.js\")).render;\n        }\n\n        const rendered = await render({ path: req.originalUrl }, ssrManifest);\n        const html = template.replace(`<!--app-html-->`, rendered ?? '');\n\n        res.status(200).setHeader(\"Content-Type\", \"text/html\").end(html);\n    } catch (error) {\n        // ? You can Add Something Went Wrong Page\n        vite.ssrFixStacktrace(error);\n        next(error);\n    }\n});\n\n// ? Start http server\napp.listen(Port, () => {\n    console.log(`Server running on http://localhost:${Port}`);\n});\n```\n\n```text\nimport ReactDOMServer from \"react-dom/server\";\nimport { StaticRouter } from \"react-router-dom/server\";\n\nimport { Router } from \"./router\";\n\ninterface IRenderProps {\n    path: string;\n}\n\nexport const render = ({ path }: IRenderProps) => {\n    return ReactDOMServer.renderToString(\n        <StaticRouter location={path}>\n            <Router />\n        </StaticRouter>\n    );\n};\n```\n\n```text\nimport ReactDOM from \"react-dom/client\";\nimport { BrowserRouter } from \"react-router-dom\";\n\nimport { Router } from \"./router\";\n\nReactDOM.hydrateRoot(\n    document.getElementById(\"app\") as HTMLElement,\n    <BrowserRouter>\n        <Router />\n    </BrowserRouter>\n);\n```\n\n```text\nimport { Routes, Route } from \"react-router-dom\";\n\nimport { Home } from \"./pages/Home\";\nimport { Other } from \"./pages/Other\";\nimport { NotFound } from \"./pages/NotFound\";\n\nexport const Router = () => {\n    return (\n        <Routes>\n            <Route index element={<Home />} />\n            <Route path=\"/other\" element={<Other />} />\n            <Route path=\"*\" element={<NotFound />} />\n        </Routes>\n    );\n};\n```\n\n```json\n{\n    \"scripts\": {\n         \"dev\": \"cross-env NODE_ENV=development node ./server.js\",\n         \"build\": \"npm run build:client && npm run build:server\",\n         \"build:client\": \"vite build --ssrManifest --outDir dist/client\",\n         \"build:server\": \"vite build --ssr src/entry-server.tsx --outDir dist/server\",\n         \"serve\": \"cross-env NODE_ENV=production node ./server.js\"\n    }\n}\n```\n\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <link rel=\"icon\" type=\"image/svg+xml\" href=\"/vite.svg\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>Vite + React + TS</title>\n  </head>\n  <body>\n    <div id=\"app\">\n        <!--app-html-->\n    </div>\n    <script type=\"module\" src=\"/src/entry-client.tsx\"></script>\n  </body>\n</html>\n```\n\n```text\nexport const Home = () => {\n    return <div>This is the Home Page</div>;\n};\n```\n\n```text\nexport const Other= () => {\n    return <div>This is the Another Page</div>;\n};\n```\n\n```text\nexport const NotFound = () => {\n    return <div>Not Found</div>;\n};\n```\n\n```bash\nyarn dev\n```\n\n```text\nStaticRouter\n```\n\n```text\nnext.js ssr\n```\n\n```none\nSyntaxError: [vite] Named export 'StaticRouter' not found. The requested module 'react-router-dom' is a CommonJS module, which may not support all module.exports as named exports.\n```\n\n```js\nimport { StrictMode } from \"react\";\nimport { renderToString } from \"react-dom/server\";\nimport { StaticRouter } from \"react-router\";\nimport Router from \"./Router\";\n\nexport function render(url: string) {\n  const html = renderToString(\n    <StrictMode>\n      <StaticRouter location={url}>\n        <Router />\n      </StaticRouter>\n    </StrictMode>\n  );\n  return { html };\n}\n```\n\n```text\nimport { StrictMode } from \"react\";\nimport { hydrateRoot } from \"react-dom/client\";\nimport { BrowserRouter } from \"react-router\";\nimport Router from \"./Router\";\n\nhydrateRoot(\n  document.getElementById(\"root\") as HTMLElement,\n  <StrictMode>\n    <BrowserRouter>\n      <Router />\n    </BrowserRouter>\n  </StrictMode>\n);\n```\n\n```text\nimport { Route, Routes } from \"react-router\";\n\nimport CategoriesPage from \"./pages/CategoriesPage\";\nimport HomePage from \"./pages/HomePage\";\nimport NotFound from \"./pages/NotFound\";\n\nfunction Router() {\n  return (\n    <Routes>\n      <Route path=\"/\" element={<HomePage />} />\n      <Route path=\"/categories\" element={<CategoriesPage />} />\n      <Route path=\"*\" element={<NotFound />} />\n    </Routes>\n  );\n}\n\nexport default Router;\n```\n\n```text\nStaticRouter\n```\n\n```text\nLink\n```\n\n========================================\n\nComments:\n- This Ans is Too much time consuming while first render\n- Thanks it works but there are few errors when building and serving. I mimiced the ssr-react option of create-vite in create-vite-extra and thus changed scripts.build:client in package.json by \"build:client\": \"vite build --ssrManifest --outDir dist/client\" and in server.js : ``` import fs from \"node:fs/promises\"; const templateHtml = isProduction ? await fs.readFile(\"./dist/client/index.html\", \"utf-8\") : \"\"; const ssrManifest = isProduction ? await fs.readFile(\"./dist/client/.vite/ssr-manifest.json\", \"utf-8\") : undefined; ``` And below : template = await fs.readFile('./index.html', 'utf-8')\n- @Heroe__ i Updated Code As Your Request in Github My Repository Checkit Out : github.com/MeetBhingradiya/vite-ssr-with-react-router-dom","metadata":{"transformedAt":"2026-08-18T18:33:46.423Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":38,"totalLines":537,"estimatedTokens":2784}}396{"id":"stack-72374719","source":"stackoverflow","questionId":72374719,"title":"What does the \"typecheck\" npm script in Vue projects using Vite and TS do?","tags":["typescript","vue.js","vite"],"text":"Title: What does the \"typecheck\" npm script in Vue projects using Vite and TS do?\nTags: typescript, vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI created a new Vue project using TypeScript and Vite via\n\n`npm init vue@latest`\n\nInside the package.json file there is a *typecheck* script\n\n```\n\"typecheck\": \"vue-tsc --noEmit -p tsconfig.vitest.json --composite false\",\n```\n\nbut I don't know its purpose. Should I use this script to ensure that my code is fine? ( E.g. for QA workflows )\n\n========================================\n\nCode:\n```text\n\"typecheck\": \"vue-tsc --noEmit -p tsconfig.vitest.json --composite false\",\n```\n\n```text\nnpm init vue@latest\n```\n\n```text\nVite\n```\n\n```text\nTypeScript\n```\n\n```text\nVite\n```\n\n```text\n\"typecheck\"\n```\n\n```text\nTypeScript\n```\n\n```text\n.ts\n```\n\n```text\n.vue\n```\n\n```text\nvue-tsc --noEmit\n```\n\n```text\n\"tsc --noEmit\n```\n\n```text\n.ts\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.423Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":67,"estimatedTokens":218}}397{"id":"stack-76379501","source":"stackoverflow","questionId":76379501,"title":"How to solve React Vite 404 Error on Vercel","tags":["reactjs","oauth","spotify","vite","vercel"],"text":"Title: How to solve React Vite 404 Error on Vercel\nTags: reactjs, oauth, spotify, vite, vercel\nSource: Stack Overflow\n\nQuestion:\nI'm new to Stack Overflow and currently building an application using React Vite. I'm integrating the Spotify API into my application and implementing the Authorization feature using the Authorization Code with PKCE Flow guide provided by Spotify here.\n\nThe application works perfectly fine on my local machine. Now, I'm trying to deploy the app on Vercel. I have set up my environment variables in the Vercel project settings. As per the Spotify documentation, I need to specify the `redirect_uri` to which the OAuth service will redirect the user. I have set the `redirect_uri` value as `http://localhost:5173/callback` in my `.env` file locally. In the Vercel environment variables, I have set the `redirect_uri` value as `https://project.vercel.app/callback`.\n\nHowever, when I run the application on Vercel, the flow works fine until I click the \"Agree\" button on the Spotify service. It then redirects to `https://project.vercel.app/callback?code=...&state=...`, but Vercel gives a 404 Not Found error.\n\nI don't know if the react router is the problem or no, but here's my react router looks like\n\n```\nconst routes = [\n {\n path: \"/callback\",\n Component: AuthCallback,\n }\n]\n\nexport const router = createBrowserRouter([...routes]);\n```\n\nI've tried double check if there's any typo when I specified the `redirect_uri` on my local machine, Vercel environment variable, and Spotify developer dashboard. And I'm sure this is not a typo problem, and I don't really know what causing this issue.\n\nI would greatly appreciate any thoughts or solutions you might have to solve this issue. Thank's.\n\n========================================\n\nCode:\n```ts\nconst routes = [\n   {\n      path: \"/callback\",\n      Component: AuthCallback,\n   }\n]\n\nexport const router = createBrowserRouter([...routes]);\n```\n\n```text\nredirect_uri\n```\n\n```text\nredirect_uri\n```\n\n```text\nhttp://localhost:5173/callback\n```\n\n```text\n.env\n```\n\n```text\nredirect_uri\n```\n\n```text\nhttps://project.vercel.app/callback\n```\n\n```text\nhttps://project.vercel.app/callback?code=...&state=...\n```\n\n```text\nredirect_uri\n```\n\n```json\n{\n    \"rewrites\": [{ \"source\": \"/(.*)\", \"destination\": \"/\" }]\n}\n```\n\n```text\nvercel.json\n```\n\n========================================\n\nComments:\n- This didn't work but I got another error.","metadata":{"transformedAt":"2026-08-18T18:33:46.424Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":88,"estimatedTokens":601}}398{"id":"stack-76774089","source":"stackoverflow","questionId":76774089,"title":"Axios related error when building react app using vite","tags":["reactjs","npm","axios","vite"],"text":"Title: Axios related error when building react app using vite\nTags: reactjs, npm, axios, vite\nSource: Stack Overflow\n\nQuestion:\nAxios was working perfectly in production but when building the application, it results in this error.\n\n```\n> react-app@0.0.0 build\n> vite build\n\nvite v4.4.7 building for production...\n✓ 118 modules transformed.\n✓ built in 1.88s\n[commonjs--resolver] Unexpected token (714:2) in C:/Users/application/client/node_modules/axios/lib/utils.js\nfile: C:/Users/application/client/node_modules/axios/lib/utils.js:714:2\n712: toFiniteNumber,\n713: findKey,\n714: {}: _global,\n ^\n715: isContextDefined,\n716: ALPHABET,\nerror during build:\nSyntaxError: Unexpected token (714:2) in C:/Users/application/client/node_modules/axios/lib/utils.js\n at pp$4.raise\n```\n\nTried update npm, deleted node modules and installed dependencies again and updated all dependencies including axios\n\n========================================\n\nTop Answer:\nI have defined\n\ndefine: { global: 'globalThis'}\n\nand after that it works fine. It works locally and in production. \"define: { _global: ({}), }\", this only work for production but not for development. and \"define: { global: ({}), }\" this works for local but not for production. so the following solution works for both.\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n define: { global: 'globalThis'} \n})\n```\n\n========================================\n\nCode:\n```text\n> react-app@0.0.0 build\n> vite build\n\nvite v4.4.7 building for production...\n✓ 118 modules transformed.\n✓ built in 1.88s\n[commonjs--resolver] Unexpected token (714:2) in C:/Users/application/client/node_modules/axios/lib/utils.js\nfile: C:/Users/application/client/node_modules/axios/lib/utils.js:714:2\n712:   toFiniteNumber,\n713:   findKey,\n714:   {}: _global,\n       ^\n715:   isContextDefined,\n716:   ALPHABET,\nerror during build:\nSyntaxError: Unexpected token (714:2) in C:/Users/application/client/node_modules/axios/lib/utils.js\n    at pp$4.raise\n```\n\n```text\ndefine: { _global: ({}), }\n```\n\n```text\n_global\n```\n\n```text\nglobal\n```\n\n```text\naxios\n```\n\n```text\n_global\n```\n\n```text\nvite.config\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n   plugins: [react()],\n   define: { global: 'globalThis'}  \n})\n```\n\n```text\n<script>var global = global || window; </script>\n```\n\n```text\nvite.config\n```\n\n```text\nUncaught ReferenceError: global is not defined\n```\n\n```text\nglobal\n```\n\n========================================\n\nComments:\n- Omg thank you, that fixed it for me! This was driving me crazy.","metadata":{"transformedAt":"2026-08-18T18:33:46.424Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":127,"estimatedTokens":682}}399{"id":"stack-73180352","source":"stackoverflow","questionId":73180352,"title":"How can I use a custom build of CKEditor 5 with React and Vite?","tags":["vite","ckeditor5","ckeditor5-react"],"text":"Title: How can I use a custom build of CKEditor 5 with React and Vite?\nTags: vite, ckeditor5, ckeditor5-react\nSource: Stack Overflow\n\nQuestion:\nFor the past several months, I've been building my app with Create React App.\n\nHowever, Ionic now supports Vite and I am attempting to migrate my app from CRA to Vite.\n\nOriginally, I made a CKEditor 5 Custom Build and set it up in a React app like this:\n\n```\nimport React from 'react';\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore Ckeditor does not supply TypeScript typings.\nimport { CKEditor } from '@ckeditor/ckeditor5-react';\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore Ckeditor does not supply TypeScript typings.\nimport Editor from 'ckeditor5-custom-build/build/ckeditor';\n```\n\nBefore building my app, I build the custom CKEditor like this:\n\n`cd ckeditor5; npm run build`\n\nThe CKEditor build command is `webpack --mode production`.\n\nNow, after configuring Vite, when I run `npm run build`, I get the following error:\n\n'default' is not exported by ckeditor5/build/ckeditor.js, imported by\nsrc/components/contentTypeCard/CKEditorInput.tsx\n\nThe CKEditor issue queue has a thread on a lack of documentation on issues with Vite, but there's nothing in particular about how to resolve this issue.\n\n### What I tried\n\nI tried building CKEditor in development mode (`webpack --mode development`) and examining the `ckeditor.js` file to try to export Editor, but the file has over 100,000 lines of code and I am totally lost.\n\n========================================\n\nTop Answer:\nIn my case it:\n\n\"react\": \"18.2.0\",\n\"vite\": \"2.9.10\",\n\n**Here is the solution that I found**:\n\npackage.json\n\n```\n\"ckeditor5-custom-build\": \"file:libs/ckeditor5\",\n```\n\nvite.config.ts\n\n```\nexport default defineConfig(() => {\n return {\n plugins: [react()],\n optimizeDeps: {\n include: ['ckeditor5-custom-build'],\n },\n build: {\n commonjsOptions: { exclude: ['ckeditor5-custom-build'], include: [] },\n },\n };\n});\n```\n\nRichTextEditor.tsx\n\n```\nimport { CKEditor, CKEditorProps } from '@ckeditor/ckeditor5-react';\nimport Editor from 'ckeditor5-custom-build';\n\nexport function RichTextEditor({\n defaultValue,\n ...props\n}: RichTextEditorProps) {\n return (\n \n \n \n );\n}\n```\n\n**Update for vite 4.4.8:**\n\n\"vite\": \"4.4.8\",\n\nvite.config.ts\n\n```\nimport commonjs from \"vite-plugin-commonjs\";\n\nexport default defineConfig(() => {\n return {\n plugins: [\n react(),\n commonjs({\n filter(id) {\n if ([\"libs/ckeditor5/build/ckeditor.js\"].includes(id)) {\n return true;\n }\n },\n }),\n ],\n optimizeDeps: {\n include: [\"ckeditor5-custom-build\"],\n },\n build: {\n commonjsOptions: { exclude: [\"ckeditor5-custom-build\"] },\n },\n };\n});\n```\n\n========================================\n\nCode:\n```text\nimport React from 'react';\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore  Ckeditor does not supply TypeScript typings.\nimport { CKEditor } from '@ckeditor/ckeditor5-react';\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore  Ckeditor does not supply TypeScript typings.\nimport Editor from 'ckeditor5-custom-build/build/ckeditor';\n```\n\n```text\ncd ckeditor5; npm run build\n```\n\n```text\nwebpack --mode production\n```\n\n```text\nnpm run build\n```\n\n```text\nwebpack --mode development\n```\n\n```text\nckeditor.js\n```\n\n```text\nimport Essentials from '@ckeditor/ckeditor5-essentials/src/essentials';\nimport Bold from '@ckeditor/ckeditor5-basic-styles/src/bold';\nimport FontSize from '@ckeditor/ckeditor5-font/src/fontsize';\nimport Link from '@ckeditor/ckeditor5-link/src/link';\nimport Paragraph from '@ckeditor/ckeditor5-paragraph/src/paragraph';\nimport Underline from '@ckeditor/ckeditor5-basic-styles/src/underline';\n\n    const editorConfig = {\n      fontSize: {\n        // Excludes \"tiny\" and \"huge\".\n        options: ['small', 'default', 'big'],\n      },\n      plugins: [Bold, Essentials, FontSize, Link, Paragraph, Underline],\n      toolbar: [\n        'bold',\n        'underline',\n        'fontsize',\n        '|',\n        'link',\n        '|',\n        'undo',\n        'redo',\n      ],\n    };\n    \n    export default editorConfig;\n```\n\n```text\nimport { CKEditor } from '@ckeditor/ckeditor5-react';\nimport ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor';\nimport editorConfig from '../../constants/CKEditor/editorConfig';\n\n  <CKEditor\n    editor={ClassicEditor}\n    config={editorConfig}\n    data={myData}\n  />\n```\n\n```text\npackage.json\n```\n\n```text\nckeditor5-custom-build\n```\n\n```text\ndepedencies\n```\n\n```text\npackage.json\n```\n\n```text\nsrc/ckeditor.ts\n```\n\n```text\neditorConfig.ts\n```\n\n```text\n\"ckeditor5-custom-build\": \"file:libs/ckeditor5\",\n```\n\n```text\nexport default defineConfig(() => {\n  return {\n    plugins: [react()],\n    optimizeDeps: {\n      include: ['ckeditor5-custom-build'],\n    },\n    build: {\n      commonjsOptions: { exclude: ['ckeditor5-custom-build'], include: [] },\n    },\n  };\n});\n```\n\n```text\nimport { CKEditor, CKEditorProps } from '@ckeditor/ckeditor5-react';\nimport Editor from 'ckeditor5-custom-build';\n\nexport function RichTextEditor({\n  defaultValue,\n  ...props\n}: RichTextEditorProps) {\n  return (\n    <EditorContainer>\n      <CKEditor editor={Editor} data={defaultValue || ''} {...props} />\n    </EditorContainer>\n  );\n}\n```\n\n```text\nimport commonjs from \"vite-plugin-commonjs\";\n\nexport default defineConfig(() => {\n  return {\n    plugins: [\n      react(),\n      commonjs({\n        filter(id) {\n          if ([\"libs/ckeditor5/build/ckeditor.js\"].includes(id)) {\n            return true;\n          }\n        },\n      }),\n    ],\n    optimizeDeps: {\n      include: [\"ckeditor5-custom-build\"],\n    },\n    build: {\n      commonjsOptions: { exclude: [\"ckeditor5-custom-build\"] },\n    },\n  };\n});\n```\n\n```text\noutput: {\n    // The name under which the editor will be exported.\n    library: 'ClassicEditor',\n    path: path.resolve(__dirname, 'build'),\n    filename: 'ckeditor.js',\n    libraryTarget: 'umd',\n    libraryExport: 'default',  \n }\n```\n\n```text\noutput: {\n    path: path.resolve(__dirname, 'build'),\n    filename: 'ckeditor.js',\n    library: {\n      type: 'module',\n    },\n  },\n  experiments: {\n    outputModule: true,\n  }\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.424Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":299,"estimatedTokens":1542}}400{"id":"stack-75223984","source":"stackoverflow","questionId":75223984,"title":"Change svg color with vite-plugin-svgr","tags":["reactjs","svg","vite","emotion"],"text":"Title: Change svg color with vite-plugin-svgr\nTags: reactjs, svg, vite, emotion\nSource: Stack Overflow\n\nQuestion:\nI'm using vite with emotion and vite-plugin-svgr. I want to change the color of `MyIcon`. I've tried fill, color etc. but it's not working. What am I supposed to do?\n\n```\nimport { ReactComponent as MyIcon } from \"../icons/dummy.svg\";\n\nfunction MyComponent() {\n const icon = css({\n fill: \"blue\", // this is not working\n });\n\n return ;\n}\n```\n\n```\n\n \n\n```\n\n========================================\n\nTop Answer:\nSame answer as Julians but with examples.\n\nReplace your color values with `replaceAttrValues` in `vite.config.ts`:\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport svgr from 'vite-plugin-svgr'\n\nexport default defineConfig({\n plugins: [\n react(),\n svgr({\n svgrOptions: {\n replaceAttrValues: {\n '#000': 'currentColor',\n '#000000': 'currentColor', // In my project, all icons are black by default so I just stick to replacing black colors\n },\n },\n }),\n ],\n}\n```\n\nThen you can use the Icon as follows:\n\n```\nimport IconCircle from 'assets/icons/circle.svg?react' \n\n```\n\n**Note:** Remember the `?react` when you import the icon\n\n**Alternatives:**\n\nYou can manually replace the .svg-file's property `fill` to `currentColor`:\n\n```\n\n \n```\n\nYou can do the `replaceAttrValues` instead of `vite.config.ts` in an `.svgrrc`-file in the root of your project replacing the color value to `currentColor`:\n\n```\n{\n \"replaceAttrValues\": {\n \"#000000\": \"currentColor\",\n \"#000\": \"currentColor\"\n }\n}\n```\n\n========================================\n\nCode:\n```js\nimport { ReactComponent as MyIcon } from \"../icons/dummy.svg\";\n\nfunction MyComponent() {\n  const icon = css({\n    fill: \"blue\", // this is not working\n  });\n\n  return <MyIcon css={icon} />;\n}\n```\n\n```html\n<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"64\" height=\"64\" viewBox=\"0 0 64 64\" fill=\"#FF0000\">\n    <path d=\"...\" style=\"fill: rgb(0, 0, 0);\"/> \n</svg>\n```\n\n```text\nMyIcon\n```\n\n```text\nfill\n```\n\n```text\ncurrentColor\n```\n\n```text\nconvertStyleToAttrs\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport svgr from 'vite-plugin-svgr'\n\nexport default defineConfig({\n  plugins: [\n    react(),\n    svgr({\n      svgrOptions: {\n        replaceAttrValues: {\n          '#000': 'currentColor',\n          '#000000': 'currentColor', // In my project, all icons are black by default so I just stick to replacing black colors\n        },\n      },\n    }),\n  ],\n}\n```\n\n```text\nimport IconCircle from 'assets/icons/circle.svg?react' \n\n<IconCheckmark color=\"red\" />\n```\n\n```text\n<svg viewBox=\"0 0 32 32\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n  <circle cx=\"16\" cy=\"16\" r=\"14\" fill=\"#000000\" /> <--- Before\n  <circle cx=\"16\" cy=\"16\" r=\"14\" fill=\"currentColor\" /> <--- After\n</svg>\n```\n\n```text\n{\n  \"replaceAttrValues\": {\n    \"#000000\": \"currentColor\",\n    \"#000\": \"currentColor\"\n  }\n}\n```\n\n```text\nreplaceAttrValues\n```\n\n```text\nvite.config.ts\n```\n\n```text\n?react\n```\n\n```text\nfill\n```\n\n```text\ncurrentColor\n```\n\n```text\nreplaceAttrValues\n```\n\n```text\nvite.config.ts\n```\n\n```text\n.svgrrc\n```\n\n```text\ncurrentColor\n```\n\n========================================\n\nComments:\n- Is your icon included as an inlined `` (inspect it in dev tools) or as an `` (you can't access fill im images)?\n- SVGR uses . Fill is just a placeholder for a correct solution to the problem.\n- So you see a rendered icon but ... black (default fill color) or in another color? Please your rendered HTML/svg output (copy the lement via dev tools inspection) as a snippet. Keep in mind there's a good chance, your icon svg asset file has some flaws e.g by applying a `fill:none` to the parent svg while having specific fills for `` elements – so you would have some css specificity issues.\n- vite-plugin-svgr applies a fill to the path element. I've edited my question with the html part.","metadata":{"transformedAt":"2026-08-18T18:33:46.424Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":203,"estimatedTokens":974}}401{"id":"stack-69837637","source":"stackoverflow","questionId":69837637,"title":"Dynamic assets in Nuxt / vite","tags":["javascript","nuxt.js","require","vite"],"text":"Title: Dynamic assets in Nuxt / vite\nTags: javascript, nuxt.js, require, vite\nSource: Stack Overflow\n\nQuestion:\nI can load images dynamically from a folder in Nuxt (+ webpack) simply with a method like:\n\n```\ngetServiceIcon(iconName) {\n return require ('../../static/images/svg/services/' + iconName + '.svg');\n}\n```\n\nI moved to Vite, and `require` is not defined here (using rollup). How can I solve this, with nuxt / vite? Any idea?\n\n========================================\n\nCode:\n```text\ngetServiceIcon(iconName) {\n  return require ('../../static/images/svg/services/' + iconName + '.svg');\n}\n```\n\n```text\nrequire\n```\n\n```js\nconst getServiceIcon = async iconName => {\n  const module = await import(/* @vite-ignore */ `../../static/images/svg/services/${iconName}.svg`)\n  return module.default.replace(/^\\/@fs/, '')\n}\n```\n\n```text\nimport()\n```\n\n========================================\n\nComments:\n- You're using Nuxt3? github.com/nuxt/framework/discussions/868\n- Nope, 2.15.8. Ty, looking into it tho.\n- Then, you can maybe ask your question down in the related repo: github.com/nuxt/vite/issues?q=is%3Aissue+images+\n- Facing this error - `Uncaught (in promise) TypeError: Failed to fetch dynamically imported module`\n- Why the @vite-ignore ?\n- @Tofandel To prevent the asset from being automatically bundled.","metadata":{"transformedAt":"2026-08-18T18:33:46.424Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":48,"estimatedTokens":328}}402{"id":"stack-72043141","source":"stackoverflow","questionId":72043141,"title":"Vue 2 Vite app: Failed to parse source for import analysis","tags":["vue.js","vite"],"text":"Title: Vue 2 Vite app: Failed to parse source for import analysis\nTags: vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI'm currently setting up a vue 2 application with vite.\n\nI'm getting this error. I would like to set the project up in vue 2. I understand it's built for vue 3, but is there something I'm missing?\n\nhttps://i.sstatic.net/kK0ZQ.png\n\nvite config\n\n```\nimport { minifyHtml, injectHtml } from 'vite-plugin-html'\n import legacy from '@vitejs/plugin-legacy'\n const path = require('path')\n const { createVuePlugin } = require('vite-plugin-vue2')\n\n module.exports = {\n plugins: [\n createVuePlugin(),\n minifyHtml(),\n injectHtml({\n injectData: {\n title: 'ProjectName',\n description: 'A single page application created using Vue.js'\n }\n }),\n legacy({\n targets: ['ie >= 11'],\n additionalLegacyPolyfills: ['regenerator-runtime/runtime']\n })\n ],\n resolve: {\n alias: {\n '@': path.resolve(__dirname, '/src'),\n '~bootstrap': 'bootstrap'\n }\n },\n css: {\n preprocessorOptions: {\n scss: {\n additionalData: `@import \"./src/scss/variables\";`\n }\n }\n }\n }\n```\n\nMy folder structure:\n\nhttps://i.sstatic.net/GrLZk.png\n\nmy package.json\n\n```\n{\n \"name\": \"co\",\n \"private\": true,\n \"version\": \"0.0.0\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\"\n },\n \"devDependencies\": {\n \"@fullhuman/postcss-purgecss\": \"^4.1.3\",\n \"@vitejs/plugin-legacy\": \"^1.8.1\",\n \"@vitejs/plugin-vue\": \"^1.6.1\",\n \"autoprefixer\": \"^10.4.5\",\n \"postcss\": \"^8.4.12\",\n \"sass\": \"~1.32.13\",\n \"vite\": \"^2.9.6\",\n \"vite-plugin-vue2\": \"^1.9.0\",\n \"vue-template-compiler\": \"^2.6.11\"\n },\n \"dependencies\": {\n \"bootstrap\": \"^4.6.0\",\n \"eslint\": \"^8.14.0\",\n \"eslint-plugin-vue\": \"^8.7.1\",\n \"vue\": \"^2.6.11\",\n \"vue-router\": \"^3.2.0\"\n }\n }\n```\n\n========================================\n\nTop Answer:\nAfter installing a fresh copy of Laravel 9 I face the same issue. So here is solution.\n\nMake sure you added these two packages in package.json\n\n```\n\"@vitejs/plugin-vue\": \"^3.2.0\",\n\"vite\": \"^3.0.0\",\n```\n\nChange vite.config.js\n\n```\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\nimport vue from '@vitejs/plugin-vue';\n\nexport default defineConfig({\n plugins: [\n laravel({\n input: [\n 'resources/sass/app.scss',\n 'resources/js/app.js',\n ],\n refresh: true,\n }),\n vue({\n template: {\n transformAssetUrls: {\n base: null,\n includeAbsolute: false,\n },\n },\n }),\n ],\n resolve: {\n alias: {\n vue: 'vue/dist/vue.esm-bundler.js',\n },\n },\n});\n```\n\nFinally run: `npm install` and then `npm run dev`\n\nOpen a new terminal and run `php artisan serve`\n\nIt should work now:\nhttp://127.0.0.1:8000/\n\n========================================\n\nCode:\n```text\nimport { minifyHtml, injectHtml } from 'vite-plugin-html'\n  import legacy from '@vitejs/plugin-legacy'\n  const path = require('path')\n  const { createVuePlugin } = require('vite-plugin-vue2')\n\n  module.exports = {\n    plugins: [\n      createVuePlugin(),\n      minifyHtml(),\n      injectHtml({\n        injectData: {\n          title: 'ProjectName',\n          description: 'A single page application created using Vue.js'\n        }\n      }),\n      legacy({\n        targets: ['ie >= 11'],\n        additionalLegacyPolyfills: ['regenerator-runtime/runtime']\n      })\n    ],\n    resolve: {\n      alias: {\n        '@': path.resolve(__dirname, '/src'),\n        '~bootstrap': 'bootstrap'\n      }\n    },\n    css: {\n      preprocessorOptions: {\n        scss: {\n          additionalData: `@import \"./src/scss/variables\";`\n        }\n      }\n    }\n  }\n```\n\n```text\n{\n      \"name\": \"co\",\n      \"private\": true,\n      \"version\": \"0.0.0\",\n      \"scripts\": {\n        \"dev\": \"vite\",\n        \"build\": \"vite build\",\n        \"preview\": \"vite preview\"\n      },\n      \"devDependencies\": {\n        \"@fullhuman/postcss-purgecss\": \"^4.1.3\",\n        \"@vitejs/plugin-legacy\": \"^1.8.1\",\n        \"@vitejs/plugin-vue\": \"^1.6.1\",\n        \"autoprefixer\": \"^10.4.5\",\n        \"postcss\": \"^8.4.12\",\n        \"sass\": \"~1.32.13\",\n        \"vite\": \"^2.9.6\",\n        \"vite-plugin-vue2\": \"^1.9.0\",\n        \"vue-template-compiler\": \"^2.6.11\"\n      },\n      \"dependencies\": {\n        \"bootstrap\": \"^4.6.0\",\n        \"eslint\": \"^8.14.0\",\n        \"eslint-plugin-vue\": \"^8.7.1\",\n        \"vue\": \"^2.6.11\",\n        \"vue-router\": \"^3.2.0\"\n      }\n    }\n```\n\n```text\nimport { defineConfig } from \"vite\";\n          import { createVuePlugin as vue } from \"vite-plugin-vue2\";\n\n          // https://vitejs.dev/config/const \n          const path = require(\"path\");\n          export default defineConfig({\n            plugins: [vue()],\n            resolve: {\n              extensions: [\n                \".mjs\",\n                \".js\",\n                \".ts\",\n                \".jsx\",\n                \".tsx\",\n                \".json\",\n                \".vue\",\n                \".scss\",\n              ],\n              alias: {\n                \"@\": path.resolve(__dirname, \"./src\"),\n                json2csv: \"json2csv/dist/json2csv.umd.js\",\n                '~bootstrap': 'bootstrap'\n              },\n            },\n            css: {\n              preprocessorOptions: {\n                scss: {\n                  //  additionalData: `@import \"@/scss/app.scss\";`,\n                  additionalData: `@import \"src/scss/_variables.scss\";`,\n                },\n              },\n            },\n            server: {\n              port: 8090,\n            },\n          });\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue()]\n})\n```\n\n```text\nvite.config.js\n```\n\n```text\npackage.json\n```\n\n```text\n\"@vitejs/plugin-vue\": \"^3.2.0\",\n\"vite\": \"^3.0.0\",\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\nimport vue from '@vitejs/plugin-vue';\n\nexport default defineConfig({\n    plugins: [\n        laravel({\n            input: [\n                'resources/sass/app.scss',\n                'resources/js/app.js',\n            ],\n            refresh: true,\n        }),\n        vue({\n            template: {\n                transformAssetUrls: {\n                    base: null,\n                    includeAbsolute: false,\n                },\n            },\n        }),\n    ],\n    resolve: {\n        alias: {\n            vue: 'vue/dist/vue.esm-bundler.js',\n        },\n    },\n});\n```\n\n```text\nnpm install\n```\n\n```text\nnpm run dev\n```\n\n```text\nphp artisan serve\n```\n\n========================================\n\nComments:\n- This can have several causes. One being you have a syntax error somewhere (missing curly braces for example). There's a issue on github about this: github.com/nuxt/vite/issues/115\n- Thanks for this; adding `extensions: etc` to my vite config meant the compiler flagged up the real error :)","metadata":{"transformedAt":"2026-08-18T18:33:46.424Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":320,"estimatedTokens":1676}}403{"id":"stack-76783532","source":"stackoverflow","questionId":76783532,"title":"Vite: Is there a possibility to exclude code elements from being built?","tags":["javascript","vue.js","nuxt.js","vite"],"text":"Title: Vite: Is there a possibility to exclude code elements from being built?\nTags: javascript, vue.js, nuxt.js, vite\nSource: Stack Overflow\n\nQuestion:\nI'm looking for a \"feature\" in Vite which will allow me to exclude some code from being built. As far as I remember in webpack there was a feature when you could create some comments like:\n\n```\n###SOMETHING\n`###END_SOMETHING\n```\n\nand this code between ###SOMETHING and ###END_SOMETHING wasn't included in output files during build process. Is there relative feature available in Vite or maybe there is another way to perform such a action? Basically code between these \"tags\" needs to be in file and working during vite dev`, but it needs to be omitted by `vite build`.\n\nI've found rollup settings but it only includes whole files.\n\n========================================\n\nCode:\n```js\n###SOMETHING\n<code goes here>\n###END_SOMETHING\n```\n\n```text\nvite dev\n```\n\n```text\nvite build\n```\n\n```text\nif (import.meta.env.DEV) {\n    // code runs in vite dev\n}\n```\n\n```text\nimport.meta.env\n```\n\n```text\nvite dev\n```\n\n```text\nvite build\n```\n\n```text\n--mode\n```\n\n```text\nimport.meta.env.DEV\n```\n\n========================================\n\nComments:\n- are you thinking about `&#47;*` and `*&#47;`?\n- No no, I don't want code to be commented, I want it to be working, but just omitted while built.\n- what does it mean? If you don't include code in the build it won't work.\n- As I said in the post, code needs to be there in source file and needs to be working during `vite dev`, it just needs to be omitted while using `vite build`. I've updated the post so it's now more clear what do I mean. :)\n- There's also the `dropLabels` option in esbuild, but for some reason it doesn't seem to work with the current version of Vite. I posted a separate (but related) question about this here: Can I get Vite to drop certain lines of code using the 'dropLabels' option?\n- Thank you, it should do the job. :)\n- If it is also necessary to exclude some imports in some build environments (specifically in SSR or non-SSR contexts), the plugin `vite-plugin-iso-import` will make that possible: github.com/bluwy/vite-plugin-iso-import\n- But this will generate a `if (false)` in production code!\n- @Paper_Folding which allows the bundler to optimize the whole block away during treeshaking\n- Okay, I also find another way, because mostly I'm using console to logging, setting `build.rolldownOptions.output.minify.compress.dropConsole` to `true` also suits my need.","metadata":{"transformedAt":"2026-08-18T18:33:46.424Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":72,"estimatedTokens":622}}404{"id":"stack-77223992","source":"stackoverflow","questionId":77223992,"title":"Vitest loads cjs export of dependency instead of esm","tags":["javascript","vite","es6-modules","commonjs","vitest"],"text":"Title: Vitest loads cjs export of dependency instead of esm\nTags: javascript, vite, es6-modules, commonjs, vitest\nSource: Stack Overflow\n\nQuestion:\nI have a `node_modules` package that exports\n\n```\n\"main\": \"dist/cjs/index.js\",\n\"module\": \"dist/esm/index.js\",\n\"types\": \"dist/types/index.d.ts\"\n```\n\nWhere the `cjs` export had been built with `tsc --module commonjs` and the `esm` export has been built with `tsc --module esnext`\n\nThe consumer app is set as `\"type\": \"module\"`\n\nNow, `vite` correctly loads the `dist/esm/` export of the package, but `vitest` loads the `dist/cjs/` export.\n\nThis causes issues with the tests, that I can resolve if for example I manually edit the `package.json` of the package to `\"main\": \"dist/esm/index.js\"`\n\nWhy does this happen and is it possible to force `vitest` to consume the `esm` export?\n\n========================================\n\nCode:\n```text\n\"main\": \"dist/cjs/index.js\",\n\"module\": \"dist/esm/index.js\",\n\"types\": \"dist/types/index.d.ts\"\n```\n\n```text\nnode_modules\n```\n\n```text\ncjs\n```\n\n```text\ntsc --module commonjs\n```\n\n```text\nesm\n```\n\n```text\ntsc --module esnext\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\nvite\n```\n\n```text\ndist/esm/\n```\n\n```text\nvitest\n```\n\n```text\ndist/cjs/\n```\n\n```text\npackage.json\n```\n\n```text\n\"main\": \"dist/esm/index.js\"\n```\n\n```text\nvitest\n```\n\n```text\nesm\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.424Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":87,"estimatedTokens":331}}405{"id":"stack-76755864","source":"stackoverflow","questionId":76755864,"title":"Supabase not storing session data in localstorage correctly","tags":["reactjs","vite","supabase"],"text":"Title: Supabase not storing session data in localstorage correctly\nTags: reactjs, vite, supabase\nSource: Stack Overflow\n\nQuestion:\nI have a vite + react + supabase application and I have a simple signup/login form. Signup and login seem to be working, except that session data is not being stored in localstorage (it's my understanding that it should).\n\nSo, refreshing the page does not keep user authenticated. I followed the tutorial to the T, so I'm not sure what would be keeping supabase from handling this correctly? Are there any gotchas I should be worried about?\n\nHere's how supabaseClient.js file\n\n```\nimport { createClient } from '@supabase/supabase-js'\n\nconst supabaseUrl = import.meta.env.VITE_SUPABASE_URL\nconst supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY\n\nexport const supabase = createClient(supabaseUrl, supabaseAnonKey)\n```\n\nAnd here's how I'm trying to reference the authenticated session\n\n```\nimport { useEffect, useState } from \"react\"\nimport { supabase } from \"../supabaseClient\"\n\nexport default function useAuth () {\n const [session, setSession] = useState(null)\n\n useEffect(() => {\n supabase.auth.getSession().then(({ data: { session } }) => {\n setSession(session)\n })\n \n supabase.auth.onAuthStateChange((_event, session) => {\n setSession(session)\n })\n }, [])\n\n console.log('session ', session)\n\n return {\n session\n }\n}\n```\n\nI then reference the hook in whatever component I want to use the user session in. It's just null every time. I verified in supabase client that the user gets created/logged in though. Thanks in advance!\n\n========================================\n\nCode:\n```text\nimport { createClient } from '@supabase/supabase-js'\n\nconst supabaseUrl = import.meta.env.VITE_SUPABASE_URL\nconst supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY\n\nexport const supabase = createClient(supabaseUrl, supabaseAnonKey)\n```\n\n```text\nimport { useEffect, useState } from \"react\"\nimport { supabase } from \"../supabaseClient\"\n\nexport default function useAuth () {\n    const [session, setSession] = useState(null)\n\n    useEffect(() => {\n        supabase.auth.getSession().then(({ data: { session } }) => {\n          setSession(session)\n        })\n    \n        supabase.auth.onAuthStateChange((_event, session) => {\n          setSession(session)\n        })\n      }, [])\n\n    console.log('session ', session)\n\n    return {\n        session\n    }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.424Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":85,"estimatedTokens":597}}406{"id":"stack-74680419","source":"stackoverflow","questionId":74680419,"title":"Dockerized Sveltkit app: Hot reload not working","tags":["docker","docker-compose","svelte","vite","sveltekit"],"text":"Title: Dockerized Sveltkit app: Hot reload not working\nTags: docker, docker-compose, svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nWith the help from SO community I was finally able to dockerize my Sveltekit app and access it from the browser (this was an issue initially). So far so good, but now every time I perform a code change I need to re-build and redeploy my container which obviously is not acceptable. Hot reload is not working, I've been trying multiple things I've found online but none of them have worked so far.\n\nHere's my `Dockerfile`:\n\n```\nFROM node:19-alpine\n\n# Set the Node environment to development to ensure all packages are installed\nENV NODE_ENV development\n\n# Change our current working directory\nWORKDIR /app\n\n# Copy over `package.json` and lock files to optimize the build process\nCOPY package.json package-lock.json ./\n# Install Node modules\nRUN npm install\n\n# Copy over rest of the project files\nCOPY . .\n\n# Perhaps we need to build it for production, but apparently is not needed to run dev script.\n# RUN npm run build\n\n# Expose port 3000 for the SvelteKit app and 24678 for Vite's HMR\nEXPOSE 3333\nEXPOSE 8080\nEXPOSE 24678\n\nCMD [\"npm\", \"run\", \"dev\"]\n```\n\nMy `docker-compose`:\n\n```\nversion: \"3.9\"\n\nservices:\n dmc-web:\n build:\n context: .\n dockerfile: Dockerfile\n container_name: dmc-web\n restart: always\n ports:\n - \"3000:3000\"\n - \"3010:3010\"\n - \"8080:8080\"\n - \"5050:5050\"\n - \"24678:24678\"\n volumes:\n - ./:/var/www/html\n```\n\nthe scripts from my `package.json`:\n\n```\n\"scripts\": {\n \"dev\": \"vite dev --host 0.0.0.0\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\",\n \"test\": \"playwright test\",\n \"lint\": \"prettier --check . && eslint .\",\n \"format\": \"prettier --write .\"\n },\n```\n\nand my `vite.config.js`:\n\n```\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport {defineConfig} from \"vite\";\n\nexport default defineConfig({\n plugins: [sveltekit()],\n server: {\n watch: {\n usePolling: true,\n },\n host: true, // needed for the DC port mapping to work\n strictPort: true,\n port: 8080,\n }\n});\n```\n\nany idea what am I missing? I can reach my app at `http://localhost:8080` but cannot get to reload the app when a code change happens.\n\nThanks.\n\n========================================\n\nTop Answer:\nI had the same problem while trying to use Svelte 5 and Docker Desktop.\n@sungryeol answer was half the way to my solution. After reading the comments, I enabled the usePooling option and now it is working as desired.\n\nHere are my configuration:\n\nDockerfile:\n\n```\nFROM node:23.3-alpine3.19\n \nWORKDIR /app\n \nCOPY package.json package-lock.json ./\nRUN npm install\n```\n\ncompose.yaml\n\n```\nservices:\n seligai_front_app:\n container_name: seligai_front_app\n build:\n context: .\n ports:\n - 5173:5173\n volumes:\n - /app/node_modules\n - .:/app\n command: npm run dev -- --host 0.0.0.0\n```\n\nvite.config.ts\n\n```\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n plugins: [sveltekit()],\n server: {\n watch: {\n usePolling: true,\n },\n },\n});\n```\n\nHope it helps someone.\n\n========================================\n\nCode:\n```text\nFROM node:19-alpine\n\n# Set the Node environment to development to ensure all packages are installed\nENV NODE_ENV development\n\n# Change our current working directory\nWORKDIR /app\n\n# Copy over `package.json` and lock files to optimize the build process\nCOPY  package.json package-lock.json ./\n# Install Node modules\nRUN npm install\n\n# Copy over rest of the project files\nCOPY . .\n\n# Perhaps we need to build it for production, but apparently is not needed to run dev script.\n# RUN npm run build\n\n# Expose port 3000 for the SvelteKit app and 24678 for Vite's HMR\nEXPOSE 3333\nEXPOSE 8080\nEXPOSE 24678\n\nCMD [\"npm\", \"run\", \"dev\"]\n```\n\n```text\nversion: \"3.9\"\n\nservices:\n  dmc-web:\n    build:\n      context: .\n      dockerfile: Dockerfile\n    container_name: dmc-web\n    restart: always\n    ports:\n      - \"3000:3000\"\n      - \"3010:3010\"\n      - \"8080:8080\"\n      - \"5050:5050\"\n      - \"24678:24678\"\n    volumes:\n      - ./:/var/www/html\n```\n\n```text\n\"scripts\": {\n        \"dev\": \"vite dev --host 0.0.0.0\",\n        \"build\": \"vite build\",\n        \"preview\": \"vite preview\",\n        \"test\": \"playwright test\",\n        \"lint\": \"prettier --check . && eslint .\",\n        \"format\": \"prettier --write .\"\n    },\n```\n\n```text\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport {defineConfig} from \"vite\";\n\nexport default defineConfig({\n    plugins: [sveltekit()],\n    server: {\n        watch: {\n            usePolling: true,\n        },\n        host: true, // needed for the DC port mapping to work\n        strictPort: true,\n        port: 8080,\n    }\n});\n```\n\n```text\nDockerfile\n```\n\n```text\ndocker-compose\n```\n\n```text\npackage.json\n```\n\n```text\nvite.config.js\n```\n\n```text\nhttp://localhost:8080\n```\n\n```yaml\n# 🚨wrong\n    volumes:\n      - ./:/var/www/html\n# ✅answer\n    volumes:\n      # it avoids mounting the workspace root\n      # because it may cause OS specific node_modules folder\n      # or build folder(.svelte-kit) to be mounted.\n      # they conflict with the temporary results from docker space.\n      # this is why many mono repos utilize ./src folder\n      - ./src:/home/node/app/src\n      - ./static:/home/node/app/static\n      - ./vite.config.js:/home/node/app/vite.config.js\n      - ./tsconfig.json:/home/node/app/tsconfig.json\n      - ./svelte.config.js:/home/node/app/svelte.config.js\n```\n\n```text\n# dockerfile\n\n# 🚨wrong\nCOPY  package.json package-lock.json ./\nRUN npm install\nCOPY . .\n# ...\nCMD [\"npm\", \"run\", \"dev\"]\n\n# ✅answer\nCOPY  package*.json ./\nRUN npm install\n# comment out COPY and CMD\n# COPY . .\n# ...\n# CMD [\"npm\", \"run\", \"dev\"]\n```\n\n```yaml\n# docker-compose.yaml\nservices:\n  svelte:\n    # ...\n    command: npm dev\n```\n\n```text\n# docker-compose.yaml\nvolumes:\n  - ./src:/$YOUR_APP_DIR/src\n  - ./static:/$YOUR_APP_DIR/static\n  # ...\n```\n\n```text\nRUN mkdir -p /home/node/app\nWORKDIR /home/node/app\n```\n\n```text\ndocker-compose.yaml\n```\n\n```text\ndockerfile\n```\n\n```text\nsleep infinity\n```\n\n```text\nCOPY\n```\n\n```text\nCMD\n```\n\n```text\ndocker-compose.yaml\n```\n\n```text\nCMD\n```\n\n```text\n/home/node/app\n```\n\n```text\n/home/node\n```\n\n```text\n/home/node/app\n```\n\n```text\ndocker run -p 8080:8080 -v $(pwd):/src node:19-alpine bash\n```\n\n```text\ncd /src\nnpm install\nnpm run dev\n```\n\n```text\nFROM node:23.3-alpine3.19\n    \nWORKDIR /app\n  \nCOPY package.json package-lock.json ./\nRUN npm install\n```\n\n```yaml\nservices:\n  seligai_front_app:\n    container_name: seligai_front_app\n    build:\n      context: .\n    ports:\n      - 5173:5173\n    volumes:\n      - /app/node_modules\n      - .:/app\n    command: npm run dev -- --host 0.0.0.0\n```\n\n```js\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n    plugins: [sveltekit()],\n    server: {\n        watch: {\n            usePolling: true,\n        },\n    },\n});\n```\n\n========================================\n\nComments:\n- Did you try the hot reload locally without docker?\n- Before dockerizing the app the hot reload was working\n- Docker is used to encapsulate a application's environment requirements for portability. If your host computer is windows and your teammate is linux, you want to use docker.\n- I just did this, but when running it I'm getting `Error: Cannot find module '&#47;app&#47;npm dev'`.\n- @MrCujo did you try run my github demo as it is? it sure does work. the answer is proving points by using my own settings. change the volume accordingly\n- thanks a lot @sungryeol!!! It finally worked! only thing was that I had to remove `command: npm dev` from `docker-compose` and leave instead the `CMD` command in my `Dockerfile`, otherwise I'd get an error saying: `node:internal&#47;modules&#47;cjs&#47;loader:1029 throw err; Error: Cannot find module '&#47;app&#47;npm run dev'` Other than that all your suggestions made it work. I appreciate your help. Wanted to grant you the points but the bounty had expired, I even tried to reinstate it again but couldn't do it.\n- Never mind, was able to open the bounty again, although my previous bounty was for 50 and it didn't let me choose 50 again, had to do it for 100, but what the heck, you deserve it for your help. I have to wait 23 hours before being able to grant it though.\n- Unfortunately it seems like using \"Rancher Desktop\" as a \"Docker Desktop\" alternative also causes file updates not to trigger a reload. I've cloned your git repo and it does not work :( I need to use 'usePolling' setting in vite.config.json.\n- @Leon using Rancher is out of scope of this discussion. You should pose a new question.\n- @MrCujo I think it's 'run': `npm run dev`\n- @Leon did you get anywhere with Rancher Desktop? (same problem)\n- Pasting the link to solution with Rancher Desktop in case anyone hits this thread: stackoverflow.com/q/78443707/5695347\n- I'm guessing you're using Windows Home? And you store your project on the hard drive for Windows? Then, even if you mount, file events in Windows (such as when a file is saved) will not be propagated to the Linux container, and you can fall back to polling, as you suggested. But a better solution is to store the project on the hard drive for the Linux instance instead. Then File events will be propagated as expected.","metadata":{"transformedAt":"2026-08-18T18:33:46.424Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":408,"estimatedTokens":2310}}407{"id":"stack-69573998","source":"stackoverflow","questionId":69573998,"title":"Is there a way to use Vite with HMR and still generate the files in the /dist folder?","tags":["vite"],"text":"Title: Is there a way to use Vite with HMR and still generate the files in the /dist folder?\nTags: vite\nSource: Stack Overflow\n\nQuestion:\nFirst of all, I wanna say that I've started using Vite awhile ago and I'm no Vite expert in any shape or form.\n\nNow, about my problem: I'm working on a Chrome Extension which requires me to have the files generated in the `/dist` folder. That works excellent using `vite build`. But, if I try to use only `vite` (to get the benefits of HMR), no files get generated in the `/dist` folder. So I have no way to load the Chrome Extension.\n\nIf anyone has faced similar issues, or knows a config that I've overlooked, feel free to it here.\n\nThanks!\n\n========================================\n\nCode:\n```text\n/dist\n```\n\n```text\nvite build\n```\n\n```text\nvite\n```\n\n```text\n/dist\n```\n\n```js\n/**\n * Custom Hot Reloading Plugin\n * Start `vite build` on Hot Module Reload\n */\nimport { build } from 'vite'\n\nexport default function HotBuild() {\n\n  let bundling = false\n  const hmrBuild = async () => { \n    bundling = true\n    await build({'build': { outDir: './hot-dist'}}) // <--- you can give a custom config here or remove it to use default options\n  };\n\n  return {\n    name: 'hot-build',\n    enforce: \"pre\",\n    // HMR\n    handleHotUpdate({ file, server }) {\n      if (!bundling) {\n        console.log(`hot vite build starting...`)\n        hmrBuild()\n          .then(() => {\n            bundling = false\n            console.log(`hot vite build finished`)\n          })\n      }  \n      return []\n    }\n  }\n}\n```\n\n```js\nimport HotBuild from './hot-build'\n\n// vite config\n{\n  plugins: [\n    HotBuild()\n  ],\n}\n```\n\n```text\nbuild\n```\n\n```text\nhot-build.ts\n```\n\n```text\nvite.config.js\n```\n\n========================================\n\nComments:\n- Thanx for the idea! But in my test app HMR isn't working anymore with this plugin. Aslo it writes files only on changes within the app code but not on start of the dev server.\n- Hi. Thanks. How can we make js to load from this built assets, not through dev server. My code still loaded from localhost:5173 not from local file. (I need it, bc I have a problem with loading web workers with laravel-vite)\n- @aybjax issue with (service- ?) workers is basically two things, self-signed cert and different origin. For development, a workaround can be to open chrome with the following switch: `chrome.exe\" --user-data-dir=&#47;tmp&#47;foo --ignore-certificate-errors --unsafely-treat-insecure-origin-as-secure=https:&#47;&#47;mydevsite&zwnj;&#8203;.dev`. You can post a new question with your dev details and tag me.\n- stackoverflow.com/questions/74641201/&hellip; was my question, but I seem not to find a solution","metadata":{"transformedAt":"2026-08-18T18:33:46.424Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":96,"estimatedTokens":668}}408{"id":"stack-76527409","source":"stackoverflow","questionId":76527409,"title":"React vitejs Unexpected string","tags":["javascript","reactjs","environment-variables","vite","apollo-client"],"text":"Title: React vitejs Unexpected string\nTags: javascript, reactjs, environment-variables, vite, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI was installing the @apollo/client library in my vite project and when i called\n\n`new InMemoryCache()` from the apollo library i got console error `Uncaught SyntaxError: Unexpected string`\n\nAnd if i clicked on the file where the error comed from (apollo dependency) this wa the red underlined line `((_globalThis$process = globalThis.process) === null || _globalThis$process === void 0 ? void 0 : _globalThis$\"development\") === \"production\" ? function instanceOf2(value, constructor) { return value instanceof constructor;`\n\nI tried so many things, using different cache libraries, changing vite condig js but I couldn't find the solution\n\n========================================\n\nTop Answer:\ni got that error also in 16.7.1.\n\nnode --version v18.16.1\nnpm --version 9.5.1\n\nOnly thing that works right now is to downgrade to 16.6.0 like Mark Kurkowski said!\n\n========================================\n\nCode:\n```text\nnew InMemoryCache()\n```\n\n```text\nUncaught SyntaxError: Unexpected string\n```\n\n```text\n((_globalThis$process = globalThis.process) === null || _globalThis$process === void 0 ? void 0 : _globalThis$\"development\") === \"production\" ? function instanceOf2(value, constructor) { return value instanceof constructor;\n```\n\n```text\ngraphql\n```\n\n========================================\n\nComments:\n- Is there any way you could your project to help us debug this?\n- This seems like it is not a problem with the package itself - do you have any additional bundle config in place?\n- I just want to confirm that downgrading graphql to 16.6.0 fixed the issue. I received this error: `code Uncaught SyntaxError: Unexpected string (at chunk-SALCFXIS.js?v=2629e44a:937:113)` After I downgraded, the error went away.\n- By now, also 16.7.1 has been released which should fix the problem.\n- @phry I am getting this error with `16.8.0`, `16.6.0` works for me\n- It appears the error was not fixed in 16.7.1, it is still occurring in 16.8.1.\n- github.com/graphql/graphql-js/issues/3918","metadata":{"transformedAt":"2026-08-18T18:33:46.424Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":52,"estimatedTokens":530}}409{"id":"stack-65953675","source":"stackoverflow","questionId":65953675,"title":"Import monaco-editor using Vite 2","tags":["vue.js","rollup","rollupjs","vite"],"text":"Title: Import monaco-editor using Vite 2\nTags: vue.js, rollup, rollupjs, vite\nSource: Stack Overflow\n\nQuestion:\nCurrently, I have set up a Vite 2 project with `monaco-editor` as a dependency.\n\nWhenever I am trying to use it says that the workers are not imported.\n\n```\neditorSimpleWorker.js:454 Uncaught (in promise) Error: Unexpected usage\n at EditorSimpleWorker.loadForeignModule (editorSimpleWorker.js:454)\n at webWorker.js:38\n```\n\nSince I am using Vite 2 I have assumed that simply specifying the rollup plugin `rollup-plugin-monaco-editor` in the plugins array. However, I am still getting this issue.\n\n```\nexport default defineConfig({\n plugins: [\n vue(),\n monaco({ languages: ['javascript'] }),\n ],\n});\n```\n\nIs there any proper way to import `monaco-editor` into a Vite 2 project?\n\n========================================\n\nTop Answer:\nThe accepted answer is ok in dev build, but in production build at current version (v2.1.2), `Uncaught ReferenceError: window is not defined` is raised on page load.\n\nSo in addition to the accepted answer, `build.rollupOptions.output.manualChunks` needs to be added to `vite.config.js` like the following.\n\n```\n// vite.config.js\nimport { defineConfig } from 'vite';\nconst prefix = `monaco-editor/esm/vs`;\nexport default defineConfig({\n build: {\n rollupOptions: {\n output: {\n manualChunks: {\n jsonWorker: [`${prefix}/language/json/json.worker`],\n cssWorker: [`${prefix}/language/css/css.worker`],\n htmlWorker: [`${prefix}/language/html/html.worker`],\n tsWorker: [`${prefix}/language/typescript/ts.worker`],\n editorWorker: [`${prefix}/editor/editor.worker`],\n },\n },\n },\n },\n});\n```\n\n========================================\n\nCode:\n```text\neditorSimpleWorker.js:454 Uncaught (in promise) Error: Unexpected usage\n    at EditorSimpleWorker.loadForeignModule (editorSimpleWorker.js:454)\n    at webWorker.js:38\n```\n\n```js\nexport default defineConfig({\n  plugins: [\n    vue(),\n    monaco({ languages: ['javascript'] }),\n  ],\n});\n```\n\n```text\nmonaco-editor\n```\n\n```text\nrollup-plugin-monaco-editor\n```\n\n```text\nmonaco-editor\n```\n\n```js\nimport editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker'\nimport jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker'\nimport cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker'\nimport htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker'\nimport tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker'\n\nself.MonacoEnvironment = {\n  getWorker(_, label) {\n    if (label === 'json') {\n      return new jsonWorker()\n    }\n    if (label === 'css' || label === 'scss' || label === 'less') {\n      return new cssWorker()\n    }\n    if (label === 'html' || label === 'handlebars' || label === 'razor') {\n      return new htmlWorker()\n    }\n    if (label === 'typescript' || label === 'javascript') {\n      return new tsWorker()\n    }\n    return new editorWorker()\n  }\n}\n```\n\n```text\n2.0.0-beta.59\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite';\nconst prefix = `monaco-editor/esm/vs`;\nexport default defineConfig({\n  build: {\n    rollupOptions: {\n      output: {\n        manualChunks: {\n          jsonWorker: [`${prefix}/language/json/json.worker`],\n          cssWorker: [`${prefix}/language/css/css.worker`],\n          htmlWorker: [`${prefix}/language/html/html.worker`],\n          tsWorker: [`${prefix}/language/typescript/ts.worker`],\n          editorWorker: [`${prefix}/editor/editor.worker`],\n        },\n      },\n    },\n  },\n});\n```\n\n```text\nUncaught ReferenceError: window is not defined\n```\n\n```text\nbuild.rollupOptions.output.manualChunks\n```\n\n```text\nvite.config.js\n```\n\n========================================\n\nComments:\n- good job i miss that on prod","metadata":{"transformedAt":"2026-08-18T18:33:46.424Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":153,"estimatedTokens":933}}410{"id":"stack-76319694","source":"stackoverflow","questionId":76319694,"title":"How to display two windows in Electron app with Electron Forge and Vite","tags":["electron","vite","electron-forge"],"text":"Title: How to display two windows in Electron app with Electron Forge and Vite\nTags: electron, vite, electron-forge\nSource: Stack Overflow\n\nQuestion:\nI'm building an Electron JS app using Electron Forge and Vite, and I'd like to display a second window in the application, but it isn't displaying properly. When I run `npm run start` the second window opens, but it displays the same content as the first window. When I run `npm run make` it opens the second window still, but the window is empty.\n\nI realize there are lots of documented ways to do this, but most use web pack, or use Electron Forge without Vite.\n\nI've done a bare bones electron forge app and just added a second window. I generated it with the following.\n\n```\nnpm init electron-app@latest electron-forge-2-windows -- --template=vite\n```\n\nI have the following directory structure.\n\n```\n.\n├── forge.config.js\n├── index.html\n├── modalWindow.html\n├── package.json\n├── src\n│ ├── index.css\n│ ├── main.js\n│ ├── preload.js\n│ └── renderer.js\n├── vite.main.config.mjs\n├── vite.modal_renderer.config.mjs\n├── vite.preload.config.mjs\n├── vite.renderer.config.mjs\n└── yarn.lock\n```\n\nforge.config.js\n\n```\nmodule.exports = {\n packagerConfig: {},\n rebuildConfig: {},\n makers: [\n {\n name: '@electron-forge/maker-squirrel',\n config: {},\n },\n {\n name: '@electron-forge/maker-zip',\n platforms: ['darwin'],\n },\n {\n name: '@electron-forge/maker-deb',\n config: {},\n },\n {\n name: '@electron-forge/maker-rpm',\n config: {},\n },\n ],\n plugins: [\n {\n name: '@electron-forge/plugin-vite',\n config: {\n // `build` can specify multiple entry builds, which can be Main process, Preload scripts, Worker process, etc.\n // If you are familiar with Vite configuration, it will look really familiar.\n build: [\n {\n // `entry` is just an alias for `build.lib.entry` in the corresponding file of `config`.\n entry: 'src/main.js',\n config: 'vite.main.config.mjs',\n },\n {\n entry: 'src/preload.js',\n config: 'vite.preload.config.mjs',\n },\n ],\n renderer: [\n {\n name: 'main_window',\n config: 'vite.renderer.config.mjs',\n },\n {\n name: 'modal_window',\n config: 'vite.modal_renderer.config.mjs',\n },\n ],\n },\n },\n ],\n};\n```\n\nsrc/main.js\n\n```\nconst { app, BrowserWindow } = require('electron');\nconst path = require('path');\n\nif (require('electron-squirrel-startup')) {\n app.quit();\n}\n\nconst createWindow = () => {\n const mainWindow = new BrowserWindow({\n width: 800,\n height: 600,\n webPreferences: {\n preload: path.join(__dirname, 'preload.js'),\n },\n });\n\n const modalWindow = new BrowserWindow({\n parent: mainWindow,\n modal: true,\n show: false,\n width: 200,\n height: 200,\n });\n\n if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {\n mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);\n } else {\n mainWindow.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`));\n }\n\n if (MODAL_WINDOW_VITE_DEV_SERVER_URL) {\n modalWindow.loadURL(MODAL_WINDOW_VITE_DEV_SERVER_URL);\n } else {\n modalWindow.loadFile(path.join(__dirname, `../renderer/${MODAL_WINDOW_VITE_NAME}/index.html`));\n }\n\n modalWindow.show();\n};\n\napp.on('ready', createWindow);\n\napp.on('window-all-closed', () => {\n if (process.platform !== 'darwin') {\n app.quit();\n }\n});\n\napp.on('activate', () => {\n if (BrowserWindow.getAllWindows().length === 0) {\n createWindow();\n }\n});\n```\n\nvite.main.config.mjs\n\n```\nimport { defineConfig } from 'vite';\n\n// https://vitejs.dev/config\nexport default defineConfig({});\n```\n\nvite.renderer.config.mjs\n\n```\nimport { defineConfig } from 'vite';\n\n// https://vitejs.dev/config\nexport default defineConfig({});\n```\n\nvite.modal_renderer.config.mjs\n\n```\nimport { defineConfig } from 'vite';\nimport { resolve } from 'path';\n\n// https://vitejs.dev/config\nexport default defineConfig({\n build: {\n rollupOptions: {\n input: {\n modal_window: resolve(__dirname, 'modalWindow.html'),\n },\n },\n },\n});\n```\n\nindex.html\n\n```\n\n \n \n Hello World!\n\n \n \n \n\n### 💖 Hello World!\n\n Welcome to your Electron application.\n\n \n \n\n```\n\nmodalWindow.html\n\n```\n\n \n \n Hello World!\n\n \n \n \n\n### Modal Window\n\n Modal\n \n\n```\n\nI can see that in my main.js the `MODAL_WINDOW_VITE_DEV_SERVER_URL` constant is resolving to `http://localhost:5174` which seems right, but I don't understand what ties that URL to the correct html file. I'm guessing what I did in `vite.modal_renderer.config.mjs` is supposed to do that, but clearly I did something wrong.\n\n========================================\n\nTop Answer:\nI've used @TheKvist's first method using the latest vite version.\n\n- Create 2 different vite config files:\n\n- `vite.mainwindow.config.ts`\n\n- `vite.secondwindow.config.ts`\n\nMake them look like so:\n\n```\nimport { defineConfig } from \"vite\";\n\nimport path from \"path\";\n\n// https://vitejs.dev/config\nexport default defineConfig({\n root: path.join(__dirname, \"src\", \"main\"), // Change \"main\" to your folder on step 4\n});\n```\n\n(Corresponds to point 4 dir structure).\n\n- Change `forge.config.ts` to:\n\n```\nrenderer: [\n {\n name: \"main_window\",\n config: \"vite.mainwindow.config.ts\",\n },\n {\n name: \"second_window\",\n config: \"vite.secondwindow.config.ts\",\n },\n ],\n```\n\n- Edit `types.d.ts` to something like:\n\n```\ndeclare const MAIN_WINDOW_VITE_DEV_SERVER_URL: string;\ndeclare const MAIN_WINDOW_VITE_NAME: string;\n\ndeclare const SECOND_WINDOW_VITE_DEV_SERVER_URL: string;\ndeclare const SECOND_WINDOW_VITE_NAME: string;\n```\n\n(Mainly to remove squiggly lines in the typescript files)\n\n- Create 2 folders under `./src/`\n\n```\n./src\n│ index.css\n│ main.ts\n│ preload.ts\n│ types.d.ts\n│\n├───second\n│ index.html\n│ index.tsx\n│ renderer.ts\n│ style.css\n│\n└───main\n index.html\n main.tsx\n renderer.ts\n```\n\nMake sure the renderer.ts has the correct path imports.\n\nLive long and prosper.\n\n========================================\n\nCode:\n```bash\nnpm init electron-app@latest electron-forge-2-windows -- --template=vite\n```\n\n```text\n.\n├── forge.config.js\n├── index.html\n├── modalWindow.html\n├── package.json\n├── src\n│   ├── index.css\n│   ├── main.js\n│   ├── preload.js\n│   └── renderer.js\n├── vite.main.config.mjs\n├── vite.modal_renderer.config.mjs\n├── vite.preload.config.mjs\n├── vite.renderer.config.mjs\n└── yarn.lock\n```\n\n```js\nmodule.exports = {\n  packagerConfig: {},\n  rebuildConfig: {},\n  makers: [\n    {\n      name: '@electron-forge/maker-squirrel',\n      config: {},\n    },\n    {\n      name: '@electron-forge/maker-zip',\n      platforms: ['darwin'],\n    },\n    {\n      name: '@electron-forge/maker-deb',\n      config: {},\n    },\n    {\n      name: '@electron-forge/maker-rpm',\n      config: {},\n    },\n  ],\n  plugins: [\n    {\n      name: '@electron-forge/plugin-vite',\n      config: {\n        // `build` can specify multiple entry builds, which can be Main process, Preload scripts, Worker process, etc.\n        // If you are familiar with Vite configuration, it will look really familiar.\n        build: [\n          {\n            // `entry` is just an alias for `build.lib.entry` in the corresponding file of `config`.\n            entry: 'src/main.js',\n            config: 'vite.main.config.mjs',\n          },\n          {\n            entry: 'src/preload.js',\n            config: 'vite.preload.config.mjs',\n          },\n        ],\n        renderer: [\n          {\n            name: 'main_window',\n            config: 'vite.renderer.config.mjs',\n          },\n          {\n            name: 'modal_window',\n            config: 'vite.modal_renderer.config.mjs',\n          },\n        ],\n      },\n    },\n  ],\n};\n```\n\n```js\nconst { app, BrowserWindow } = require('electron');\nconst path = require('path');\n\nif (require('electron-squirrel-startup')) {\n  app.quit();\n}\n\nconst createWindow = () => {\n  const mainWindow = new BrowserWindow({\n    width: 800,\n    height: 600,\n    webPreferences: {\n      preload: path.join(__dirname, 'preload.js'),\n    },\n  });\n\n  const modalWindow = new BrowserWindow({\n    parent: mainWindow,\n    modal: true,\n    show: false,\n    width: 200,\n    height: 200,\n  });\n\n  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {\n    mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);\n  } else {\n    mainWindow.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`));\n  }\n\n  if (MODAL_WINDOW_VITE_DEV_SERVER_URL) {\n    modalWindow.loadURL(MODAL_WINDOW_VITE_DEV_SERVER_URL);\n  } else {\n    modalWindow.loadFile(path.join(__dirname, `../renderer/${MODAL_WINDOW_VITE_NAME}/index.html`));\n  }\n\n  modalWindow.show();\n};\n\napp.on('ready', createWindow);\n\napp.on('window-all-closed', () => {\n  if (process.platform !== 'darwin') {\n    app.quit();\n  }\n});\n\napp.on('activate', () => {\n  if (BrowserWindow.getAllWindows().length === 0) {\n    createWindow();\n  }\n});\n```\n\n```js\nimport { defineConfig } from 'vite';\n\n// https://vitejs.dev/config\nexport default defineConfig({});\n```\n\n```js\nimport { defineConfig } from 'vite';\n\n// https://vitejs.dev/config\nexport default defineConfig({});\n```\n\n```js\nimport { defineConfig } from 'vite';\nimport { resolve } from 'path';\n\n// https://vitejs.dev/config\nexport default defineConfig({\n  build: {\n    rollupOptions: {\n      input: {\n        modal_window: resolve(__dirname, 'modalWindow.html'),\n      },\n    },\n  },\n});\n```\n\n```html\n<!DOCTYPE html>\n<html>\n  <head>\n    <meta charset=\"UTF-8\" />\n    <title>Hello World!</title>\n\n  </head>\n  <body>\n    <h1>💖 Hello World!</h1>\n    <p>Welcome to your Electron application.</p>\n    <script type=\"module\" src=\"/src/renderer.js\"></script>\n  </body>\n</html>\n```\n\n```html\n<!DOCTYPE html>\n<html>\n  <head>\n    <meta charset=\"UTF-8\" />\n    <title>Hello World!</title>\n\n  </head>\n  <body>\n    <h1>Modal Window</h1>\n    <div>Modal</div>\n  </body>\n</html>\n```\n\n```text\nnpm run start\n```\n\n```text\nnpm run make\n```\n\n```text\nMODAL_WINDOW_VITE_DEV_SERVER_URL\n```\n\n```text\nhttp://localhost:5174\n```\n\n```text\nvite.modal_renderer.config.mjs\n```\n\n```bash\nmv modalWindow.html modal_window/index.html # directory is of course arbitrary\n```\n\n```js\nexport default defineConfig({\n  root: resolve(__dirname, \"modal_window\"),\n});\n```\n\n```js\nexport default defineConfig({\n  build: {\n    rollupOptions: {\n      input: {\n        main_window: resolve(__dirname, \"index.html\"),\n        modal_window: resolve(__dirname, 'modalWindow.html'),\n      },\n    },\n  },\n});\n```\n\n```js\n// mainWindow\nif (MAIN_WINDOW_VITE_DEV_SERVER_URL) {\n  mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);\n} else {\n  mainWindow.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`));\n}\n\n// modalWindow - both use the same constant now\nif (MAIN_WINDOW_VITE_DEV_SERVER_URL) {\n  // add file name here ................................. v \n  modalWindow.loadURL(`${MAIN_WINDOW_VITE_DEV_SERVER_URL}/modalWindow.html`); \n} else {\n  // change file name here ...................................................... v \n  modalWindow.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/modalWindow.html`));\n}\n```\n\n```text\nmodalWindow.html\n```\n\n```text\nmodalWindow.html\n```\n\n```text\nloadURL/loadFile\n```\n\n```text\nmodalWindow.html\n```\n\n```text\nindex.html\n```\n\n```text\nroot\n```\n\n```text\nvite.modal_window.config.js\n```\n\n```text\nvite.modal_window.config.js\n```\n\n```text\nvite.renderer.config.js\n```\n\n```text\nloadURL/loadFile\n```\n\n```text\nvite.renderer.config.js\n```\n\n```text\nmain.js\n```\n\n```text\n*_VITE_*\n```\n\n```text\n*_VITE_DEV_SERVER_URL\n```\n\n```text\nhttp://localhost:<port>/<base>\n```\n\n```text\nport\n```\n\n```text\nbase\n```\n\n```text\n/\n```\n\n```text\nloadURL\n```\n\n```text\nindex.html\n```\n\n```text\n*_VITE_NAME\n```\n\n```text\nforge.config.js\n```\n\n```text\nbuild.outDir\n```\n\n```text\n.vite/renderer/<renderer.name>/\n```\n\n```text\nloadFile\n```\n\n```text\ncreate-electron-app\n```\n\n```text\nimport { defineConfig } from \"vite\";\n\nimport path from \"path\";\n\n// https://vitejs.dev/config\nexport default defineConfig({\n  root: path.join(__dirname, \"src\", \"main\"), // Change \"main\" to your folder on step 4\n});\n```\n\n```text\nrenderer: [\n        {\n          name: \"main_window\",\n          config: \"vite.mainwindow.config.ts\",\n        },\n        {\n          name: \"second_window\",\n          config: \"vite.secondwindow.config.ts\",\n        },\n      ],\n```\n\n```text\ndeclare const MAIN_WINDOW_VITE_DEV_SERVER_URL: string;\ndeclare const MAIN_WINDOW_VITE_NAME: string;\n\ndeclare const SECOND_WINDOW_VITE_DEV_SERVER_URL: string;\ndeclare const SECOND_WINDOW_VITE_NAME: string;\n```\n\n```text\n./src\n│   index.css\n│   main.ts\n│   preload.ts\n│   types.d.ts\n│\n├───second\n│       index.html\n│       index.tsx\n│       renderer.ts\n│       style.css\n│\n└───main\n        index.html\n        main.tsx\n        renderer.ts\n```\n\n```text\nvite.mainwindow.config.ts\n```\n\n```text\nvite.secondwindow.config.ts\n```\n\n```text\nforge.config.ts\n```\n\n```text\ntypes.d.ts\n```\n\n```text\n./src/\n```\n\n========================================\n\nComments:\n- I tried the first option here but but setting the `root` the output is the same folder. This means when you build your Electron app, with `electron-forge package` for example, the built code does not end up in your app.\n- @chetbox Of course, every renderer's Vite configuration has to point to its own root directory for the build to work. That means you can not build two renderers to, say, \"modal_window\", but instead have to choose another directory name for one of the renderers.\n- I understand that the purpose of the first method is to separate assets, but how would one use the public directory? It seems inaccessible entirely in the app unless I explicitly have publicDir defined in the renderer config, but that creates duplicate assets, and doesn't feel like the right solution to common assets between the two renderers.","metadata":{"transformedAt":"2026-08-18T18:33:46.425Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":53,"totalLines":743,"estimatedTokens":3363}}411{"id":"stack-76644298","source":"stackoverflow","questionId":76644298,"title":"Vite multiple entry points without [folder]/index.html pattern","tags":["html","vite"],"text":"Title: Vite multiple entry points without [folder]/index.html pattern\nTags: html, vite\nSource: Stack Overflow\n\nQuestion:\nI'm new to vite and trying to migrate from a gulp workflow to vite. I want to output multiple html files in this format: (Not like dist/about/index.html)\n\n```\n...\nsrc\n|_index.html\n|_about.html\n|_contact.html\n|_assets\n\ndist\n|_index.html\n|_about.html\n|_contact.html\n|_assets\n```\n\nIs this possible?\n\n========================================\n\nCode:\n```text\n...\nsrc\n|_index.html\n|_about.html\n|_contact.html\n|_assets\n\ndist\n|_index.html\n|_about.html\n|_contact.html\n|_assets\n```\n\n```text\nimport { defineConfig } from 'vite';\n\nexport default defineConfig(() => {\n    return {\n        build: {\n            rollupOptions: {\n                input: ['index.html', 'about.html'],\n                output: {\n                    entryFileNames: ['index.html', 'about.html']\n                }\n            },\n        },\n    };\n});\n```\n\n```text\npublic\n```\n\n```text\ninput\n```\n\n```text\noutput.entryFileNames\n```\n\n```text\nfast-glob\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.425Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":74,"estimatedTokens":259}}412{"id":"stack-73355479","source":"stackoverflow","questionId":73355479,"title":"How to specify runtime directory for Vite when running the dev server","tags":["reactjs","vite"],"text":"Title: How to specify runtime directory for Vite when running the dev server\nTags: reactjs, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use Vite for a React project. I need to configure Vite so that when I run the dev server it places the runtime files in a particular directory (because the files are used with another runtime environment). The server config doesn't seems to have an option but I'm not sure if I'm missing something or it is in a different place. Thanks\n\n========================================\n\nCode:\n```text\nbuild --watch\n```\n\n```text\nnpm run dev & npm run build -- --watch\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.425Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":17,"estimatedTokens":152}}413{"id":"stack-76436481","source":"stackoverflow","questionId":76436481,"title":"Vitest: How can I mock a function that the function being tested uses?","tags":["jestjs","vite","vitest"],"text":"Title: Vitest: How can I mock a function that the function being tested uses?\nTags: jestjs, vite, vitest\nSource: Stack Overflow\n\nQuestion:\nFor example, how can I mock the `hello` function and `.mockReturnValue(\"Hi\")`? Hoping someone can assist with this simple example as it's quite confusing to me currently.\n\n```\n// greet.ts\nexport function hello() {\n return \"Hello \";\n}\n\nexport function greet(name: string) {\n return hello() + name;\n}\n```\n\nTest file:\n\n```\n// greet.spec.ts\nimport {hello, greet} from \"./greet\";\n\nvi.mock(\"./greet\", async () => {\n const mod = await vi.importActual(\"./greet\");\n const hello = vi.fn().mockReturnValue(\"Hi \");\n return {\n ...mod,\n hello,\n // greet: vi.fn((name: string)=> hello() + name),\n // ^this works if I uncomment it, but it defeats \n // the purpose of the test. \n // Is it just not possible to do what I want? \n }\n})\n\ndescribe(\"Greeting\", () => {\n test(\"should return a personalized greeting\", async () => {\n const result = greet(\"John\");\n\n expect(result).toBe(\"Hi John\");\n expect(hello).toHaveBeenCalled();\n });\n});\n```\n\nRunning the test still gives `Hello John` and the `hello` function is not called. No surprise... how can I mock the implementation of `hello()` in the actual `greet` function?\n\n========================================\n\nCode:\n```js\n// greet.ts\nexport function hello() {\n  return \"Hello \";\n}\n\nexport function greet(name: string) {\n  return hello() + name;\n}\n```\n\n```js\n// greet.spec.ts\nimport {hello, greet} from \"./greet\";\n\nvi.mock(\"./greet\", async () => {\n  const mod = await vi.importActual<typeof \n    import(\"./greet\")>(\"./greet\");\n  const hello = vi.fn().mockReturnValue(\"Hi \");\n  return {\n    ...mod,\n    hello,\n    // greet: vi.fn((name: string)=> hello() + name),\n    // ^this works if I uncomment it, but it defeats \n    // the purpose of the test. \n    // Is it just not possible to do what I want? \n  }\n})\n\ndescribe(\"Greeting\", () => {\n  test(\"should return a personalized greeting\", async () => {\n    const result = greet(\"John\");\n\n    expect(result).toBe(\"Hi John\");\n    expect(hello).toHaveBeenCalled();\n  });\n});\n```\n\n```text\nhello\n```\n\n```text\n.mockReturnValue(\"Hi\")\n```\n\n```text\nHello John\n```\n\n```text\nhello\n```\n\n```text\nhello()\n```\n\n```text\ngreet\n```\n\n```text\nmock()\n```\n\n```text\ndoMock()\n```\n\n```text\ndoMock()\n```\n\n```text\nmock()\n```\n\n```text\n./greet\n```\n\n```text\nhello\n```\n\n```text\nhello\n```\n\n```text\nhello\n```\n\n```text\ngreet\n```\n\n========================================\n\nComments:\n- I see. Thanks. I updated my own attempt. It looks closer to how it should be, and I know if I mock the greet function and rewrite the logic in the test, it would work but it kinda defeats the purpose. How can I replace the `hello` function in the original implementation of `greet` I wonder...\n- Ah i see what you mean now! Essentially you need to use a more testable pattern for this (which is a good thing, making your code more testable is a noble goal). See here stackoverflow.com/questions/45111198/&hellip;, I think that matches perfectly your issue.\n- ^ Thanks. That's helpful. I can accept your answer if you update it a bit with some commentary based on the question you linked, if you're interested\n- Makes sense, I'll edit appropriately\n- You say: \"the usual way out of this situation isn't to try to find some hacky workaround that works with the existing code, but to instead change your code architecture to be more testable\". I don't understand what about @wongx's code is problematic. He is calling a function from within another function. Isn't this like one of the most basic instances where one would mock something? What is an alternative pattern here? Passing `hello` as an argument to `greet`?\n- Admittedly I feel I strayed in this answer a bit because often when people start hitting blocks in this area, its because their mocking solution is very technically complex and that effort would be better spent improving the abstraction. In this case though, there's nothing fundamentally wrong with what he is doing, so I think your implied observation that changes would not add anything is valid in this case. Your only option is to reach for cheap hacks stackoverflow.com/a/47976589/1086398 or to remodel it slightly like in your suggestion. Mocking is overused generally (IMO).","metadata":{"transformedAt":"2026-08-18T18:33:46.425Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":160,"estimatedTokens":1067}}414{"id":"stack-74833465","source":"stackoverflow","questionId":74833465,"title":"React-router-dom is not working with Vite","tags":["javascript","reactjs","react-router-dom","vite"],"text":"Title: React-router-dom is not working with Vite\nTags: javascript, reactjs, react-router-dom, vite\nSource: Stack Overflow\n\nQuestion:\nI'm building an web application besed on React and Vite. I also use `react-router-dom` to create a navigation into my app but when I go to the main page I've got this error in my browser's console:\n\n`Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/react-router-dom.js?v=67b79ac4' does not provide an export named 'Redirect'`\n\nI'm trying to make a navigation into my React app with `react-router-dom`. Here is my `App.jsx` code :\n\n```\nimport { BrowserRouter as Router, Switch, Route, Redirect } from \"react-router-dom\"\n\nimport Header from \"./routes/Header/Header\";\nimport Home from \"./routes/Home/Home.jsx\";\nimport AboutMe from \"./routes/AboutMe/AboutMe.jsx\";\nimport Portfolio from \"./routes/Portfolio/Portfolio.jsx\";\nimport Socials from \"./routes/Socials/Socials.jsx\";\n\nfunction App() {\n\n return (\n \n \n \n \n \n \n \n \n \n \n \n \n )\n}\n\nexport default App\n```\n\nAnd here is all my dependencies in the `package.json` file :\n\n```\n\"dependencies\": {\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\",\n \"react-router-dom\": \"^6.5.0\",\n \"sass\": \"^1.57.0\"\n},\n\"devDependencies\": {\n \"@types/react\": \"^18.0.26\",\n \"@types/react-dom\": \"^18.0.9\",\n \"@vitejs/plugin-react\": \"^3.0.0\",\n \"vite\": \"^4.0.0\"\n}\n```\n\nSo can someone explain me why my navigation is not working and how can I resolve the problem ?\n\n========================================\n\nTop Answer:\nIn your src directory update your index.js or main.js if using vite\n\n```\nimport React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App.jsx'\nimport './index.css'\nimport { BrowserRouter } from \"react-router-dom\"\n\nReactDOM.createRoot(document.getElementById('root')).render(\n \n \n \n \n ,\n)\n```\n\nimport Route and Routes from react router dom then import your global assets in App.jsx\n\n```\nimport { useState } from 'react';\nimport { Route, Routes } from \"react-router-dom\";\nimport './App.css';\n\nimport Header from \"./routes/Header/Header\";\nimport Home from \"./routes/Home/Home.jsx\";\nimport AboutMe from \"./routes/AboutMe/AboutMe.jsx\";\nimport Portfolio from \"./routes/Portfolio/Portfolio.jsx\";\nimport Socials from \"./routes/Socials/Socials.jsx\";\n```\n\nThen render\n\n```\nfunction App() {\n\n return (\n \n \n \n } />\n } />\n } />\n } />\n \n \n )\n}\n\nexport default App\n```\n\nRemember to update\n\n```\n to \n```\n\nfor your nav links\n\n========================================\n\nCode:\n```js\nimport { BrowserRouter as Router, Switch, Route, Redirect } from \"react-router-dom\"\n\nimport Header from \"./routes/Header/Header\";\nimport Home from \"./routes/Home/Home.jsx\";\nimport AboutMe from \"./routes/AboutMe/AboutMe.jsx\";\nimport Portfolio from \"./routes/Portfolio/Portfolio.jsx\";\nimport Socials from \"./routes/Socials/Socials.jsx\";\n\nfunction App() {\n\n  return (\n    <div className=\"App\">\n      <Router>\n        <Header />\n        <Switch>\n          <Route exact path=\"/\" component={Home} />\n          <Route exace path=\"/about-me\" component={AboutMe} />\n          <Route exact path=\"/portfolio\" component={Portfolio} />\n          <Route exact path=\"/socials\" component={Socials} />\n          <Redirect to=\"/\" />\n        </Switch>\n      </Router>\n    </div>\n  )\n}\n\nexport default App\n```\n\n```json\n\"dependencies\": {\n  \"react\": \"^18.2.0\",\n  \"react-dom\": \"^18.2.0\",\n  \"react-router-dom\": \"^6.5.0\",\n  \"sass\": \"^1.57.0\"\n},\n\"devDependencies\": {\n  \"@types/react\": \"^18.0.26\",\n  \"@types/react-dom\": \"^18.0.9\",\n  \"@vitejs/plugin-react\": \"^3.0.0\",\n  \"vite\": \"^4.0.0\"\n}\n```\n\n```text\nreact-router-dom\n```\n\n```text\nUncaught SyntaxError: The requested module '/node_modules/.vite/deps/react-router-dom.js?v=67b79ac4' does not provide an export named 'Redirect'\n```\n\n```text\nreact-router-dom\n```\n\n```text\nApp.jsx\n```\n\n```text\npackage.json\n```\n\n```text\nreact-router-dom\n```\n\n```text\npackage.json\n```\n\n```text\nimport { redirect } from \"react-router-dom\";\n```\n\n```js\n<Route ***exace*** path=\"/about-me\" component={AboutMe} />\n```\n\n```text\nimport React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App.jsx'\nimport './index.css'\nimport { BrowserRouter } from \"react-router-dom\"\n\nReactDOM.createRoot(document.getElementById('root')).render(\n  <React.StrictMode>\n    <BrowserRouter>\n      <App />\n    </BrowserRouter>\n  </React.StrictMode>,\n)\n```\n\n```text\nimport { useState } from 'react';\nimport { Route, Routes } from \"react-router-dom\";\nimport './App.css';\n\nimport Header from \"./routes/Header/Header\";\nimport Home from \"./routes/Home/Home.jsx\";\nimport AboutMe from \"./routes/AboutMe/AboutMe.jsx\";\nimport Portfolio from \"./routes/Portfolio/Portfolio.jsx\";\nimport Socials from \"./routes/Socials/Socials.jsx\";\n```\n\n```text\nfunction App() {\n\n  return (\n    <div className=\"App\">\n      <Header/>\n      <Routes>\n        <Route path=\"/\" element= {<Home/>} />\n        <Route path=\"/about-me\" element= {<AboutMe/>} />\n        <Route path=\"/portfolio\" element= {<Portfolio/>} />\n        <Route path=\"/socials\" element= {<Socials/>} />\n      </Routes>\n    </div>\n  )\n}\n\nexport default App\n```\n\n```text\n<a href=\"\"> to <Link to=\"\">\n```\n\n```text\nfunction App() {\n\n  return (\n    <div className=\"App\">\n      <BrowserRouter>\n        <Header />\n        <Routes>\n          <Route path=\"/\" element={Home} />\n          <Route path=\"/about-me\" element={AboutMe} />\n          <Route path=\"/portfolio\" element={Portfolio} />\n          <Route path=\"/socials\" element={Socials} />\n        </Routes>\n      </BrowserRouter>\n    </div>\n  )\n}\n```\n\n```text\nreact-router-dom\n```\n\n```text\n<Switch>\n```\n\n========================================\n\nComments:\n- You're using code for RR v5 and below but you've installed v6. RR changed quite a lot when it advanced to v6. You'll want to take a look at the upgrade documentation and make those fixes to your code.\n- It looks like Vite is trying to import a specific version of the module, `&#47;node_modules&#47;.vite&#47;deps&#47;react-router-dom.js?v=67b79ac4`, which does not contain the `Redirect` export.\n- React Router v6 has changed to use `Navigate` component instead of `Redirect`. You should do as shown here: stackoverflow.com/a/69872699/14426823. Note that the props for the `Route` component is also no longer `component=`; it is `element=` now\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- I had tried redirect also, but it didn't work for me. I decided to use the Navigate component instead.","metadata":{"transformedAt":"2026-08-18T18:33:46.425Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":294,"estimatedTokens":1658}}415{"id":"stack-76078204","source":"stackoverflow","questionId":76078204,"title":"Why do I have to download dotenv package if I can use .env file without it?","tags":["reactjs","vite","dotenv"],"text":"Title: Why do I have to download dotenv package if I can use .env file without it?\nTags: reactjs, vite, dotenv\nSource: Stack Overflow\n\nQuestion:\nI am working on a React project, where I have to use an API. To use environment variables, I have created a `.env` file, and it is working fine without installing the `dotenv` package.\n\nWhy do I need to install the `dotenv` package from npm? What am I missing when I am not using dotenv? Because the project is working fine without dotenv.\n\nI'm using `npm create vite` by the way.\n\n========================================\n\nCode:\n```text\n.env\n```\n\n```text\ndotenv\n```\n\n```text\ndotenv\n```\n\n```text\nnpm create vite\n```\n\n```text\ncreate-react-app\n```\n\n```text\ncreate-next-app\n```\n\n```text\nnpm create vite\n```\n\n```text\ndotenv\n```\n\n```text\ndotenv\n```\n\n```text\n.env\n```\n\n```text\nenv.local\n```\n\n```text\ndotenv\n```\n\n```text\n.env\n```\n\n========================================\n\nComments:\n- Did you use `create-react-app` or `create-next-app` to set up your project?\n- I used npm `npm create vite@latest`\n- Thaks for answering. Check my below answer and let me know please.\n- dotenv automates activating environment variables automatically when you change directories, instead of requiring manual interaction. It's not at all requires, just a convenience.\n- `vite` has it under the hood.\n- What about deployment, is dotenv only for development. Or is there any use of dotenv in deployment. By the way, thanks for answering :)\n- It can be used in both cases. And in both cases, when you install your project, it will be installed as part of Vite, so you don't have to do anything.","metadata":{"transformedAt":"2026-08-18T18:33:46.425Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":76,"estimatedTokens":403}}416{"id":"stack-75311706","source":"stackoverflow","questionId":75311706,"title":"How to solve importers[path] is not a function for clean Vue 3/Vite/Storybook installation","tags":["vue.js","vite","storybook"],"text":"Title: How to solve importers[path] is not a function for clean Vue 3/Vite/Storybook installation\nTags: vue.js, vite, storybook\nSource: Stack Overflow\n\nQuestion:\nAfter the following steps\n\n- install a clean Vue3/Vite application as outlined in the docs (Vue application runs correctly)\n\n- install Storybook as describes in the docs\n\n- run Storybook (`npm run storybook`)\n\nI run into the following error:\n\n```\nimporters[path] is not a function\n\nTypeError: importers[path] is not a function\n at StoryStore2.importFn (http://localhost:6006/virtual:/@storybook/builder-vite/storybook-stories.js:6:31)\n at StoryStore2.loadCSFFileByStoryId (http://localhost:6006/node_modules/.vite-storybook/deps/chunk-WS7C7QNU.js?v=58e9ae5a:2297:19)\n at StoryStore2._callee2$ (http://localhost:6006/node_modules/.vite-storybook/deps/chunk-WS7C7QNU.js?v=58e9ae5a:2355:29)\n at tryCatch (http://localhost:6006/node_modules/.vite-storybook/deps/chunk-IKIHLHDP.js?v=58e9ae5a:46:44)\n at Generator.invoke (http://localhost:6006/node_modules/.vite-storybook/deps/chunk-IKIHLHDP.js?v=58e9ae5a:213:26)\n at Generator.next (http://localhost:6006/node_modules/.vite-storybook/deps/chunk-IKIHLHDP.js?v=58e9ae5a:87:25)\n at asyncGeneratorStep2 (http://localhost:6006/node_modules/.vite-storybook/deps/chunk-WS7C7QNU.js?v=58e9ae5a:2140:24)\n at _next (http://localhost:6006/node_modules/.vite-storybook/deps/chunk-WS7C7QNU.js?v=58e9ae5a:2158:9)\n```\n\nWhat could be wrong here and how can this be solved?\n\nhttps://i.sstatic.net/NHdX7.png\n\n========================================\n\nTop Answer:\nIn my case, this error was caused by attempting to import a .js component into a .ts extension storybook story. Updating the story to .tsx fixed the issue for me. It also fixed the issue when I updated my component and story both to .ts extensions.\n\n========================================\n\nCode:\n```text\nimporters[path] is not a function\n\n\nTypeError: importers[path] is not a function\n    at StoryStore2.importFn (http://localhost:6006/virtual:/@storybook/builder-vite/storybook-stories.js:6:31)\n    at StoryStore2.loadCSFFileByStoryId (http://localhost:6006/node_modules/.vite-storybook/deps/chunk-WS7C7QNU.js?v=58e9ae5a:2297:19)\n    at StoryStore2._callee2$ (http://localhost:6006/node_modules/.vite-storybook/deps/chunk-WS7C7QNU.js?v=58e9ae5a:2355:29)\n    at tryCatch (http://localhost:6006/node_modules/.vite-storybook/deps/chunk-IKIHLHDP.js?v=58e9ae5a:46:44)\n    at Generator.invoke (http://localhost:6006/node_modules/.vite-storybook/deps/chunk-IKIHLHDP.js?v=58e9ae5a:213:26)\n    at Generator.next (http://localhost:6006/node_modules/.vite-storybook/deps/chunk-IKIHLHDP.js?v=58e9ae5a:87:25)\n    at asyncGeneratorStep2 (http://localhost:6006/node_modules/.vite-storybook/deps/chunk-WS7C7QNU.js?v=58e9ae5a:2140:24)\n    at _next (http://localhost:6006/node_modules/.vite-storybook/deps/chunk-WS7C7QNU.js?v=58e9ae5a:2158:9)\n```\n\n```text\nnpm run storybook\n```\n\n```text\n{\n  \"name\": \"Test project\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vue-tsc && vite build\",\n    \"preview\": \"vite preview\",\n    \"storybook\": \"start-storybook -p 6006\",\n    \"build-storybook\": \"build-storybook\"\n  },\n  \"dependencies\": {\n    \"vue\": \"^3.2.45\"\n  },\n  \"devDependencies\": {\n    \"@babel/core\": \"^7.20.12\",\n    \"@storybook/addon-actions\": \"^6.5.16\",\n    \"@storybook/addon-essentials\": \"^6.5.16\",\n    \"@storybook/addon-interactions\": \"^6.5.16\",\n    \"@storybook/addon-links\": \"^6.5.16\",\n    \"@storybook/builder-vite\": \"^0.3.0\",\n    \"@storybook/testing-library\": \"^0.0.13\",\n    \"@storybook/vue3\": \"^6.5.16\",\n    \"@vitejs/plugin-vue\": \"^4.0.0\",\n    \"babel-loader\": \"^8.3.0\",\n    \"typescript\": \"^4.9.3\",\n    \"vite\": \"^4.1.0\",\n    \"vue-loader\": \"^16.8.3\",\n    \"vue-tsc\": \"^1.0.24\"\n  }\n}\n```\n\n```text\n<project name>\n```\n\n```text\n<project name>\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.425Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":102,"estimatedTokens":960}}417{"id":"stack-74518887","source":"stackoverflow","questionId":74518887,"title":"Blank page when deploying a react app to github pages and vite","tags":["reactjs","web-deployment","github-pages","vite"],"text":"Title: Blank page when deploying a react app to github pages and vite\nTags: reactjs, web-deployment, github-pages, vite\nSource: Stack Overflow\n\nQuestion:\nWhen i try to deploy my react app to github pages with the package gh-pages, the result page is blank.result page\n\nThe page I am trying to deploy is here: LINK\nI don't know if it matters but I am currently using the free domain given to me by GitHub: www.elvas.me\n\nI tried following the react official docs: Link, but it didn't work for me... Perhaps it's because I am using vite and not create-react-app?\n\n***Edit***\n\nFound out that the site is trying to get the .js and the .css from the wrong place.\nhttps://i.sstatic.net/MgUEH.png\n\nI just don't know what I am doing wrong...\n\n========================================\n\nTop Answer:\nI see that you have managed to deploy your React project to Github pages successfully, but here is how I did it in case anyone needs help:\n\n- First things first, make sure that your \".git\" folder and your project are in the same folder.\n\nhttps://i.sstatic.net/kgg5G.png\n\n- Run `npm run build`. You should have a `dist` folder now.\n\n- Open the file `vite.config.js` (or `.ts`).\n\n- Add the `base` file with your repository name. Include the two `/`.\n\nExample: let's say your github project's URL is `https://github.com/atlassian/react-beautiful-dnd`.\n\n```\nexport default defineConfig({\n base: \"/react-beautiful-dnd/\",\n plugins: [react()],\n});\n```\n\n- Open your `.gitignore` file and **delete** the `dist` line from it. You want to make sure that the `dist` folder is pushed to github.\n\n- `git add .`\n\n- `git commit -m \"deploy\"`\n\n- `git subtree push --prefix dist origin gh-pages`\n\n- Wait for a couple minutes (in my case it took 4 minutes) and open the page. In the example above, the URL would look like this: **https://atlassian.github.io/react-beautiful-dnd**\n\nIn case it's still showing a blank page, it's very likely to do with the step number 3. Ensure you added the correct repository URL and that it begins and ends with the `/` sign.\n\nThat is about it, I hope it helps. I used this blog post for guidance, it is a more detailed explanation of the above.\n\n========================================\n\nCode:\n```text\nbase:\"{repName}\"\n```\n\n```text\nexport default defineConfig({\n  base: \"/react-beautiful-dnd/\",\n  plugins: [react()],\n});\n```\n\n```text\nnpm run build\n```\n\n```text\ndist\n```\n\n```text\nvite.config.js\n```\n\n```text\n.ts\n```\n\n```text\nbase\n```\n\n```text\n/\n```\n\n```text\nhttps://github.com/atlassian/react-beautiful-dnd\n```\n\n```text\n.gitignore\n```\n\n```text\ndist\n```\n\n```text\ndist\n```\n\n```text\ngit add .\n```\n\n```text\ngit commit -m \"deploy\"\n```\n\n```text\ngit subtree push --prefix dist origin gh-pages\n```\n\n```text\n/\n```\n\n```text\nvite.config.ts\n```\n\n```text\nvite.config.ts\n```\n\n```text\nvite.config.js\n```\n\n```text\ntsconfig.node.json\n```\n\n```text\n\"/\"\n```\n\n```text\nvite build\n```\n\n```text\ndist/index.html\n```\n\n```text\ndist/index.html\n```\n\n```text\nvite.config.js\n```\n\n```text\nsrc\n```\n\n```text\nvite build\n```\n\n```text\n/*\n...\n*/\nexport default defineConfig({\n    plugins: [react()],\n    base: \"/<REPO>/\",\n});\n```\n\n```text\n/*\n...\n*/\n\nReactDOM.createRoot(document.getElementById(\"root\")).render(\n  <React.StrictMode>\n    <BrowserRouter basename={\"/<REPO>/\"}>\n      <App />\n    </BrowserRouter>\n  </React.StrictMode>\n);\n```\n\n```text\nvite.config.js\n```\n\n```text\nbase\n```\n\n```text\nhttps://<USERNAME>.github.io/<REPO>\n```\n\n```text\nvite.config.js\n```\n\n```text\nbasename\n```\n\n```text\n<REPO>\n```\n\n```text\n<BrowserRoute>\n```\n\n```text\nmain.jsx\n```\n\n```text\nbasename\n```\n\n```text\ngitignore\n```\n\n```text\nvite.config.js\n```\n\n```text\nwith:\n          # Upload entire folder\n          path: '.'\n```\n\n```text\nwith:\n          # Upload dist folder\n          path: './dist'\n```\n\n```text\nimport SignIn from './pages/Signin'\n\nfunction App() {\nreturn (\n  <BrowserRouter basename=\"/your-repositorie-name\">\n    <Routes>\n      <Route path=\"/\" element={<SignIn />} />\n    </Routes>\n  </BrowserRouter>\n)\n}\n\nexport default App\n```\n\n========================================\n\nComments:\n- Have you set the \"/\" route ?\n- How do I do that? In the index.html?\n- I mean in the app.js, where you define your routes, is the \"/\" (the home route) defined ?\n- I don't think it is... But I am not using react-router, do I need it?\n- If you only have one route, no. But if you want to develop many routes in the future, I recommend you to use react-router.\n- For this specific project, i do not need more than one route :)\n- Did you do `npm run build`? It looks like your files aren't the build files in the github repo\n- I did! I am using yarn, so `yarn run build`. The files don't look the same because I was testing stuff, but now it's all updated. Still not working tho.\n- when i do `yarn deploy`, it will automatically do the `yarn run build` right?\n- Thanks for this. I didn't see these instructions anywhere in the github docs.\n- I think is a good practice to put dist in gitignore, because besides being necessary data in the repository, it can create conflicts when you are working with a team.","metadata":{"transformedAt":"2026-08-18T18:33:46.425Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":43,"totalLines":281,"estimatedTokens":1260}}418{"id":"stack-73298724","source":"stackoverflow","questionId":73298724,"title":"Laravel Vite Deployment to Host","tags":["php","laravel","vite"],"text":"Title: Laravel Vite Deployment to Host\nTags: php, laravel, vite\nSource: Stack Overflow\n\nQuestion:\nI'm having a trouble with Vite in Laravel. I ran the command **npm run build** and then I uploaded files to my shared hosting. But it doesn't load css and js files.\n\nI've put `@vite(['resources/css/admin.css', 'resources/js/app.js'])` at the top of the script.\nThen I ran the command `npm run build`.\nAnd then uploaded all files to my shared hosting.\nI tried to open the page. Style and JS files looks like this on page source;\n\n\r\n\r\n\n```\n\n```\n\n\r\n\r\n\r\n\nAnd it gives me these errors in browser console obviously because it tries to get files from localhost.\n\nWhich configurations should I make in Vite?\n\n========================================\n\nTop Answer:\nthat's a silly problem, you are sending the requests to the http://127.0.0.1 not the host! you have to send the request to for expample https://hostname.com not http://127.0.0.1\n\n========================================\n\nCode:\n```html\n<script type=\"module\" src=\"http://127.0.0.1:5173/@vite/client\"></script>\n<link rel=\"stylesheet\" href=\"http://127.0.0.1:5173/resources/css/admin.css\" />\n<script type=\"module\" src=\"http://127.0.0.1:5173/resources/js/app.js\"></script>\n```\n\n```text\n@vite(['resources/css/admin.css', 'resources/js/app.js'])\n```\n\n```text\nnpm run build\n```\n\n```text\npublic/hot\n```\n\n========================================\n\nComments:\n- Laravel shouldn't be trying to get assets from your local machine when it's in production. You've got something misconfigured somewhere, you've either hardcoded a local address or you've got a config file somewhere which is pointing to a local address.\n- Please edit your question to contain properly formatted text, not images of text. See Please do not upload images of code/data/errors when asking a question. for many reasons why this is important. Also: there's really no specific programming question here.\n- I edited the question. The image is Chrome console errors. Nothing more. Problem is not that. Problem is; Vite tries to get files from localhost. Why? Where am I missing?\n- Just deleting the hot file in the public solved my issue ,thanks man\n- ohh man, I wasted an hour trying to figure it out. Never seen this before. Much appreciated\n- There is no hot file inside public folder. It is not working for me. Can you help? I have done the npm run build also\n- solved my problem, thanks sir.\n- I do not specify the host address. Vite does all the thing. I just write **@vite(['resource/app.css'])**. And the problem was with the **hot** file in public. If the hot file exists in public folder, app thinks it's in development mode. I deleted that file and it fixed.\n- @Blitzconn Thank you so much! I literally spent over an hour for this","metadata":{"transformedAt":"2026-08-18T18:33:46.426Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":65,"estimatedTokens":688}}419{"id":"stack-72671763","source":"stackoverflow","questionId":72671763,"title":"Vite doesn't update included js files when changed","tags":["vue.js","vite","quasar-framework"],"text":"Title: Vite doesn't update included js files when changed\nTags: vue.js, vite, quasar-framework\nSource: Stack Overflow\n\nQuestion:\nIn my Quasary CLI project I include my own js files like this:\n\n```\nimport Task from \"src/js/task.js\"\n```\n\nWhen I change something in this file (task.js) and save it, my changes are not visible or functional with hot reload. However I see this in the console:\n[vite] hot updated: /src/components/kk-phase-tasks.vue\n\nSo hot reload seems to recognize a change and updates.\n\nEven after reloading the page my changes are not build in.\n\nOnly after closing the dev server and start it again (quasar dev) my changes are reflected.\n\nDo I have to define folders or files that vite should update?\nWhat am I missing?\n\n========================================\n\nCode:\n```text\nimport Task from \"src/js/task.js\"\n```\n\n```text\nimport Task from \"src/js/Task.js\"\n```\n\n```text\ntask.js\n```\n\n========================================\n\nComments:\n- Same thing here. But in my case it was the oposite. I had imported the file with a missing first uppercase.\n- In my case it was because the import path didn't start with `&#47;`. I added it and it fixed the issue.","metadata":{"transformedAt":"2026-08-18T18:33:46.426Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":43,"estimatedTokens":292}}420{"id":"stack-76691769","source":"stackoverflow","questionId":76691769,"title":"How to use DecompressionStream to decompress a gzip file using JavaScript in Browser?","tags":["javascript","typescript","vite","webapi"],"text":"Title: How to use DecompressionStream to decompress a gzip file using JavaScript in Browser?\nTags: javascript, typescript, vite, webapi\nSource: Stack Overflow\n\nQuestion:\nAll major browsers now support the DecompressionStream API, but I can't figure out how to use it with `fetch()` to decompress a gzip file in browser.\n\nThe following code works with a base64 string:\n\n\r\n\r\n\n```\nconst decompress = async (url) => {\n const ds = new DecompressionStream('gzip');\n const response = await fetch(url);\n const blob_in = await response.blob();\n const stream_in = blob_in.stream().pipeThrough(ds);\n const blob_out = await new Response(stream_in).blob();\n return await blob_out.text();\n};\n\ndecompress(\n 'data:application/octet-stream;base64,H4sIAAAAAAAAE/NIzcnJVyjPL8pJAQBSntaLCwAAAA=='\n).then((result) => {\n console.log(result);\n});\n```\n\n\r\n\r\n\r\n\nHowever, if I create a `hello.txt.gz` file using `gzip hello.txt` on MacOS (`hello.txt` is a plain text file with content \"hello world\"), then the function above throws an Error.\n\n```\ndecompress('/hello.txt.gz').then((result) => {\n console.log(result);\n});\n```\n\n```\n# FireFox\nFailed to read data from the ReadableStream: “TypeError: The input data is corrupted: incorrect header check”.\nUncaught (in promise) DOMException: The operation was aborted.\n\n# Chrome\nUncaught (in promise) TypeError: Failed to fetch\n\n# Safari\n[Error] Unhandled Promise Rejection: TypeError: TypeError: Failed to Decode Data.\n[Error] Unhandled Promise Rejection: TypeError: Failed to Decode Data.\n```\n\n**Edit**\n\nThere is a reproducible demo at Stackblitz.\n\n========================================\n\nCode:\n```js\nconst decompress = async (url) => {\n  const ds = new DecompressionStream('gzip');\n  const response = await fetch(url);\n  const blob_in = await response.blob();\n  const stream_in = blob_in.stream().pipeThrough(ds);\n  const blob_out = await new Response(stream_in).blob();\n  return await blob_out.text();\n};\n\ndecompress(\n  'data:application/octet-stream;base64,H4sIAAAAAAAAE/NIzcnJVyjPL8pJAQBSntaLCwAAAA=='\n).then((result) => {\n  console.log(result);\n});\n```\n\n```text\ndecompress('/hello.txt.gz').then((result) => {\n  console.log(result);\n});\n```\n\n```bash\n# FireFox\nFailed to read data from the ReadableStream: “TypeError: The input data is corrupted: incorrect header check”.\nUncaught (in promise) DOMException: The operation was aborted.\n\n# Chrome\nUncaught (in promise) TypeError: Failed to fetch\n\n# Safari\n[Error] Unhandled Promise Rejection: TypeError: TypeError: Failed to Decode Data.\n[Error] Unhandled Promise Rejection: TypeError: Failed to Decode Data.\n```\n\n```text\nfetch()\n```\n\n```text\nhello.txt.gz\n```\n\n```text\ngzip hello.txt\n```\n\n```text\nhello.txt\n```\n\n```text\n\"content-encoding\": \"gzip\"\n​​\"content-length\": \"42\"\n\"content-type\": \"text/plain\"\n```\n\n```text\n.gz\n```\n\n```text\nhello.txt.gz\n```\n\n```text\nhello.txt.gzip\n```\n\n========================================\n\nComments:\n- *\"Failed to fetch\"* - does the file accessible in the first place?\n- It indeed looks like you're just hitting a 404 or alike. Check you path and your network tab. Also, from an URL like that you don't need to go to a Blob and then extract a stream from it, nor to produce a Blob from the Response to then get a text from it, you can directly do `const stream_in = response.body.pipeThrough(ds); return new Response(stream_in).text()` jsfiddle.net/yv5wzsrt\n- Thanks! @BagusTesa I added a demo at stackblitz.com/edit/vitejs-vite-vrvd2k?file=src%2Fmain.ts. The fetch response is 200.\n- Hi @Kaiido, I added a demo at stackblitz.com/edit/vitejs-vite-vrvd2k?file=src%2Fmain.ts . It seems the fetch response is okay (200). Thank you so much for your example! It worked with my `hello.txt.gz` file! I will keep looking into it.\n- Oh, that's interesting, but no, the response is not ok. The server sends the Content-Type as \"text/plain\" and the Content Encoding as \"gzip\", and it doesn't pass any data. Somehow the `.gz` extension makes it trip out in thinking it's one of its own response or something like that. Change the extension of your file e.g. to `.bin` and it will work fine. I'm really not sure why the server behaves like that, and I'm not sure either if it's only a stackblitz issue or if it's a default config. Just tried on my localhost (almost bare apache config) and it works fine, so that'd be a stackblitz issue.\n- Wow I see, thank you so much @Kaiido!! ❤️❤️ Changing to `.bin` worked for me. I guess there is something weird going on with the Vite server. They might be pre-processing files with extension `.gz`...\n- @Kaiido Could you please add a short answer so I can accept it and close the problem? 🙏\n- Related Vite issue: github.com/vitejs/vite/issues/12266\n- Oh I'm sorry I don't really have time right now to compose an answer, and the GH issue you found would make a far better answer than what I could have written, so feel free to self-answer :-) (Ps: I added retrospectively the vite issue for discoverability since this is actually the source of the issue).\n- Also, Response.body ( developer.mozilla.org/en-US/docs/Web/API/Response/body ) is already a ReadableStream, so you don't need to turn it into a blob first","metadata":{"transformedAt":"2026-08-18T18:33:46.426Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":144,"estimatedTokens":1285}}421{"id":"stack-77211052","source":"stackoverflow","questionId":77211052,"title":"MessageEvent console.log is spamming my console can&#180;t get rid of it","tags":["javascript","reactjs","console","vite","console.log"],"text":"Title: MessageEvent console.log is spamming my console can&#180;t get rid of it\nTags: javascript, reactjs, console, vite, console.log\nSource: Stack Overflow\n\nQuestion:\nMessage Event console.logs\nMessageEvent info\nSO, as you guys can see in the img, im getting swated by this console.logs, and need help removing them, it says they come from a conten getdify.js\n\nI know it is something i'm doing because they only appear when im working on a proyect or building something, in any other page this console.logs aren't there, im no expert but this thing is just annoying\n\nWell i reaaally tried searching for people with the same issue but no luck, guess im the only bastard with this things\n\nAt the beginning tried to search for every possible lose console.log left alone no luck\n\nEdit: Somethimes the console.log spamming just stop, I don't do anything different, just working suddenly stops.\n\n========================================\n\nTop Answer:\nYou could also right click on the alerts and click on:\n\nhttps://i.sstatic.net/RHyQq.png\n\nThat way, the browser saves the filter for the next time:\n\nhttps://i.sstatic.net/IjNfU.png\n\n========================================\n\nComments:\n- Well thats a good chance for you to start learning what \"debugger\" is, how to get to the line that logs messages, how to put a breakpoint and how to read the callstack after breakpoint hit. And google has no idea about what \"getdify.js\" is and we cant see whats inside of it to check why it spams console logs. So we are unable to help you due to we dont have any \"minimal reproducible example\".\n- See github.com/facebook/react-devtools/issues/812\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- Oh. That simple. Weird.\n- Indeed, I removed the React Dev Tools and it solved. Thanks!\n- It's not related to dev tools in any way. It's Opera's Dify cashback system which should be turned off. Opera is now bloated with tons of trash plugins causing various problems.\n- Indeed this solved everything\n- I had turned this off long ago however, I was also getting these messages. The fix that finally worked for me was to turn it off in the opera flags: opera://flags. See opera forum article forums.opera.com/topic/47377/addons-cashback-web-monitor/72","metadata":{"transformedAt":"2026-08-18T18:33:46.426Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":39,"estimatedTokens":615}}422{"id":"stack-76017338","source":"stackoverflow","questionId":76017338,"title":"Prevent creating definition files `d.ts` onstorybook build (Vite react library Project)","tags":["javascript","reactjs","typescript","vite","package.json"],"text":"Title: Prevent creating definition files `d.ts` onstorybook build (Vite react library Project)\nTags: javascript, reactjs, typescript, vite, package.json\nSource: Stack Overflow\n\nQuestion:\nI'm working on a component's library using react + typescript . I'm using vite and each time I build storybook, dts plugin runs.\n\nThat has 2 side effects:\n\n- It creates a lot of unnecessary folders and files\n\n- Takes extra time the CI build step\n\nThis is my `vite.config.ts`\n\n```\nimport { defineConfig } from \"vite\"\nimport { resolve } from \"path\"\nimport dts from \"vite-plugin-dts\"\nimport { viteStaticCopy } from \"vite-plugin-static-copy\"\n\nexport default defineConfig({\n publicDir: false,\n build: {\n lib: {\n entry: resolve(__dirname, \"src/index.ts\"),\n name: \"kb-lib\",\n fileName: \"index\",\n },\n rollupOptions: {\n external: [\"react\"],\n output: {\n globals: {\n react: \"React\",\n },\n assetFileNames: \"static/styles/components.css\",\n },\n },\n },\n plugins: [\n dts({\n insertTypesEntry: true,\n }),\n viteStaticCopy({\n targets: [\n {\n src: resolve(__dirname, \"src/static\"),\n dest: \"./\",\n },\n {\n src: resolve(__dirname, \"./README.md\"),\n dest: \"./\",\n rename: \"README.md\",\n },\n {\n src: resolve(__dirname, \"./package.json\"),\n dest: \"./\",\n },\n ],\n }),\n ],\n})\n```\n\nHere are the extra folders/files it creates:\n\nhttps://i.sstatic.net/UOKi0.png\n\nI wanna prevent the creation of `.d.ts` files on storybook building.\n\nIs there a way to prevent this behavior?\n\n========================================\n\nTop Answer:\nAdd in your .storybook/main.js|ts this:\n\n```\nimport { withoutVitePlugins } from '@storybook/builder-vite'\n...\nconst config: StorybookConfig = {\n ...\n async viteFinal(config) {\n return {\n ...config,\n plugins: await withoutVitePlugins(config.plugins, ['vite:dts']),\n }\n },\n}\n```\n\n========================================\n\nCode:\n```js\nimport { defineConfig } from \"vite\"\nimport { resolve } from \"path\"\nimport dts from \"vite-plugin-dts\"\nimport { viteStaticCopy } from \"vite-plugin-static-copy\"\n\nexport default defineConfig({\n  publicDir: false,\n  build: {\n    lib: {\n      entry: resolve(__dirname, \"src/index.ts\"),\n      name: \"kb-lib\",\n      fileName: \"index\",\n    },\n    rollupOptions: {\n      external: [\"react\"],\n      output: {\n        globals: {\n          react: \"React\",\n        },\n        assetFileNames: \"static/styles/components.css\",\n      },\n    },\n  },\n  plugins: [\n    dts({\n      insertTypesEntry: true,\n    }),\n    viteStaticCopy({\n      targets: [\n        {\n          src: resolve(__dirname, \"src/static\"),\n          dest: \"./\",\n        },\n        {\n          src: resolve(__dirname, \"./README.md\"),\n          dest: \"./\",\n          rename: \"README.md\",\n        },\n        {\n          src: resolve(__dirname, \"./package.json\"),\n          dest: \"./\",\n        },\n      ],\n    }),\n  ],\n})\n```\n\n```text\nvite.config.ts\n```\n\n```text\n.d.ts\n```\n\n```text\ndts\n```\n\n```text\nnpm run tsc\n```\n\n```text\nimport { withoutVitePlugins } from '@storybook/builder-vite'\n...\nconst config: StorybookConfig = {\n    ...\n    async viteFinal(config) {\n        return {\n            ...config,\n            plugins: await withoutVitePlugins(config.plugins, ['vite:dts']),\n        }\n    },\n}\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"declaration\": true,\n    \"declarationDir\": \"./build\",\n  },\n}\n```\n\n```ts\n//.storybook/maint.ts`\n\nconst config: StorybookConfig = {\n  // ...\n    async viteFinal(config) {\n    const { mergeConfig } = await import('vite');\n    /**\n     * `storybook build` does not reconcile the path correctly for the `vite:dts` plugin and causes the\n     * build to fail. By removing the plugin, storybook will successfully build.\n     */\n    const dtsIndex = config.plugins?.findIndex((plugin) => {\n      if (plugin && typeof plugin === 'object' && 'name' in plugin && plugin.name === 'vite:dts') {\n        return true;\n      }\n      return false;\n    });\n\n    // Remove `vite:dts` plugin from config.plugins array using the index provided in `dtsIndex`.\n    if (dtsIndex !== undefined && dtsIndex !== -1) {\n      config.plugins?.splice(dtsIndex, 1);\n    }\n\n    return mergeConfig(config, {\n      resolve: {\n        ...config.resolve,\n      },\n    });\n  },\n};\n\n\n  [1]: https://stackoverflow.com/questions/76017338/prevent-creating-definition-files-d-ts-onstorybook-build-vite-react-library-p#comment134090392_76017338\n```\n\n```text\nvite-plugin-dts\n```\n\n```text\ndeclarationDir\n```\n\n```text\ndts\n```\n\n```text\nviteFinal(config){ config.plugins.shift(); return config; }\n```\n\n========================================\n\nComments:\n- Why can't you just remove `dts(...)` from `plugins: [ dts(...) ]` ?\n- See storybook.js.org/docs/react/builders/vite#configuration\n- @Dimava I had a build step to create the library to publish to NPM that uses that plugin to create `d.ts` definition files. Also, I don't understand when you put the docs. I read it before, but I didn't find a solution for this.\n- you can `viteFinal(config){ config.plugins.shift(); return config; }` as far as I undestood\n- Thanks @Dimava I solved this removing `dts` plugin and moving the definitons generation to the tsc. This way I decoupled `d.ts` generation from Vite.\n- Very useful, thanks\n- Wonderful, works fine, thanks!","metadata":{"transformedAt":"2026-08-18T18:33:46.426Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":243,"estimatedTokens":1290}}423{"id":"stack-79756341","source":"stackoverflow","questionId":79756341,"title":"Vite keeps detecting Node.js 18 even though Node 22.12 is installed on Windows","tags":["reactjs","node.js","npm","vite","version"],"text":"Title: Vite keeps detecting Node.js 18 even though Node 22.12 is installed on Windows\nTags: reactjs, node.js, npm, vite, version\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a Vite + React project on Windows.\n\nI previously had an old Node version (18.20.5), but I installed nvm4w to manage Node versions and then installed Node.js 22.12.0.\n\nRunning node -v correctly returns:\n\nv22.12.0\n\nAnd Get-Command node in PowerShell shows:\n\nPath : C:\\nvm4w\\nodejs\\node.exe\nFileVersion : 22.12.0\n\nHowever, when I start the Vite dev server (npm run dev), I get the following error:\n\nYou are using Node.js 18.20.5. Vite requires Node.js version 20.19+ or 22.12+. Please upgrade your Node.js version.\nerror when starting dev server:\nTypeError: crypto.hash is not a function\n\n```\nYou are using Node.js 18.20.5. Vite requires Node.js version 20.19+ or 22.12+. Please upgrade your Node.js version.\nerror when starting dev server:\nTypeError: crypto.hash is not a function\n at getHash (file:///C:/Users/Leandro/Documents/Programacion_Web/Programacion/Anio2/REACT/React%20clase%201/vite-project/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:2648:21)\n at getLockfileHash (file:///C:/Users/Leandro/Documents/Programacion_Web/Programacion/Anio2/REACT/React%20clase%201/vite-project/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:11616:9)\n at getDepHash (file:///C:/Users/Leandro/Documents/Programacion_Web/Programacion/Anio2/REACT/React%20clase%201/vite-project/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:11619:23)\n at initDepsOptimizerMetadata (file:///C:/Users/Leandro/Documents/Programacion_Web/Programacion/Anio2/REACT/React%20clase%201/vite-project/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:11072:53)\n at createDepsOptimizer (file:///C:/Users/Leandro/Documents/Programacion_Web/Programacion/Anio2/REACT/React%20clase%201/vite-project/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:34740:17)\n at new DevEnvironment (file:///C:/Users/Leandro/Documents/Programacion_Web/Programacion/Anio2/REACT/React%20clase%201/vite-project/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:35505:109)\n at Object.defaultCreateClientDevEnvironment [as createEnvironment] (file:///C:/Users/Leandro/Documents/Programacion_Web/Programacion/Anio2/REACT/React%20clase%201/vite-project/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:35924:9)\n at _createServer (file:///C:/Users/Leandro/Documents/Programacion_Web/Programacion/Anio2/REACT/React%20clase%201/vite-project/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:28341:132)\n at async CAC. (file:///C:/Users/Leandro/Documents/Programacion_Web/Programacion/Anio2/REACT/React%20clase%201/vite-project/node_modules/vite/dist/node/cli.js:579:18)\n```\n\nI have already deleted node_modules, reinstalled the project from scratch, cleared caches (npm cache clean --force), and manually checked that no Node 18 folders exist, but Vite still insists on detecting Node 18.20.5.\n\nnode -v\nv22.19.0\n\n========================================\n\nTop Answer:\nI was having the exact same issue (using Vite v7, it kept detecting Node 21.2 even though I had Node 22.19 on PATH), but I found a \"brute-force\" way to fix it. Go inside the `node_modules/vite` directory in your project and find the exact line where Vite prints out `You are using Node.js...`. You can use the vscode search feature or some other tool, but for me it was in `node_modules/vite/dist/node/cli.js`.\n\nAbove the line where they print that warning, add this line:\n\n```\nconsole.log(`ghost node executable path: ${process.execPath}`);\n```\n\nRun `npm run dev` again and it should print out where your ghost version of node is. Then you can go delete it or otherwise remove it so Vite doesn't detect it, and it should proceed to use the correct version afterward.\n\n========================================\n\nCode:\n```text\nYou are using Node.js 18.20.5. Vite requires Node.js version 20.19+ or 22.12+. Please upgrade your Node.js version.\nerror when starting dev server:\nTypeError: crypto.hash is not a function\n    at getHash (file:///C:/Users/Leandro/Documents/Programacion_Web/Programacion/Anio2/REACT/React%20clase%201/vite-project/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:2648:21)\n    at getLockfileHash (file:///C:/Users/Leandro/Documents/Programacion_Web/Programacion/Anio2/REACT/React%20clase%201/vite-project/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:11616:9)\n    at getDepHash (file:///C:/Users/Leandro/Documents/Programacion_Web/Programacion/Anio2/REACT/React%20clase%201/vite-project/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:11619:23)\n    at initDepsOptimizerMetadata (file:///C:/Users/Leandro/Documents/Programacion_Web/Programacion/Anio2/REACT/React%20clase%201/vite-project/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:11072:53)\n    at createDepsOptimizer (file:///C:/Users/Leandro/Documents/Programacion_Web/Programacion/Anio2/REACT/React%20clase%201/vite-project/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:34740:17)\n    at new DevEnvironment (file:///C:/Users/Leandro/Documents/Programacion_Web/Programacion/Anio2/REACT/React%20clase%201/vite-project/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:35505:109)\n    at Object.defaultCreateClientDevEnvironment [as createEnvironment] (file:///C:/Users/Leandro/Documents/Programacion_Web/Programacion/Anio2/REACT/React%20clase%201/vite-project/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:35924:9)\n    at _createServer (file:///C:/Users/Leandro/Documents/Programacion_Web/Programacion/Anio2/REACT/React%20clase%201/vite-project/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:28341:132)\n    at async CAC.<anonymous> (file:///C:/Users/Leandro/Documents/Programacion_Web/Programacion/Anio2/REACT/React%20clase%201/vite-project/node_modules/vite/dist/node/cli.js:579:18)\n```\n\n```text\nnpm install\n```\n\n```text\nnpm install node\n```\n\n```text\nwhere node\nwhere npm\nwhere npx\nnode -e \"console.log('node:', process.version, '\\nexe:', process.execPath)\"\n```\n\n```text\nPATH\n```\n\n```text\nC:\\nvm4w\\nodejs\\\n```\n\n```text\nC:\\nvm4w\n```\n\n```text\nC:\\nvm4w\\nodejs\n```\n\n```text\nC:\\Program Files\\nodejs\n```\n\n```text\nconsole.log(`ghost node executable path: ${process.execPath}`);\n```\n\n```text\nnode_modules/vite\n```\n\n```text\nYou are using Node.js...\n```\n\n```text\nnode_modules/vite/dist/node/cli.js\n```\n\n```text\nnpm run dev\n```\n\n```text\nnvm - update with `nvm install -g @latest`\n```\n\n```text\nrm -rf node_modules package-lock.json\nnvm install 24.13.0   \nnpm install\n```\n\n```text\n.npmrc \n.nvmrc\n```\n\n```text\nengine-strict=true\n```\n\n```text\n24.13.0\n```\n\n========================================\n\nComments:\n- Windows has different terminals and they don't always play nice with each over. e.g. You might install something in vsCode and it'll not show up in powershell. Sometimes it comes right with a restart of the terminal. Maybe try another command terminal that is not powershell.\n- I already tried all of that. I deleted Node, nvm4w, and every trace of Node I could find. But when I reinstall Node and create the project again from scratch, as soon as I run Vite it always gives me the same error: You are using Node.js 18.20.5. and the error $ where npm C:\\Program Files\\nodejs\\npm C:\\Program Files\\nodejs\\npm.cmd C:\\Users\\Leandro\\AppData\\Roaming\\npm\\npm C:\\Users\\Leandro\\AppData\\Roaming\\npm\\npm.cmd $ where node C:\\Program Files\\nodejs\\node.exe $ node -e \"console.log('node:', process.version, '\\nexe:', process.execPath)\" node: v22.19.0 exe: C:\\Program Files\\n\n- @LeandroRodriguezValerio Okay. From where and how do you launch your terminal? Is it within an IDE? If so, your IDE may be forcing a node version, Webstorm for example has custom Node interpreters. Ensure that those aren't set up. Clear your `node_modules`. Finally, if all else fails, try installing Everything Search by VoidTools and query by `node` to find literally all your node installations and nuke everything and start over without installing v18.\n- Unfortunately, I couldn’t get it to work with those methods. Honestly, I don’t know what’s failing. I searched with Voidtools and there’s no Node 18 on my PC, but I found two temporary solutions that I’m going to post as an answer to my post.\n- Unfortunately, I couldn’t get it to work with that method. I tried creating the project in different directories and it didn’t work. Honestly, I don’t know what’s failing, but I found two solutions that I’m going to post as an answer to my post.\n- Even npm install node works for me also. Thanks!\n- npm install node did work for me indeed\n- Thank you. I had similar issue and i tried everything... reinstalling node , nvm, npm . npm install node works for me. Again thank you !\n- It worked...wtf... I was going insane. ty bro\n- Omg thank you. npm install node worked for me. I thought I was losing my mind. I did LITERALLY everything else (cleared the cache, made sure there was only 1 node version, etc).\n- This worked for me thanks! I had a duplicate node_modules installed with an older Node version somewhere on my desktop and vite kept picking it up. I found that folder using your log and deleted it. I reran the program and voila, vite starts picking the correct node_modules!","metadata":{"transformedAt":"2026-08-18T18:33:46.426Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":167,"estimatedTokens":2287}}424{"id":"stack-73192256","source":"stackoverflow","questionId":73192256,"title":"Use Jquery in Laravel Vite","tags":["jquery","laravel","vite"],"text":"Title: Use Jquery in Laravel Vite\nTags: jquery, laravel, vite\nSource: Stack Overflow\n\nQuestion:\nI get an error when try to import jquery in laravel VITE, jquery seems to be loaded in my compiled javascript:\n\n```\nUncaught TypeError: window.$ is not a function\n at dashboard:1823:12\n(anonimo) @ dashboard:1823\n[Violation]Forced reflow while executing JavaScript took 72ms\ndashboard:101 \n \n \n Uncaught Error: Bootstrap's JavaScript requires jQuery\n at app.0bbf2228.js:50:31\n```\n\nApp.js is:\n\n```\nimport vue from \"vue\";\nwindow.Vue = vue;\n\nimport jQuery from 'jquery'\nwindow.$ = jQuery;\n\nimport './bootstrap';\n```\n\n========================================\n\nTop Answer:\nFound an answer here:\n\nThis is because jQuery when imported in an ESM context considers itself in non-global mode and therefore does not put $ on window, but bootstrap is eagerly initialized on import and expects $ to be available on window.\n\nThis is unfortunately a case where jQuery and Bootstrap were designed without ESM in mind so they rely on implicit global coupling to work.\n\n– Evan You on the GitHub bug report\n\nhttps://www.mapledesign.co.uk/tech-blog/vite-bootstrap-4-jquery/\n\n========================================\n\nCode:\n```text\nUncaught TypeError: window.$ is not a function\n    at dashboard:1823:12\n(anonimo) @ dashboard:1823\n[Violation]Forced reflow while executing JavaScript took 72ms\ndashboard:101 \n \n        \n       Uncaught Error: Bootstrap's JavaScript requires jQuery\n    at app.0bbf2228.js:50:31\n```\n\n```text\nimport vue from \"vue\";\nwindow.Vue = vue;\n\n\nimport jQuery from 'jquery'\nwindow.$ = jQuery;\n\nimport './bootstrap';\n```\n\n```js\nimport $ from \"jquery\";\nwindow.$ = $;\n```\n\n```text\n@vite('resources/js/app.js')\n\n<script type=\"module\">\n$('h1').text('Hello, World')\n</script>\n```\n\n```text\n$\n```\n\n```text\nwindow\n```\n\n```text\n<script>\n```\n\n```text\n<script>\n```\n\n```text\n@vite\n```\n\n========================================\n\nComments:\n- What is the second script is also using `@vite('...')` to include the script?\n- I was missing the `type=\"module\"` attribute setting on `script`.","metadata":{"transformedAt":"2026-08-18T18:33:46.426Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":108,"estimatedTokens":517}}425{"id":"stack-79083166","source":"stackoverflow","questionId":79083166,"title":"How to replace includePaths in vite config when using the modern sass compiler","tags":["sass","vite"],"text":"Title: How to replace includePaths in vite config when using the modern sass compiler\nTags: sass, vite\nSource: Stack Overflow\n\nQuestion:\nI'm migrating a project to the new sass compiler, but it seems that vite is not passing the includePaths\n\n```\n{\ncss: {\n preprocessorOptions: {\n scss: {\n api: 'modern-compiler',\n includePaths: [ // This needs to be replaced\n path.resolve(\"views\"),\n path.resolve(\"views/scss/theme\"),\n ],\n },\n },\n },\n}\n```\n\nI get this error when building\n\n```\n[sass] Can't find stylesheet to import.\n@import \"views/scss/front/product/common\";\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n```\n\nWhat is the correct way to add include paths to the sass config?\n\nHere's what I tried\n\n```\n{\n css: {\n preprocessorOptions: {\n scss: {\n api: 'modern-compiler',\n importers: [\n {\n findFileUrl(url) {\n console.log(url); // this was not logged, so the importer was not called\n // if (!url.startsWith('~')) return null;\n // return new URL(url.substring(1), pathToFileURL('node_modules'));\n }\n }\n ]\n },\n },\n }\n}\n```\n\n========================================\n\nTop Answer:\nI partly resolved the issue by using an alias\n\nvite.config.ts\n\n```\nresolve: {\n alias: {\n \"@views\": path.resolve(\"views\"),\n },\n},\n```\n\nthen I changed the import to\n\n```\n@import \"@views/....\"\n```\n\n========================================\n\nCode:\n```js\n{\ncss: {\n    preprocessorOptions: {\n      scss: {\n        api: 'modern-compiler',\n        includePaths: [ // This needs to be replaced\n          path.resolve(\"views\"),\n          path.resolve(\"views/scss/theme\"),\n        ],\n      },\n    },\n  },\n}\n```\n\n```text\n[sass] Can't find stylesheet to import.\n@import \"views/scss/front/product/common\";\n        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n```\n\n```js\n{\n  css: {\n    preprocessorOptions: {\n      scss: {\n        api: 'modern-compiler',\n        importers: [\n        {\n          findFileUrl(url) {\n            console.log(url); // this was not logged, so the importer was not called\n            // if (!url.startsWith('~')) return null;\n            // return new URL(url.substring(1), pathToFileURL('node_modules'));\n          }\n        }\n      ]\n      },\n    },\n  }\n}\n```\n\n```js\nexport default defineConfig({\n  css: {\n    preprocessorOptions: {\n      scss: {\n        loadPaths: [\"./src/styles\"],\n      },\n    },\n  },\n});\n```\n\n```text\nvite\n```\n\n```text\nv6.0.0\n```\n\n```text\nincludePaths\n```\n\n```text\nloadPaths\n```\n\n```text\nvite.config.ts\n```\n\n```json\nresolve: {\n  alias: {\n    \"@views\": path.resolve(\"views\"),\n  },\n},\n```\n\n```scss\n@import \"@views/....\"\n```\n\n========================================\n\nComments:\n- I used a workaround like this because `loadPaths` didn't work in the versions I use. However, `resolve.alias` also affects JavaScript/TypeScript imports.\n- Thank you! I read this doc but couldn't understand it well, they should have added an example like you did! I appreciate your help.\n- Yeah, I had to dig through the source code to figure out. Anyways, glad it helped.","metadata":{"transformedAt":"2026-08-18T18:33:46.426Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":173,"estimatedTokens":735}}426{"id":"stack-69424422","source":"stackoverflow","questionId":69424422,"title":"Use `compilerOptions.baseUrl` with Vite.js project?","tags":["vite","esbuild"],"text":"Title: Use `compilerOptions.baseUrl` with Vite.js project?\nTags: vite, esbuild\nSource: Stack Overflow\n\nQuestion:\nI'm trying to migrate from Create React App to Vite.js, but I'm having issues with the import aliases.\n\nIn Create React App I have a `jsconfig.json` file with `compilerOptions.baseUrl` set to `src`, so that if I `import Comp from 'components/MyComponent` it gets automatically converted to a relative import that points to `src/components/MyComponent`.\n\nI can't understand how to achieve the same with Vite.js and esbuild?\n\n========================================\n\nTop Answer:\nIf you didn't like the accepted answer, you can achieve same behaviour using the npm package `vite-jsconfig-paths` (If you need typescript, use `vite-tsconfig-paths` instead) as described below.\n\nIn `vite.config.js` file :\n\n```\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport jsconfigPaths from 'vite-jsconfig-paths';\n\nexport default defineConfig({\n plugins: [\n react(),\n jsconfigPaths(),\n ],\n // ...other config\n});\n```\n\nIn `jsconfig.json` file :\n\n```\n{\n \"compilerOptions\": {\n \"baseUrl\": \"src\"\n }\n}\n```\n\nLets assume you have a folder structure like below :\n\n```\nroot_project\n│ README.md\n│ package.json \n│ vite.config.js\n└───src\n│ | app.js\n│ |___components\n| | |___ SomeComponent.jsx\n└───node_modules\n```\n\nWith this configuration, we give **Vite** the ability to resolve imports using `jsconfig.json` path mapping. Since we set `baseUrl: src` in our `jsconfig.json` file, we can import `SomeComponent.jsx` file as :\n\n`import SomeComponent from 'components/SomeComponent'`\n\n========================================\n\nCode:\n```text\njsconfig.json\n```\n\n```text\ncompilerOptions.baseUrl\n```\n\n```text\nsrc\n```\n\n```text\nimport Comp from 'components/MyComponent\n```\n\n```text\nsrc/components/MyComponent\n```\n\n```text\nroot_project\n│   README.md\n│   package.json    \n│\n└───resources\n│   │   index.html\n│   |   app.js\n│   |___components\n|   |   |\n|   |   |___ HelloWorld.svelte\n|   |\n│   │___assets\n|   |   |\n|   |   |___css\n|   |   |   |\n|   |   |   |___app.scss\n|   |   |   \n|   |___config\n|   |   |\n|   |   |___index.ts\n│   |\n└───node_modules\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport path from 'path'\nimport { readdirSync } from 'fs'\n\nconst absolutePathAliases: { [key: string]: string } = {};\n// Root resources folder\nconst srcPath = path.resolve('./resources/');\n// Ajust the regex here to include .vue, .js, .jsx, etc.. files from the resources/ folder\nconst srcRootContent = readdirSync(srcPath, { withFileTypes: true }).map((dirent) => dirent.name.replace(/(\\.ts){1}(x?)/, ''));\n\nsrcRootContent.forEach((directory) => {\n  absolutePathAliases[directory] = path.join(srcPath, directory);\n});\n\nexport default defineConfig({\n  root: 'resources',\n  resolve: {\n    alias: {\n      ...absolutePathAliases\n    }\n  },\n\n  build: {\n    rollupOptions: {\n      input: '/main.ts'\n    }\n  }\n});\n```\n\n```js\nimport HelloWorld from 'components/HelloWorld.svelte'\n```\n\n```js\nimport { foo } from 'config'\n```\n\n```js\nimport path from 'path'               // <--- global\nimport { foo } from 'config'          // <--- resources\nimport logoUrl from 'assets/logo.png' // <--- resources\n```\n\n```text\nroot\n```\n\n```text\nvite\n```\n\n```text\nvite.config.js\n```\n\n```text\nresources\n```\n\n```text\nresources\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport jsconfigPaths from 'vite-jsconfig-paths';\n\nexport default defineConfig({\n    plugins: [\n        react(),\n        jsconfigPaths(),\n    ],\n    // ...other config\n});\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"baseUrl\": \"src\"\n  }\n}\n```\n\n```text\nroot_project\n│   README.md\n│   package.json    \n│   vite.config.js\n└───src\n│   |   app.js\n│   |___components\n|   |   |___ SomeComponent.jsx\n└───node_modules\n```\n\n```text\nvite-jsconfig-paths\n```\n\n```text\nvite-tsconfig-paths\n```\n\n```text\nvite.config.js\n```\n\n```text\njsconfig.json\n```\n\n```text\njsconfig.json\n```\n\n```text\nbaseUrl: src\n```\n\n```text\njsconfig.json\n```\n\n```text\nSomeComponent.jsx\n```\n\n```text\nimport SomeComponent from 'components/SomeComponent'\n```\n\n========================================\n\nComments:\n- I am receiving This localhost page can’t be foundNo web page was found for the web address: localhost:3000 HTTP ERROR 404 :c\n- This worked for me whitout replacing regex. Maybe it's because I'm using @mui/material library.","metadata":{"transformedAt":"2026-08-18T18:33:46.426Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":248,"estimatedTokens":1096}}427{"id":"stack-78127595","source":"stackoverflow","questionId":78127595,"title":"How inject css in shadowDom with vite?","tags":["javascript","reactjs","vite"],"text":"Title: How inject css in shadowDom with vite?\nTags: javascript, reactjs, vite\nSource: Stack Overflow\n\nQuestion:\nI have vite config and React app.\n\n```\nimport react from '@vitejs/plugin-react';\nimport * as path from 'path';\nimport { defineConfig, splitVendorChunkPlugin } from 'vite';\nimport htmlPlugin from 'vite-plugin-html-config';\nimport { dependencies } from './package.json';\n\nconst exclVendors = ['react', 'react-router-dom', 'react-dom'];\nfunction renderChunks(deps: Record) {\n let chunks = {};\n Object.keys(deps).forEach((key) => {\n if (exclVendors.includes(key)) return;\n chunks[key] = [key];\n });\n return chunks;\n}\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n server: {\n port: 8082\n },\n envPrefix: 'APP_',\n resolve: {\n alias: [{ find: '@', replacement: path.resolve(__dirname, 'src') }],\n },\n plugins: [\n react(),\n htmlPlugin({ favicon: './src/assets/logo.svg' }),\n splitVendorChunkPlugin(),\n ],\n build: {\n sourcemap: false,\n rollupOptions: {\n output: {\n manualChunks: {\n ...renderChunks(dependencies),\n },\n },\n },\n },\n});\n```\n\nI want create app in shadow Dom.\n\nThe application is built in the shadow Dom but the css is added to the head.\n\nHow to add all css to shadow Dom ?\n\nI tried installing the vite-plugin-css-injected-by-js plugin but it did not move the css from the head css\n\nIn esbuild this is done by esbuild-css-modules-plugin, but I haven’t found how to do the same in vite.\n\n====\n\nAlternative solution with esbuild.\n\nThe config is very simple, but it does what I need. Very fast build and all css is added to the specified tag without making changes to the code.\n\n```\nconst buildParams = {\n entryPoints: entryPoints,\n bundle: true,\n metafile: true,\n outfile: outfile,\n format: \"esm\",\n loader: { \".js\": \"jsx\", \".json\": \"json\", \".png\": \"file\", \".jpeg\": \"file\", \".jpg\": \"dataurl\", \".svg\": \"dataurl\", \".woff\": \"file\" },\n color: true,\n minify: true,\n sourcemap: true,\n mainFields : [ 'module' , 'main' ],\n define: define,\n plugins: [\n glsl({\n minify: true\n }),\n aliasPlugin([{ find: '@', replacement: path.resolve(__dirname, 'src') }]),\n polyfillNode({\n process: true,\n buffer: true,\n }),\n cssModulesPlugin({\n inject: 'body',\n force: true,\n dashedIndents: true,\n emitDeclarationFile: false,\n localsConvention: 'camelCase',\n pattern: '[name]-[hash]-[local]'\n }),\n copy({\n resolveFrom: 'cwd',\n assets: {\n from: ['./index.esbuild.html'],\n to: ['./dist/index.html']\n },\n watch: false,\n })\n ]\n }\n\n let result = await esbuild.build(buildParams)\n```\n\n========================================\n\nTop Answer:\nI just published a package which may is a good solution for this problem:\n\n**vite-plugin-css-position**\n\nIt uses `vite-plugin-css-injected-by-js` under the hood but provides a more intuitive API. With this, it’s as simple as:\n\n```\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport { viteCssPosition } from \"vite-plugin-css-position\";\n\nexport default defineConfig({\n plugins: [viteCssPosition(), react()],\n});\n```\n\nAnd then within your app (which can also run inside the Shadow DOM):\n\n```\nimport StylesTarget from \"vite-plugin-css-position/react\";\n\nexport function App() {\n return (\n \n \n Your App Content\n \n );\n}\n```\n\nI needed a robust solution that also supports multiple React mounts on a single site, so I decided to make it reusable and publish it. It also supports HMR. Hope this helps!\n\n========================================\n\nCode:\n```text\nimport react from '@vitejs/plugin-react';\nimport * as path from 'path';\nimport { defineConfig, splitVendorChunkPlugin } from 'vite';\nimport htmlPlugin from 'vite-plugin-html-config';\nimport { dependencies } from './package.json';\n\nconst exclVendors = ['react', 'react-router-dom', 'react-dom'];\nfunction renderChunks(deps: Record<string, string>) {\n  let chunks = {};\n  Object.keys(deps).forEach((key) => {\n    if (exclVendors.includes(key)) return;\n    chunks[key] = [key];\n  });\n  return chunks;\n}\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  server: {\n    port: 8082\n  },\n  envPrefix: 'APP_',\n  resolve: {\n    alias: [{ find: '@', replacement: path.resolve(__dirname, 'src') }],\n  },\n  plugins: [\n    react(),\n    htmlPlugin({ favicon: './src/assets/logo.svg' }),\n    splitVendorChunkPlugin(),\n  ],\n  build: {\n    sourcemap: false,\n    rollupOptions: {\n      output: {\n        manualChunks: {\n          ...renderChunks(dependencies),\n        },\n      },\n    },\n  },\n});\n```\n\n```text\nconst buildParams = {\n        entryPoints: entryPoints,\n        bundle: true,\n        metafile: true,\n        outfile: outfile,\n        format: \"esm\",\n        loader: { \".js\": \"jsx\", \".json\": \"json\", \".png\": \"file\", \".jpeg\": \"file\", \".jpg\": \"dataurl\", \".svg\": \"dataurl\", \".woff\": \"file\" },\n        color: true,\n        minify: true,\n        sourcemap: true,\n        mainFields : [ 'module' , 'main' ],\n        define: define,\n        plugins: [\n            glsl({\n                minify: true\n            }),\n            aliasPlugin([{ find: '@', replacement: path.resolve(__dirname, 'src') }]),\n            polyfillNode({\n                process: true,\n                buffer: true,\n            }),\n            cssModulesPlugin({\n                inject: 'body',\n                force: true,\n                dashedIndents: true,\n                emitDeclarationFile: false,\n                localsConvention: 'camelCase',\n                pattern: '[name]-[hash]-[local]'\n            }),\n            copy({\n                resolveFrom: 'cwd',\n                assets: {\n                    from: ['./index.esbuild.html'],\n                    to: ['./dist/index.html']\n                },\n                watch: false,\n            })\n        ]\n    }\n\n    let result = await esbuild.build(buildParams)\n```\n\n```text\nimport styles from \"./App.css?inline\"\nfunction App() {\n  // ... other code\n  return (\n    <>\n      <style>{styles}</style>\n      <div className=\"chrome-extension-boilerplate\">\n        {/* ...other components*/}\n      </div>\n    </>\n  )\n}\n```\n\n```text\nfunction attachStyleToShadowDom(shadowWrapper: ShadowRoot, cssContent: string) {\n    // create a variable to attach the tailwind stylesheet\n    const style = document.createElement(\"style\")\n\n    //Attach the stylesheet as text\n    style.textContent = cssContent\n\n    // apply the style\n    shadowWrapper.appendChild(style)\n}\n\nexport function createShadowRoot(root: Element, styles: string) {\n    // Set shadow root inside of root element\n    const shadowRoot = root.attachShadow({ mode: \"open\" })\n    root.appendChild(shadowRoot)\n    // Add React App root node and styles\n    const rootIntoShadow = document.createElement(\"div\")\n    rootIntoShadow.id = appRootId\n    shadowRoot.appendChild(rootIntoShadow)\n    attachStyleToShadowDom(shadowRoot, styles)\n    return rootIntoShadow\n}\n```\n\n```text\n?inline\n```\n\n```js\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport { viteCssPosition } from \"vite-plugin-css-position\";\n\nexport default defineConfig({\n  plugins: [viteCssPosition(), react()],\n});\n```\n\n```tsx\nimport StylesTarget from \"vite-plugin-css-position/react\";\n\nexport function App() {\n  return (\n    <div>\n      <StylesTarget />\n      <span>Your App Content</span>\n    </div>\n  );\n}\n```\n\n```text\nvite-plugin-css-injected-by-js\n```\n\n========================================\n\nComments:\n- I didn't find a solution for vite. I made it simpler and started using esbuild. There are no such problems there.\n- There is an alternative to this solution, but you will be required to manage to inject the URL, you can use rollup-plugin-css-only to extract the CSS and point that in the URL Link. `` `plugins: [react(), crx({ manifest }), css({ output: \"bundle.css\" })],` github.com/EduardoAC/browser-extension-boilerplate/blob/mast&zwnj;&#8203;er/&hellip;\n- With esbuild, it is enough to specify only the tag where you need to add the css. This is the easiest and fastest option. github.com/indooorsman/esbuild-css-modules-plugin/blob/main/&zwnj;&#8203;&hellip; inject?: boolean | string | ((css: string, digest: string) => string);\n- Gotcha, that's a good choice indeed. Thanks for sharing\n- Just in case, I added the config that I use now. I don’t know how good it is, but it does what I need.","metadata":{"transformedAt":"2026-08-18T18:33:46.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":317,"estimatedTokens":2051}}428{"id":"stack-67261174","source":"stackoverflow","questionId":67261174,"title":"How to import type in vue3 setup script with typescript?","tags":["typescript","vuejs3","vite"],"text":"Title: How to import type in vue3 setup script with typescript?\nTags: typescript, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI want to use `` feature with props type check in typescript.\nBut it seems that `` didn't import RouteRecordRaw as a type but as a value?\nAnd if I run this code in vite, the browser console will print an error:\n\n\"Uncaught SyntaxError: The requested module '/node_modules/.vite/vue-router.js?v=52a879a7' does not provide an export named 'RouteRecordRaw'\"\n\nCode:\n\n```\n\nimport { RouteRecordRaw } from \"vue-router\";\n// VSCode will print an error: \"RouteRecordRaw\" only refers to a type, butisbeing used as a value here. (TS2693) \n\nimport { defineProps } from \"vue\";\n\nconst props = defineProps;\n}>();\n\nconst renderRoutes = props.routeList;\n\n```\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\" setup>\nimport { RouteRecordRaw } from \"vue-router\";\n// VSCode will print an error: \"RouteRecordRaw\" only refers to a type, butisbeing used as a value here. (TS2693) \n\nimport { defineProps } from \"vue\";\n\nconst props = defineProps<{\n  routeList: Array<RouteRecordRaw>;\n}>();\n\nconst renderRoutes = props.routeList;\n</script>\n```\n\n```text\n<script setup>\n```\n\n```text\n<script setup>\n```\n\n```js\nimport type { RouteRecordRaw } from \"vue-router\";\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.427Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":56,"estimatedTokens":322}}429{"id":"stack-72853762","source":"stackoverflow","questionId":72853762,"title":"Vue - Vite | Static svg assets","tags":["vue.js","svg","import","vuejs3","vite"],"text":"Title: Vue - Vite | Static svg assets\nTags: vue.js, svg, import, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nIn my Vue vite app, I am trying to use svg file as src attribute in html element.\n\n```\n\n```\n\nIn development, it works as expected.\nIn production, the src attribute of the image is *[object Object]*. I tried every approach from Vite documentation , but none of these could fix the issue. I am using vite-svg-loader, so I can use svg files as Vue Components. Could this be somehow related to the issue?\n\nThank you.\n\n========================================\n\nTop Answer:\nTry to import it as module then bind it to the `src` attribute :\n\n```\nimport mainBanner from \"~/assets/images/bg/main-banner.svg\"\n\n```\n\n========================================\n\nCode:\n```text\n<img class=\"...\" src=\"/src/assets/images/bg/main-banner.svg\" alt=\"Background\">\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport svgLoader from 'vite-svg-loader'\n\nexport default defineConfig({\n  plugins: [\n    svgLoader({\n      defaultImport: 'url', 👈\n    }),\n  ],\n})\n```\n\n```html\n👇\n<img src=\"@/assets/logo.svg?url\" />\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\n// import svgLoader from 'vite-svg-loader' ⛔️ delete\n\nexport default defineConfig({\n  plugins: [\n    // svgLoader() ⛔️ delete\n  ],\n})\n```\n\n```text\nvite-svg-loader\n```\n\n```text\nvite-svg-loader\n```\n\n```text\n*.svg\n```\n\n```text\n<img>.src\n```\n\n```text\n[object Object]\n```\n\n```text\n*.svg\n```\n\n```text\nurl\n```\n\n```text\nurl\n```\n\n```text\nvite-svg-loader\n```\n\n```text\n*.svg\n```\n\n```text\nvite-svg-loader\n```\n\n```text\nvite-svg-loader\n```\n\n```text\nimport mainBanner from \"~/assets/images/bg/main-banner.svg\"\n\n<img class=\"...\" :src=\"mainBanner\" alt=\"Background\">\n```\n\n```text\nsrc\n```\n\n```text\n<img :src=\"`/src/assets/images/bg/main-banner${bannerId}.svg`\" alt=\"Background\">\n```\n\n```text\n<img :src=\"`/main-banner${bannerId}.svg`\" alt=\"Background\">\n```\n\n```text\n<img :src=\"`/src/assets/images/bg/main-banner${bannerId}.svg`\" alt=\"Background\">\n```\n\n```text\nmain-banner1.svg\n```\n\n```text\nmain-banner2.svg\n```\n\n```text\npublic\n```\n\n```text\npublic\n```\n\n========================================\n\nComments:\n- Just in case, such technique will disable general CSS/styling support for the SVG. Related: stackoverflow.com/questions/4906148/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:46.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":154,"estimatedTokens":576}}430{"id":"stack-73505695","source":"stackoverflow","questionId":73505695,"title":"How apply tailwindcss styles to emails in Laravel 9 with vite","tags":["php","laravel","email","tailwind-css","vite"],"text":"Title: How apply tailwindcss styles to emails in Laravel 9 with vite\nTags: php, laravel, email, tailwind-css, vite\nSource: Stack Overflow\n\nQuestion:\nI am not able to make work styles in my mails blade.\n\nThe final goal is to have a layout for mails. By now, for testing puposes, I have:\n\n- The controller that sends the mail\n\n- The mail component\n\n- The maileable class\n\n- The layout for emails, as a duplicated of guest.blade.php jetstream file\n\n- One specific email blade file, the content to add in the previus layout, is a duplicated of welcome.blade.php jetstream file\n\napp\\Http\\Controllers\\TestController.php\n\n```\nuser())\n ->send(new TestingMail());\n return view('welcome');\n }\n}\n```\n\napp\\View\\Components\\MailLayout.php\n\n```\napp\\Mail\\TestingMail.php\n\n```\nview('mails.general');\n }\n}\n```\n\nresources\\views\\layouts\\mail.blade.php\n\n```\n\ngetLocale()) }}\">\n \n \n \n \n\n {{ config('app.name', 'Laravel') }}\n\n \n \n\n \n @vite(['resources/css/app.scss', 'resources/js/app.js'])\n \n \n \n {{ $slot }}\n \n \n\n```\n\nresources\\views\\mails\\general.blade.php\n\n```\n\n \n \n {{ __('Dashboard') }}\n \n \n\n \n \n \n \n \n \n \n\n```\n\nI receive the mail with no styles. The only help that I found was this link https://ralphjsmit.com/tailwind-css-multiple-configurations-laravel-mix but that was wrote for laravel mix, I don't have idea to migrate this webpack.mix.js to vite.\n\nAny help or orientation will be apreciated, thanks.\n\n**EDIT**\nI finnally made it work, combining the @Jaap's answer and other package:\nhttps://github.com/fedeisas/laravel-mail-css-inliner\n\nhttps://github.com/motomedialab/laravel-vite-helper\n\nvite helper is not ideal because it does not work when npm run dev is running, but it is sufficient for me.\n\n========================================\n\nTop Answer:\nI don't know if you still need this.\n\nBut I managed to get it to work nicely with some packages, a custom vite config and the --watch flag. Probably the best work around that I created for this.\n\nThis allows you to quickly build emails locally which almost works the same as `dev`\n\nFirst I created a file called `mail.scss` in `resources/css/` with these contents:\n\n```\n@import 'tailwindcss/base';\n@import 'tailwindcss/components';\n@import 'tailwindcss/utilities';\n```\n\nI only need the tailwind basics so I keep these for now.\n\nThen I installed these packages\n\n- https://github.com/fedeisas/laravel-mail-css-inliner\n\n- https://github.com/motomedialab/laravel-vite-helper\n\nAnd inside the config from `laravel-mail-css-inliner` I will add my SCSS file like:\n\n`config/css-inliner.php`\n\n```\n [\n public_path(vite('resources/css/mail.scss', 'build', true))\n ],\n\n];\n```\n\nNow I created a new vite config for just my emails that's really basic:\n\n`vite-email.config.js`\n\n```\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\n\nexport default defineConfig({\n plugins: [\n laravel({\n input: [\n 'resources/css/mail.scss',\n ],\n refresh: true,\n }),\n ],\n});\n```\n\nNow finally in my `package.json` I have added the following script:\n\n```\n{\n \"scripts\": {\n // Mail\n \"build:mail\": \"vite build --config ./vite-email.config.js --watch\",\n // General\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"build:server\": \"vite build --ssr\",\n \"build:all\": \"npm run build && npm run build:server\"\n },\n}\n```\n\nAs you see in the top script `build:mail` I am using the `vite-email.config.js` I created. This will only build the `mail.scss` to the `public/build` folder.\n\nNow I am also using the flag `--watch`. This enables rollup watcher and will watch all the files and trigger a rebuild.\n\nSo if I change `mail/order-sent.blade.php` and add some extra tailwindcss classes. It will rebuild again.\n\nBecause you're using a custom vite config, and you're only rebuilding your `mail.scss` and not `app.js` **and** `app.scss` for example, this will be really fast. It usually builds in roughly 100-500ms at me.\n\n========================================\n\nCode:\n```text\n<?php\nnamespace App\\Http\\Controllers;\n\nuse App\\Mail\\TestingMail;\nuse Illuminate\\Http\\Request;\nuse Illuminate\\Support\\Facades\\Mail;\n\nclass TestController extends Controller\n{\n    public function __invoke(Request $request)\n    {\n        $result = Mail::to($request->user())\n                ->send(new TestingMail());\n        return view('welcome');\n     }\n}\n```\n\n```text\n<?php\n\nnamespace App\\View\\Components;\n\nuse Illuminate\\View\\Component;\n\nclass MailLayout extends Component\n{\n    /**\n     * Create a new component instance.\n     *\n     * @return void\n     */\n    public function __construct()\n    {\n        //\n    }\n\n    /**\n     * Get the view / contents that represent the component.\n     *\n     * @return \\Illuminate\\Contracts\\View\\View|\\Closure|string\n     */\n    public function render()\n    {\n        return view('layouts.mail');\n    }\n}\n```\n\n```text\n<?php\n\nnamespace App\\Mail;\n\nuse Illuminate\\Bus\\Queueable;\nuse Illuminate\\Mail\\Mailable;\nuse Illuminate\\Queue\\SerializesModels;\n\nclass TestingMail extends Mailable\n{\n    use Queueable, SerializesModels;\n\n    /**\n     * Create a new message instance.\n     *\n     * @return void\n     */\n    public function __construct()\n    {\n        //\n    }\n\n    /**\n     * Build the message.\n     *\n     * @return $this\n     */\n    public function build()\n    {\n        return $this->view('mails.general');\n    }\n}\n```\n\n```text\n<!DOCTYPE html>\n<html lang=\"{{ str_replace('_', '-', app()->getLocale()) }}\">\n    <head>\n        <meta charset=\"utf-8\">\n        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n        <meta name=\"csrf-token\" content=\"{{ csrf_token() }}\">\n\n        <title>{{ config('app.name', 'Laravel') }}</title>\n\n        <!-- Fonts -->\n        <link rel=\"stylesheet\" href=\"https://fonts.bunny.net/css2?family=Nunito:wght@400;600;700&display=swap\">\n\n        <!-- Scripts -->\n        @vite(['resources/css/app.scss', 'resources/js/app.js'])\n    </head>\n    <body>\n        <div class=\"font-sans text-gray-900 antialiased\">\n            {{ $slot }}\n        </div>\n    </body>\n</html>\n```\n\n```text\n<x-mail-layout>\n    <x-slot name=\"header\">\n        <h2 class=\"font-semibold text-xl text-gray-800 leading-tight\">\n            {{ __('Dashboard') }}\n        </h2>\n    </x-slot>\n\n    <div class=\"py-12\">\n        <div class=\"max-w-7xl mx-auto sm:px-6 lg:px-8\">\n            <div class=\"bg-white overflow-hidden shadow-xl sm:rounded-lg\">\n                <x-jet-welcome />\n            </div>\n        </div>\n    </div>\n</x-mail-layout>\n```\n\n```text\nnpm run build\n```\n\n```text\n<style>\n```\n\n```text\nwelcome.blade.php\n```\n\n```text\nnpx tailwindcss -o build.css --minify\n```\n\n```text\n@vite('YOURPATH/build.css')\n```\n\n```css\n@import 'tailwindcss/base';\n@import 'tailwindcss/components';\n@import 'tailwindcss/utilities';\n```\n\n```php\n<?php\nreturn [\n    'css-files' => [\n        public_path(vite('resources/css/mail.scss', 'build', true))\n    ],\n\n];\n```\n\n```js\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\n\nexport default defineConfig({\n  plugins: [\n    laravel({\n      input: [\n        'resources/css/mail.scss',\n      ],\n      refresh: true,\n    }),\n  ],\n});\n```\n\n```json\n{\n    \"scripts\": {\n        // Mail\n        \"build:mail\": \"vite build --config ./vite-email.config.js --watch\",\n        // General\n        \"dev\": \"vite\",\n        \"build\": \"vite build\",\n        \"build:server\": \"vite build --ssr\",\n        \"build:all\": \"npm run build && npm run build:server\"\n    },\n}\n```\n\n```text\ndev\n```\n\n```text\nmail.scss\n```\n\n```text\nresources/css/\n```\n\n```text\nlaravel-mail-css-inliner\n```\n\n```text\nconfig/css-inliner.php\n```\n\n```text\nvite-email.config.js\n```\n\n```text\npackage.json\n```\n\n```text\nbuild:mail\n```\n\n```text\nvite-email.config.js\n```\n\n```text\nmail.scss\n```\n\n```text\npublic/build\n```\n\n```text\n--watch\n```\n\n```text\nmail/order-sent.blade.php\n```\n\n```text\nmail.scss\n```\n\n```text\napp.js\n```\n\n```text\napp.scss\n```\n\n========================================\n\nComments:\n- Works perfectly, thanks! Now I have other problem, in the package config file you must provide the path of css file in public dir, but vite generates public\\build\\assets\\app.68478134.css file, with this random number. I can't find in vite docs how to get this path dinamically from php\n- finnally I used a vite helper from github, it is not ideally because in dev not loads the styles...but in prouduction works. I will update the question.\n- What is the vite helper? @msolla\n- have problem imppoortinng the hot viiite fille :(\n- Yes, that is done. My resources\\views\\mails\\general.blade.php file is extending resources\\views\\layouts\\mail.blade.php and I include assets with vite there (@vite(['resources/css/app.scss', 'resources/js/app.js'])) I had run npm run build and npm run dev, but doesn't work.\n- Wow, this looks nice. I will test it as soon as possible. Thanks @Aspheleia !!\n- @msolla Did you end up testing this solution yet?\n- Using the public path results in file_get_contents errors.\n- @Oddman: were you able to solve the public path problem?\n- @YeasirArafatMajumder yes - you have to build the file, and then use the usual process vite path using the vite helper. And you can't have the dev process running for your CSS builds, else it all fucks up. It's extremely fickle. But once on production it's generally fine.\n- @Oddman For me locally it all works great, even with vite running in watch mode. but when i send the emails out, in gmail the email is not styled at all. Locally i trap the emials with mailhog and that looks good too! I am not sure what is wrong\n- @YeasirArafatMajumder that could be due to what classes you're using - google stirps a lot of unsupported styles - and if just one class contains unsupported styling, you won't see ANY styles. You will need to educate yourself on what they support - one thing, is rgba background colors, which tailwind uses by default.","metadata":{"transformedAt":"2026-08-18T18:33:46.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":454,"estimatedTokens":2436}}431{"id":"stack-73754777","source":"stackoverflow","questionId":73754777,"title":"Svelte: Import by absolute path does not work","tags":["typescript","svelte","vite"],"text":"Title: Svelte: Import by absolute path does not work\nTags: typescript, svelte, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to import enums, objects, functions, and svelte components by using absolute paths to files, but the compiler can't find them.\n\nThis is how i do the imports:\n\n```\n\n import { MyEnum } from \"src/lib/enums\";\n ... code ...\n\n```\n\nThe VS Code compiler does not complain about the path.\n\nI get the following error message on the window when running the app:\n\n```\n[plugin:vite:import-analysis] Failed to resolve import \"src/lib/enums\" from \"src\\lib\\GUI\\ObjectOnBoard.svelte\". Does the file exist?\n35 | \n36 | const { Object: Object_1 } = globals;\n37 | import { MyEnum } from \"src/lib/enums\";\n | ^\n```\n\nI have done some research, and i've found out that there might be some issues regarding my config files, but i don't know how to configure these files in order to make the referencing work. These are the config files (the ones i think are relevant?) in my project:\n\nvite.config.ts:\n\n```\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [svelte()],\n})\n```\n\nsvelte.config.js:\n\n```\nimport sveltePreprocess from 'svelte-preprocess'\n\nexport default {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: sveltePreprocess(),\n}\n```\n\ntsconfig.json:\n\n```\n{\n \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n \"compilerOptions\": {\n \"target\": \"esnext\",\n \"useDefineForClassFields\": true,\n \"module\": \"esnext\",\n \"resolveJsonModule\": true,\n \"baseUrl\": \".\",\n /**\n * Typecheck JS in `.svelte` and `.js` files by default.\n * Disable checkJs if you'd like to use dynamic types in JS.\n * Note that setting allowJs false does not prevent the use\n * of JS in `.svelte` files.\n */\n \"allowJs\": true,\n \"checkJs\": true,\n \"isolatedModules\": true,\n },\n \"include\": [\"src/**/*.d.ts\", \"src/**/*.{svelte,ts,js}\"],\n \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\nThe answer given below works for compiling the code, so now it actually runs which is awesome! But there are still some problem regarding VS Code autocompletion and error messages (red wiggly lines).\n\nSpecifying absolute paths works flawless inside of .svelte files, but in .ts files, typescript keeps alerting the error, eventhough the code compiles and works:\n\n```\n\"Cannot find module 'src/lib/objects/outlet' or its corresponding type declarations.\"\n```\n\nThis error statements appears within the file \"src/lib/MainDataStructure\".\n\nI've tried \"Restart TS Server\", but it does not help. I've looked at this question which has alot of suggestions on how to solve this, but none works for me.\n\nThis is my current tsconfig.json file:\n\n```\n{\n \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n \"compilerOptions\": {\n \"moduleResolution\": \"node\",\n \"target\": \"esnext\",\n \"useDefineForClassFields\": true,\n \"module\": \"esnext\",\n \"resolveJsonModule\": true,\n \"allowSyntheticDefaultImports\": true,\n /**\n * Typecheck JS in `.svelte` and `.js` files by default.\n * Disable checkJs if you'd like to use dynamic types in JS.\n * Note that setting allowJs false does not prevent the use\n * of JS in `.svelte` files.\n */\n \"allowJs\": true,\n \"checkJs\": true,\n \"isolatedModules\": true,\n \"baseUrl\": \".\",\n \"paths\": {\n \"src/*\": [\n \"src/*\"\n ],\n }\n },\n \"include\": [\"src/**/*.d.ts\", \"src/**/*.{svelte,ts,js}\"],\n \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\nThis is an image of my directory in the project:\n\nhttps://i.sstatic.net/UpZV1.png\n\n========================================\n\nTop Answer:\nThis is an answer to those who is using SvelteKit.\n\nReference:\n\nhttps://kit.svelte.dev/docs/configuration#alias\n\nUse case:\n\n```\n\n import 'src/app.css';\n\n```\n\nWhere the folder `src` is located at the root level of the project.\n\nSolution:\n\nThis section is needed in `svelte.config.js`.\n\n```\nconst config = {\n ...\n kit: {\n + alias: {\n + src: 'src',\n + },\n }\n};\n```\n\nNo need to change `vite.config.ts` or `tsconfig.json` manually as the documentation says Svelte will handle it.\n\nYou can also change the line to `$src: 'src'` to make it look closer to Svelte's convention.\n\n```\n\n import '$src/app.css';\n\n```\n\n========================================\n\nCode:\n```text\n<script lang=ts>\n    import { MyEnum } from \"src/lib/enums\";\n    ... code ...\n<script/>\n```\n\n```text\n[plugin:vite:import-analysis] Failed to resolve import \"src/lib/enums\" from \"src\\lib\\GUI\\ObjectOnBoard.svelte\". Does the file exist?\n35 |  \n36 |  const { Object: Object_1 } = globals;\n37 |  import { MyEnum } from \"src/lib/enums\";\n   |                              ^\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [svelte()],\n})\n```\n\n```text\nimport sveltePreprocess from 'svelte-preprocess'\n\nexport default {\n  // Consult https://github.com/sveltejs/svelte-preprocess\n  // for more information about preprocessors\n  preprocess: sveltePreprocess(),\n}\n```\n\n```text\n{\n  \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n  \"compilerOptions\": {\n    \"target\": \"esnext\",\n    \"useDefineForClassFields\": true,\n    \"module\": \"esnext\",\n    \"resolveJsonModule\": true,\n    \"baseUrl\": \".\",\n    /**\n     * Typecheck JS in `.svelte` and `.js` files by default.\n     * Disable checkJs if you'd like to use dynamic types in JS.\n     * Note that setting allowJs false does not prevent the use\n     * of JS in `.svelte` files.\n     */\n    \"allowJs\": true,\n    \"checkJs\": true,\n    \"isolatedModules\": true,\n  },\n  \"include\": [\"src/**/*.d.ts\", \"src/**/*.{svelte,ts,js}\"],\n  \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\n```text\n\"Cannot find module 'src/lib/objects/outlet' or its corresponding type declarations.\"\n```\n\n```text\n{\n  \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n  \"compilerOptions\": {\n    \"moduleResolution\": \"node\",\n    \"target\": \"esnext\",\n    \"useDefineForClassFields\": true,\n    \"module\": \"esnext\",\n    \"resolveJsonModule\": true,\n    \"allowSyntheticDefaultImports\": true,\n    /**\n     * Typecheck JS in `.svelte` and `.js` files by default.\n     * Disable checkJs if you'd like to use dynamic types in JS.\n     * Note that setting allowJs false does not prevent the use\n     * of JS in `.svelte` files.\n     */\n    \"allowJs\": true,\n    \"checkJs\": true,\n    \"isolatedModules\": true,\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"src/*\": [\n        \"src/*\"\n      ],\n    }\n  },\n  \"include\": [\"src/**/*.d.ts\", \"src/**/*.{svelte,ts,js}\"],\n  \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\n```json\n{\n    \"compilerOptions\": {\n        \"paths\": {\n            \"src/*\": [\n                \"src/*\"\n            ],\n        },\n        // ...\n}\n```\n\n```text\n// ...\nimport path from 'path';\n\nexport default defineConfig({\n    // ...\n    resolve: {\n        alias: {\n            src: path.resolve('src/'),\n        },\n    }\n});\n```\n\n```text\ntsconfig/svelte\n```\n\n```text\nsrc\n```\n\n```text\ntsconfig.json\n```\n\n```text\nbaseUrl\n```\n\n```text\n'.'\n```\n\n```text\nsrc\n```\n\n```text\nvite-tsconfig-paths\n```\n\n```text\nvite.config.js\n```\n\n```text\ntsconfig\n```\n\n```text\n<script>\n    import 'src/app.css';\n</script>\n```\n\n```text\nconst config = {\n    ...\n    kit: {\n        + alias: {\n        +   src: 'src',\n        + },\n    }\n};\n```\n\n```text\n<script>\n    import '$src/app.css';\n</script>\n```\n\n```text\nsrc\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nvite.config.ts\n```\n\n```text\ntsconfig.json\n```\n\n```text\n$src: 'src'\n```\n\n========================================\n\nComments:\n- I tried adding \"paths\": { \"src/*\" : [ \"src/*\" ] } into compilerOptions, but it does not yet work. I don't think i can you on Node module resolution and baseUrl, could you elaborate?\n- If you look at the `vite.config.js`, it has an import from `'vite'`. There is no such folder => By default imports look for modules in `node_modules` (unless they start with a `.`). This lookup mechanism is called \"module resolution\", and searching for `node_modules` is the mechanism for Node.\n- The `baseUrl` option specifies what folder the paths used with the `path` option and other imports are relative to.\n- (The TS config from `@tsconfig&#47;svelte` sets `\"moduleResolution\": \"node\"`, by the way.)\n- I don't really know what i want to set my configurations to, all i know is i want to specify the locations of files as like \"src/lib/enums\", and your answer does not seem to work for me unfortunately. Appart from adding \"paths\": { \"src/*\" : [ \"src/*\" ] } to compilerOptions, is there anything else i'm missing?\n- I just noticed that Vite needs additional setup to handle this; edited my answer.\n- Added some more info for a manual Vite fix.\n- Amazing, adding the vite-tsconfig-paths package worked!\n- Now i find, as you mentioned, that code completion regarding absolute path in typescript does not work, VS Code is giving an error on the absolute path, eventhough the code compiles and works (only in .ts files, .svelte files works fine). You mention the tsconfig file, what should i correct to make autocompletion work and get rid of the VS Code error?\n- Depends on your folder structure, also make sure to restart the TS language server after changes to the config. Would recommend checking other questions like this one.\n- I've tried almost every combination on the question you sent in the comment, but nothing works. I'm updating my question with further information...\n- Sorry, I do not know what the issue with that might be. I would suggest moving that to a separate question since this is mainly a dev tooling issue, unrelated to Svelte.\n- Both work for me: kit.alias in svelte.config.js, or resolve.alias in vite.config.js, or both together.","metadata":{"transformedAt":"2026-08-18T18:33:46.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":391,"estimatedTokens":2420}}432{"id":"stack-76689520","source":"stackoverflow","questionId":76689520,"title":"Can Shadcn ui be installed for Vite + React with javascript and not typescript?","tags":["reactjs","typescript","tailwind-css","vite"],"text":"Title: Can Shadcn ui be installed for Vite + React with javascript and not typescript?\nTags: reactjs, typescript, tailwind-css, vite\nSource: Stack Overflow\n\nQuestion:\nI am having trouble installing and using shadcn components on mt vite + react + tailwind project. i tried following the guide in their documentation here. It seems that it requires typescript for it to work?\n\nI tried to:\n\n- Create a React Javascript project with Vite\n\n- Install Tailwind for Vite React from their doc.\n\n- the shadcn guide in their docs i linked above.\n\nIt says it needs the \"tsconfig.json\" file, which means typescript. I then tried the steps above again, but instead of javascript i created a Typescript project. But it still did not work, i get this error when i try to run the server with `npm run dev` :\nEISDIR: illegal operation on a directory, read\n\nI have uploaded the source code on github here\n\n========================================\n\nTop Answer:\nTypeScript is the recommended way but they provide components in JavaScript version too which you can use by:\n\n- create `jsconfig.json` in root folder instead of `tsconfig.json` and paste the below content:\n\n```\n{\n \"compilerOptions\": {\n \"baseUrl\": \".\",\n \"paths\": {\n \"@/*\": [\"./src/*\"]\n }\n }\n}\n```\n\n- Update your `vite.config.js` code with below content:\n\n```\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport tailwindcss from \"@tailwindcss/vite\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\n// https://vite.dev/config/\nexport default defineConfig({\n plugins: [react(), tailwindcss()],\n resolve: {\n alias: {\n \"@\": path.resolve(__dirname, \"./src\"),\n },\n },\n});\n```\n\n- Run on terminal (Verifies everything and initialize shadcn)\n\n```\nnpx shadcn-ui@latest init\n```\n\n========================================\n\nCode:\n```text\nnpm run dev\n```\n\n```text\nimport { Button } from \"@/components/ui/button\"\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@/*\": [\"./src/*\"]\n    }\n  }\n}\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport path from \"path\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  resolve: {\n    alias: {\n      \"@\": path.resolve(__dirname, \"./src\"),\n    },\n  },\n});\n```\n\n```text\njsconfig.json\n```\n\n```text\nvite.config.js\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@/*\": [\"./src/*\"]\n    }\n  }\n}\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport path from \"path\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  resolve: {\n    alias: {\n      \"@\": path.resolve(__dirname, \"./src\"),\n    },\n  },\n});\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@/*\": [\"./src/*\"]\n    }\n  }\n}\n```\n\n```js\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport tailwindcss from \"@tailwindcss/vite\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\n// https://vite.dev/config/\nexport default defineConfig({\n  plugins: [react(), tailwindcss()],\n  resolve: {\n    alias: {\n      \"@\": path.resolve(__dirname, \"./src\"),\n    },\n  },\n});\n```\n\n```bash\nnpx shadcn-ui@latest init\n```\n\n```text\njsconfig.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\nvite.config.js\n```\n\n========================================\n\nComments:\n- The code for most if not all of the components use TypeScript. you can download them and remove the typescript annotations probably (and have less intellisense and such). if you're intent on using javascript, nothings stopping you from setting up a TypeScript project and then using JavaScript for your own stuff (though i highly recommend learning basic TypeScript). as for your error, i would completely delete the project folders you made for this and make a new ts project through vite. make sure you're either on the latest version of node or using the LTS version of node\n- @Samathingamajig thanks for your reply! I did create a ts vite project with react and i followed the docs and added/installed the button component just to test it but i got this error message. did i configure something wrong?\n- code styling is corrupted.","metadata":{"transformedAt":"2026-08-18T18:33:46.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":194,"estimatedTokens":1109}}433{"id":"stack-76555816","source":"stackoverflow","questionId":76555816,"title":"Laravel Vite assets from https","tags":["laravel","https","vite"],"text":"Title: Laravel Vite assets from https\nTags: laravel, https, vite\nSource: Stack Overflow\n\nQuestion:\nVite on production is taking assets from `http` despite APP_URL is set to `https://`.\n\nhttps://i.sstatic.net/iLjQX.png\n\nHow to resolve this in the Vite config? I can't change Laravel AppServiceProvider to force to use https because this would cause other issues.\n\nI use `@vite` directive to get resources, I can change that if needed:\n\n```\n@vite('resources/js/app.js')\n```\n\nI tried `vite build -- --https` but this doesn't seem to work.\n\n========================================\n\nCode:\n```text\n@vite('resources/js/app.js')\n```\n\n```text\nhttp\n```\n\n```text\nhttps://\n```\n\n```text\n@vite\n```\n\n```text\nvite build -- --https\n```\n\n```text\nASSET_URL\n```\n\n```text\n.env\n```\n\n```text\nhttp://\n```\n\n========================================\n\nComments:\n- also, clear config cache .\n- @franciso - this is using AppServiceProvider - I can't do that.\n- i've same problem, but adding ASSET_URL with https:// not solving my problem","metadata":{"transformedAt":"2026-08-18T18:33:46.427Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":60,"estimatedTokens":252}}434{"id":"stack-75207113","source":"stackoverflow","questionId":75207113,"title":"ERR_NO_BUFFER_SPACE error on M1 Macbook Pro","tags":["macos","websocket","vite"],"text":"Title: ERR_NO_BUFFER_SPACE error on M1 Macbook Pro\nTags: macos, websocket, vite\nSource: Stack Overflow\n\nQuestion:\nI have been using the Macbook Pro M1 for web development for the past 7 months.\n\nLately, after about 1-2 minutes of starting my dev server (React with Vite and Gatsby), I get an ERR_NO_BUFFER_SPACE in Chrome, and I don't have an internet connection.\n\nMy co-workers with non-M1 Macbooks do not have the same issue.\n\n========================================\n\nTop Answer:\nSo looking for this error in Chromium we get a reference to ENOBUFS in the source code here:\n\nhttps://chromium.googlesource.com/chromium/src/+/HEAD/net/base/net_errors_posix.cc\n\nAccording to this https://www.encyclo.co.uk/meaning-of-ENOBUFS the error is due to:\n\nIn programming, ENOBUFS is a POSIX error code defined in . This condition caused by lack of memory in the OS`s buffers. Typically occurs in socket programming\n\nI would suspect that there's a bug in the socket programming in Chrome that is mostly manifested in the ARM version of the operating system. This could either be a Chrome bug or an OS bug.\n\nIn this message https://groups.google.com/g/nodejs/c/ahVUQHRVhAo?pli=1 it suggests that it could be caused by excessive writes. Could something in your React code be overloading a network buffer?\n\n========================================\n\nComments:\n- I encountered the same error message today. Solved after a reboot.(also M1 MBA)","metadata":{"transformedAt":"2026-08-18T18:33:46.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":30,"estimatedTokens":357}}435{"id":"stack-75913640","source":"stackoverflow","questionId":75913640,"title":"How to add a loader (less-loader) to vite.js (vite.config.js)?","tags":["javascript","less","vite"],"text":"Title: How to add a loader (less-loader) to vite.js (vite.config.js)?\nTags: javascript, less, vite\nSource: Stack Overflow\n\nQuestion:\nI started using Vite.js and I want to use less files in my project, I didn't find a clear solution to add a loader, especially less-loader beceause I am using Ant Design v4.\n\nI used :\n\n```\nimport react from '@vitejs/plugin-react';\n\nexport default {\n plugins: [react()],\n css: {\n preprocessorOptions: {\n less: {\n javascriptEnabled: true,\n },\n },\n },\n};\n```\n\nbut it doesn't work, and I tried :\n\n```\nimport react from '@vitejs/plugin-react';\n\nexport default {\n plugins: [\n {\n name: 'less',\n transform(code, id) {\n if (id.endsWith('.less')) {\n return require('less').renderSync({ data: code }).css;\n }\n },\n },\n ],\n css: {\n modules: {\n localsConvention: 'camelCaseOnly',\n },\n preprocessorOptions: {\n less: {\n javascriptEnabled: true,\n },\n },\n },\n};\n```\n\nnothing works, I asked chatGPT but it gave me random solution and nones worked, any solution or article to learn how to configure loaders in vite.js ?\n\n========================================\n\nCode:\n```text\nimport react from '@vitejs/plugin-react';\n\nexport default {\n  plugins: [react()],\n  css: {\n    preprocessorOptions: {\n      less: {\n        javascriptEnabled: true,\n      },\n    },\n  },\n};\n```\n\n```text\nimport react from '@vitejs/plugin-react';\n\nexport default {\n  plugins: [\n    {\n      name: 'less',\n      transform(code, id) {\n        if (id.endsWith('.less')) {\n          return require('less').renderSync({ data: code }).css;\n        }\n      },\n    },\n  ],\n  css: {\n    modules: {\n      localsConvention: 'camelCaseOnly',\n    },\n    preprocessorOptions: {\n      less: {\n        javascriptEnabled: true,\n      },\n    },\n  },\n};\n```\n\n```text\ncss: {\n    preprocessorOptions: {\n      less: {\n        math: \"always\",\n        relativeUrls: true,\n        javascriptEnabled: true\n      },\n    },\n  }\n```\n\n```text\nless\n```\n\n```text\nmath\n```\n\n```text\nrelativeUrls\n```\n\n```text\njavascriptEnabled\n```\n\n```text\nvite+reactjs+antd+less\n```\n\n========================================\n\nComments:\n- For more information, I found details in Vite.js documentation","metadata":{"transformedAt":"2026-08-18T18:33:46.427Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":136,"estimatedTokens":534}}436{"id":"stack-78562367","source":"stackoverflow","questionId":78562367,"title":"Electron - React app __dirname is not defined","tags":["reactjs","electron","vite","electron-forge"],"text":"Title: Electron - React app __dirname is not defined\nTags: reactjs, electron, vite, electron-forge\nSource: Stack Overflow\n\nQuestion:\nI have an electron app that I'm packaging with vite using the forge template. I'm having trouble pulling in the `ipcRenderer` into the React files as it crashes the app with this error:\n\n```\nUncaught ReferenceError: __dirname is not defined\n at node_modules/electron/index.js (electron.js?v=fee19837:36:30)\n at __require (chunk-CEQRFMJQ.js?v=fee19837:11:50)\n at electron.js?v=fee19837:54:16\n```\n\nI've tried different approaches to fix this but still no luck:\n\n- Using `import.meta.url`:\n\n```\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n```\n\n- Using `vite.config.js`:\n\n```\nexport default defineConfig({\n plugins: [\n commonjs(),\n NodeGlobalsPolyfillPlugin({\n process: true,\n buffer: true,\n }),\n ],\n resolve: {\n alias: {\n '@': path.resolve(__dirname, './src'),\n },\n },\n define: {\n 'process.env': {},\n '__dirname': '__dirname', // This is a simple way to inject __dirname\n },\n});\n```\n\n- Exposing `ipcRenderer` in `preload.ts`:\n\n```\ncontextBridge.exposeInMainWorld('ipcRenderer', ipcRenderer)\n```\n\n- Using `browserify` in vite config\n\n```\nalias: {\n '@': path.resolve(__dirname, './src'),\n path: 'path-browserify'\n}\n```\n\nNone of them work and I still get the same error.\n\nHere is my tsconfig:\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"ESNext\",\n \"module\": \"commonjs\",\n \"allowJs\": true,\n \"skipLibCheck\": true,\n \"esModuleInterop\": true,\n \"noImplicitAny\": true,\n \"sourceMap\": true,\n \"baseUrl\": \".\",\n \"outDir\": \"dist\",\n \"moduleResolution\": \"node\",\n \"resolveJsonModule\": true,\n \"jsx\": \"react-jsx\",\n \"paths\": {\n \"*\": [\"node_modules/*\"]\n }\n },\n \"include\": [\"src/**/*.ts\", \"src/**/*.tsx\"],\n}\n```\n\nI'm using Electron v30.0.9\n\n========================================\n\nTop Answer:\nI had the same issue using electron - vue - vite, try to delete the usage of electron from your renderer process.\n\n========================================\n\nCode:\n```bash\nUncaught ReferenceError: __dirname is not defined\n    at node_modules/electron/index.js (electron.js?v=fee19837:36:30)\n    at __require (chunk-CEQRFMJQ.js?v=fee19837:11:50)\n    at electron.js?v=fee19837:54:16\n```\n\n```js\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n```\n\n```js\nexport default defineConfig({\n  plugins: [\n    commonjs(),\n    NodeGlobalsPolyfillPlugin({\n      process: true,\n      buffer: true,\n    }),\n  ],\n  resolve: {\n    alias: {\n      '@': path.resolve(__dirname, './src'),\n    },\n  },\n  define: {\n    'process.env': {},\n    '__dirname': '__dirname', // This is a simple way to inject __dirname\n  },\n});\n```\n\n```js\ncontextBridge.exposeInMainWorld('ipcRenderer', ipcRenderer)\n```\n\n```js\nalias: {\n  '@': path.resolve(__dirname, './src'),\n  path: 'path-browserify'\n}\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"module\": \"commonjs\",\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"esModuleInterop\": true,\n    \"noImplicitAny\": true,\n    \"sourceMap\": true,\n    \"baseUrl\": \".\",\n    \"outDir\": \"dist\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"jsx\": \"react-jsx\",\n    \"paths\": {\n      \"*\": [\"node_modules/*\"]\n    }\n  },\n  \"include\": [\"src/**/*.ts\", \"src/**/*.tsx\"],\n}\n```\n\n```text\nipcRenderer\n```\n\n```text\nimport.meta.url\n```\n\n```text\nvite.config.js\n```\n\n```text\nipcRenderer\n```\n\n```text\npreload.ts\n```\n\n```text\nbrowserify\n```\n\n```js\ncontextBridge.exposeInMainWorld(\"ipcRenderer\", ipcRenderer); // Bad, not secure\n```\n\n```js\nimport { fileURLToPath } from \"url\";\nimport path from \"path\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n```\n\n```text\nelectron\n```\n\n```text\n__dirname\n```\n\n```text\nelectron\n```\n\n```text\n__dirname\n```\n\n```text\nBrowserWindow\n```\n\n========================================\n\nComments:\n- And to add—this could be caused by any dependency to your backend process code. I frequently types between frontend and backend processes—which is fine since it's typescript only, and therefore not compiled into the build. However, I referenced a backend constant from a frontend component and this had the side-effect of pulling electron into the frontend.","metadata":{"transformedAt":"2026-08-18T18:33:46.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":225,"estimatedTokens":1058}}437{"id":"stack-79201371","source":"stackoverflow","questionId":79201371,"title":"React Router Future Flag Warning in Remix Vite app","tags":["react-router","vite","remix.run"],"text":"Title: React Router Future Flag Warning in Remix Vite app\nTags: react-router, vite, remix.run\nSource: Stack Overflow\n\nQuestion:\nI'm using Remix with a modern `npx create-remix@latest` (cloudflare) template. It uses React router under the hood (Remix does), but I don't explicitly use React router anywhere in my code.\n\nNow I get this warning:\n\n⚠️ React Router Future Flag Warning: The revalidation behavior after\n4xx/5xx `action` responses is changing in v7. You can use the\n`v7_skipActionErrorRevalidation` future flag to opt-in early. For more\ninformation, see\nhttps://reactrouter.com/v6/upgrading/future#v7_skipactionerrorrevalidation.\n\nClicking on the link gives me suggestions on how to edit the component to fix this, but I don't have such a component in my app.\n\nThese are my de(relevant) pendencies:\n\n```\n\"@remix-run/cloudflare\": \"^2.11.1\",\n\"@remix-run/cloudflare-pages\": \"^2.11.1\",\n\"@remix-run/react\": \"^2.11.1\",\n\"remix-utils\": \"^7.6.0\",\n```\n\nWhat do I do to make these warning logs go away / to fix this?\n\n========================================\n\nTop Answer:\n```\n\n```\n\n========================================\n\nCode:\n```text\n\"@remix-run/cloudflare\": \"^2.11.1\",\n\"@remix-run/cloudflare-pages\": \"^2.11.1\",\n\"@remix-run/react\": \"^2.11.1\",\n\"remix-utils\": \"^7.6.0\",\n```\n\n```text\nnpx create-remix@latest\n```\n\n```text\naction\n```\n\n```text\nv7_skipActionErrorRevalidation\n```\n\n```js\nimport { vitePlugin as remix } from \"@remix-run/dev\";\nimport { defineConfig } from \"vite\";\n\nexport default defineConfig({\n  plugins: [\n    remix({\n      ....,\n      future: {\n        /* any enabled future flags */\n        v7_skipActionErrorRevalidation: true, // <-- early opt-in\n      },\n      ....,\n    }),\n  ],\n});\n```\n\n```text\nv7_skipActionErrorRevalidation\n```\n\n```text\nnpm install react-router-dom@latest\n```\n\n```js\nimport { createBrowserRouter, RouterProvider, Navigate } from \"react-router-dom\";\n\nimport Home from \"./pages/Home\";\nimport Login from \"./pages/Login\";\nimport PageNotFound from \"./pages/PageNotFound\";\n\n// Configure the router with future flags enabled\nconst router = createBrowserRouter(\n  [\n    { path: \"/\", element: <Navigate to=\"/login\" /> }, // Redirect to \"/login\"\n    { path: \"/login\", element: <Login /> },\n    { path: \"/home\", element: <Home /> },\n    { path: \"*\", element: <PageNotFound /> }, // Fallback for unknown routes\n  ],\n  {\n    future: {\n      v7_relativeSplatPath: true, // Enables relative paths in nested routes\n      v7_fetcherPersist: true,   // Retains fetcher state during navigation\n      v7_normalizeFormMethod: true, // Normalizes form methods (e.g., POST or GET)\n      v7_partialHydration: true, // Supports partial hydration for server-side rendering\n      v7_skipActionErrorRevalidation: true, // Prevents revalidation when action errors occur\n    },\n  }\n);\n\nfunction App() {\n  return (\n    <RouterProvider\n      future={{ v7_startTransition: true }} // Enables React's startTransition API\n      router={router}\n    />\n  );\n}\n\nexport default App;\n```\n\n```js\n<BrowserRouter\n  future={{\n    v7_startTransition: true,\n    v7_relativeSplatPath: true,\n  }}>\n```\n\n========================================\n\nComments:\n- These are just warnings about future features so in all likelihood you can probably ignore them. Have you checked the Remix.run docs on configurability?\n- Yes this was my thinking too. I kind of live and die with console messages haha, but I understand that a little wait will probably do the trick.\n- This is indeed the place where I can add feature flags (there are v3_ flags present there). It still doesn't remove the warning at this point, but thanks for pointing me to this file, for this particular log I'll just sit it out :)\n- @Sventies Yeah, I tried to provide as much an answer without outright saying something crazy like \"this is how you remove the warning\". Based on the messaging it reads more informational to me than anything \"bad\" is happening.\n- @Sventies The Remix.run/React-Router-DOM landscape is also becoming quite muddled. I thought it at least a little bit odd that you'd see RRDv7 future flag \"warnings\" when you are using Remix v2. I've read a few of their blogs that *basically* state that RRDv7 and Remix v3 will effectively be the same thing, and Remix only ships the extra bits for Server-Side-Rendering. So in that regard, I guess I shouldn't be surprised that future feature flags bleed over a bit.\n- @Sventies And React-Router 7 dropped yesterday. Looking through the CHANGELOG.md I noticed that for version 6.28.0 they \"added deprecation warnings for any future flags that you have not yet opted into. Please use the flags to better prepare for eventually upgrading to v7\", which is what I think you ran into.\n- Welcome. See how to answer to improve on your contributions. As it stands this is likely seen as a poor one.\n- Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. **Would you kindly edit your answer to include additional details for the benefit of the community?**","metadata":{"transformedAt":"2026-08-18T18:33:46.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":140,"estimatedTokens":1310}}438{"id":"stack-74177078","source":"stackoverflow","questionId":74177078,"title":"Styles is missing after I bundle my project with Vite","tags":["vue.js","vite","rollup"],"text":"Title: Styles is missing after I bundle my project with Vite\nTags: vue.js, vite, rollup\nSource: Stack Overflow\n\nQuestion:\nAs title, my styles (including style tag in SFC and css imported to `app.ts`) are missing when I compile my app in IIFE format.\n\nI have no idea whether it's by Vite or RollUp... It works properly with `vite serve`, but not `vite build`.\n\nI saw the css emitted in other format, but not `IIFE`. For that, I can't load Vue form CDN, which I want to.\n\n```\n// vite.config.js\nimport vue from \"@vitejs/plugin-vue\";\nimport { defineConfig } from \"vite\";\nimport env from \"vite-plugin-env-compatible\";\n\nexport default defineConfig({\n plugins: [\n env({\n prefix: \"\",\n mountedPath: \"process.env\",\n }),\n vue(),\n ],\n build: {\n minify: true,\n rollupOptions: {\n external: [\"vue\"],\n output: {\n format: \"iife\",\n globals: {\n vue: \"Vue\",\n },\n },\n },\n },\n});\n```\n\n```\n// src/app.ts\nimport { createApp } from \"vue\";\n\nimport App from \"./App.vue\";\n\nimport \"./main.css\";\n\ncreateApp(App).mount(\"#app\");\n```\n\n```\n\n \n\n### Hello World\n\n Click Me!\n Clicked: {{ count }}\n\nimport { ref } from \"vue\";\n\n//#region Counter\nconst count = ref(0);\nconst increment = () => (count.value += 1);\n//#endregion\n\nh1 {\n color: green;\n}\n\n```\n\n========================================\n\nCode:\n```js\n// vite.config.js\nimport vue from \"@vitejs/plugin-vue\";\nimport { defineConfig } from \"vite\";\nimport env from \"vite-plugin-env-compatible\";\n\nexport default defineConfig({\n  plugins: [\n    env({\n      prefix: \"\",\n      mountedPath: \"process.env\",\n    }),\n    vue(),\n  ],\n  build: {\n    minify: true,\n    rollupOptions: {\n      external: [\"vue\"],\n      output: {\n        format: \"iife\",\n        globals: {\n          vue: \"Vue\",\n        },\n      },\n    },\n  },\n});\n```\n\n```js\n// src/app.ts\nimport { createApp } from \"vue\";\n\nimport App from \"./App.vue\";\n\nimport \"./main.css\";\n\ncreateApp(App).mount(\"#app\");\n```\n\n```html\n<!-- src/App.vue -->\n<template>\n  <h1>Hello World</h1>\n\n  <button @click=\"increment\">Click Me!</button>\n  <div>Clicked: {{ count }}</div>\n</template>\n\n<script setup lang=\"ts\">\nimport { ref } from \"vue\";\n\n//#region Counter\nconst count = ref(0);\nconst increment = () => (count.value += 1);\n//#endregion\n</script>\n\n<style scoped>\nh1 {\n  color: green;\n}\n</style>\n```\n\n```text\napp.ts\n```\n\n```text\nvite serve\n```\n\n```text\nvite build\n```\n\n```text\nIIFE\n```\n\n```text\nbuild.cssCodeSplit\n```\n\n```text\nfalse\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.428Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":164,"estimatedTokens":596}}439{"id":"stack-75965182","source":"stackoverflow","questionId":75965182,"title":"Vite 4 build files without hash","tags":["reactjs","vite"],"text":"Title: Vite 4 build files without hash\nTags: reactjs, vite\nSource: Stack Overflow\n\nQuestion:\nI am using Vite 4.2.0 for my react project. I want my build files name without hash.\nI have tried below config in vite.config.js but still it's not reflecting.\n\n```\nexport default defineConfig({\n plugins: [react()],\n build:{\n rollupOutputOptions: {\n entryFileNames: `assets/[name].js`,\n chunkFileNames: `assets/[name].js`,\n assetFileNames: `assets/[name].[ext]`\n },\n css: {\n extract: {\n filename: '[name].css' // change CSS file name to include hash\n }\n }\n }\n\n})\n```\n\n========================================\n\nTop Answer:\nThis can solve the purpose. Complete vite.config.js will look something like this:\n\n```\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\nimport vue from '@vitejs/plugin-vue';\n\n export default defineConfig({\n plugins: [\n vue({\n template: {\n transformAssetUrls: {\n base: null,\n includeAbsolute: false,\n },\n },\n }),\n laravel({\n input: [\n 'resources/css/app.css', \n 'resources/js/app.js',\n 'resources/assets/frontend/frontend.css',\n 'resources/assets/backend/frontend.css'\n ],\n refresh: true\n }),\n],\nbuild: {\n rollupOptions: {\n output: {\n entryFileNames: `assets/[name].js`,\n chunkFileNames: `assets/[name].js`,\n assetFileNames: 'assets/[name].css',\n }\n }\n }\n});\n```\n\n========================================\n\nCode:\n```text\nexport default defineConfig({\n  plugins: [react()],\n  build:{\n    rollupOutputOptions: {\n      entryFileNames: `assets/[name].js`,\n      chunkFileNames: `assets/[name].js`,\n      assetFileNames: `assets/[name].[ext]`\n    },\n    css: {\n      extract: {\n        filename: '[name].css' // change CSS file name to include hash\n      }\n    }\n  }\n\n})\n```\n\n```js\n// vite.config.js\nexport default defineConfig({\n  build: {\n    rollupOptions: {\n      output: {\n        entryFileNames: `assets/[name].js`,\n        chunkFileNames: `assets/[name].js`,\n        assetFileNames: `assets/[name].[ext]`,\n      },\n    },\n  },\n})\n```\n\n```text\nbuild.rollupOptions\n```\n\n```text\nbuild.rollupOutputOptions\n```\n\n```text\noutput\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\nimport vue from '@vitejs/plugin-vue';\n\n export default defineConfig({\n    plugins: [\n    vue({\n        template: {\n            transformAssetUrls: {\n                base: null,\n                includeAbsolute: false,\n            },\n        },\n    }),\n    laravel({\n        input: [\n            'resources/css/app.css', \n            'resources/js/app.js',\n            'resources/assets/frontend/frontend.css',\n            'resources/assets/backend/frontend.css'\n        ],\n        refresh: true\n    }),\n],\nbuild: {\n    rollupOptions: {\n      output: {\n        entryFileNames: `assets/[name].js`,\n        chunkFileNames: `assets/[name].js`,\n        assetFileNames: 'assets/[name].css',\n      }\n    }\n  }\n});\n```\n\n========================================\n\nComments:\n- Why you don't want to use hash?\n- I want to host build files and add them as CDN to some other project. If it has hash then file name keeps changing.\n- Can you add the result from the code above?\n- Can you try to change `rollupOutputOptions` to `rollupOptions`?\n- Hi, I tried `rollupOptions` but it shows a kind of warning like. Unknown input options: entryFileNames, chunkFileNames, assetFileNames. Allowed options: acorn, acornInjectPlugins, cache, context, experimentalCacheExpiry, experimentalLogSideEffects... also, the output is as same as the default.\n- github.com/vitejs/vite/issues/378#issuecomment-768816653\n- Can you try this issue solution?","metadata":{"transformedAt":"2026-08-18T18:33:46.428Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":165,"estimatedTokens":895}}440{"id":"stack-75535328","source":"stackoverflow","questionId":75535328,"title":"Failed to resolve import \"@inertia/inertia\" from \"resources\\js\\Pages\\Dashboard.vue\"","tags":["laravel","vue.js","vite","inertiajs"],"text":"Title: Failed to resolve import \"@inertia/inertia\" from \"resources\\js\\Pages\\Dashboard.vue\"\nTags: laravel, vue.js, vite, inertiajs\nSource: Stack Overflow\n\nQuestion:\nI've created a Laravel app, and then added Inertia and Vue using Laravel Breeze. Everything was running well until I writted this:\n`import { Inertia } from '@inertia/inertia'`\n\nIn my `AppName\\\\resources\\\\js\\\\Pages\\\\Dashboard.vue`. Then, strangely, when I opened the browser in the dashboard I got this Vite error:\n\n[plugin:vite:import-analysis] Failed to resolve import \"@inertia/inertia\" from \"resources\\js\\Pages\\Dashboard.vue\". Does the file exist?\n\nHere is my `package.json`:\n\n```\n{\n \"private\": true,\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\"\n },\n \"devDependencies\": {\n \"@inertiajs/vue3\": \"^1.0.0\",\n \"@tailwindcss/forms\": \"^0.5.3\",\n \"@vitejs/plugin-vue\": \"^4.0.0\",\n \"autoprefixer\": \"^10.4.12\",\n \"axios\": \"^1.1.2\",\n \"laravel-vite-plugin\": \"^0.7.2\",\n \"lodash\": \"^4.17.19\",\n \"postcss\": \"^8.4.18\",\n \"tailwindcss\": \"^3.2.1\",\n \"vite\": \"^4.0.0\",\n \"vue\": \"^3.2.41\"\n },\n \"dependencies\": {\n \"moment\": \"^2.29.4\"\n }\n}\n```\n\n========================================\n\nTop Answer:\nSwitch from\n\n```\nimport { Inertia } from '@inertiajs/inertia'\n```\n\nto\n\n```\nimport { router } from '@inertiajs/vue3'\n```\n\n========================================\n\nCode:\n```json\n{\n    \"private\": true,\n    \"scripts\": {\n        \"dev\": \"vite\",\n        \"build\": \"vite build\"\n    },\n    \"devDependencies\": {\n        \"@inertiajs/vue3\": \"^1.0.0\",\n        \"@tailwindcss/forms\": \"^0.5.3\",\n        \"@vitejs/plugin-vue\": \"^4.0.0\",\n        \"autoprefixer\": \"^10.4.12\",\n        \"axios\": \"^1.1.2\",\n        \"laravel-vite-plugin\": \"^0.7.2\",\n        \"lodash\": \"^4.17.19\",\n        \"postcss\": \"^8.4.18\",\n        \"tailwindcss\": \"^3.2.1\",\n        \"vite\": \"^4.0.0\",\n        \"vue\": \"^3.2.41\"\n    },\n    \"dependencies\": {\n        \"moment\": \"^2.29.4\"\n    }\n}\n```\n\n```text\nimport { Inertia } from '@inertia/inertia'\n```\n\n```text\nAppName\\\\resources\\\\js\\\\Pages\\\\Dashboard.vue\n```\n\n```text\npackage.json\n```\n\n```text\nimport { Inertia } from '@inertia/inertia'\n```\n\n```text\nimport { router } from '@inertiajs/vue3'\n```\n\n```text\n<template>\n    <div>\n        <input type=\"text\" v-model=\"search\" id=\"&quot;form-subscribe-Filter\" placeholder=\"Search...\"\n    class=\" rounded-lg border-transparent flex-1 appearance-none border border-gray-300 w-full py-2 px-4 bg-white text-gray-700 placeholder-gray-400 shadow-sm text-base focus:outline-none focus:ring-2 focus:ring-purple-600 focus:border-transparent\" />\n    </div>\n</template>\n\n<script setup>\n  import {ref,watch} from 'vue'\n  import { router } from '@inertiajs/vue3'\n\n    let search=ref('');\n\n    watch(search,(value)=>{\n        // console.log('Changed:'+value)\n        router.get('/users',{search:value},{\n            preserveState:true,\n            replace:true    \n        });\n    })\n</script>\n```\n\n```text\nimport { router } from '@inertiajs/vue3'\n```\n\n```text\nimport { Inertia } from '@inertia/inertia'\n```\n\n```text\nrouter.get()\n```\n\n```text\nrouter.post()\n```\n\n```text\nInertia.get()\n```\n\n```text\nInertia.post()\n```\n\n```text\nrouter\n```\n\n```text\nInertia\n```\n\n```text\n'/users'\n```\n\n```text\nimport { Inertia } from '@inertiajs/inertia'\n```\n\n```text\nimport { router } from '@inertiajs/vue3'\n```\n\n========================================\n\nComments:\n- The documentation is pretty self explanatory: inertiajs.com/upgrade-guide#new-dependencies. It says you must use `import { router } from '@inertiajs&#47;vue3'`.","metadata":{"transformedAt":"2026-08-18T18:33:46.428Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":176,"estimatedTokens":867}}441{"id":"stack-74417822","source":"stackoverflow","questionId":74417822,"title":"How can I use Buffer, process in Vite app?","tags":["reactjs","typescript","vite","web3js"],"text":"Title: How can I use Buffer, process in Vite app?\nTags: reactjs, typescript, vite, web3js\nSource: Stack Overflow\n\nQuestion:\nI'm using wagmi in typescript react app setup by Vite.\n\nI got some issue ex:\n\n\"global is not defined\", \"buffer is not defined\"\n\nAnd I tried it again with some code in main.tsx:\n\n```\nimport { Buffer } from 'buffer';\nimport process from 'process';\n\nwindow.global = window;\nwindow.Buffer = Buffer;\nwindow.process = process;\n```\n\nBut I still get some error ex:\n\"Module \"process\" has been externalized for browser compatibility. Cannot access \"process.versions\" in client code.\"\n\nError will occur when I connect to coinbase or walletconnect connector.\n\nMy vite.config.ts\n\n```\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\n//import Buffer from 'buffer';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n server: {\n port: 5000,\n },\n resolve: {\n alias: [{ find: '@', replacement: '/src' }],\n },\n define: {\n // global: 'window',\n // Buffer: Buffer,\n // process: process,\n },\n});\n```\n\n========================================\n\nTop Answer:\nMany people ask same question here, but I cannot find proper answer.\nHowever, I found out **perfect answer** a few days ago.\n\nwe sometimes encounter error **\"process is not defined\"** in vite app.\n**That's because Vite does not automatically polyfill Node.js modules.**\n\nhttps://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility\n\n**Answer** is https://www.npmjs.com/package/vite-plugin-node-polyfills\n\nit says\n\nSince browsers do not support Node's Core Modules, packages that use\nthem must be polyfilled to function in browser environments. In an\nattempt to prevent runtime errors, Vite produces errors or warnings\nwhen your code references builtin modules such as fs or path.\n\n**Solution:**\n\n- Install the package as a dev dependency.\n\nnpm install --save-dev vite-plugin-node-polyfills\n\n- Add the plugin to your **vite.config.ts** file.\n\n\r\n\r\n\n```\nimport { defineConfig, loadEnv } from 'vite'\nimport { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'\nimport { nodePolyfills } from 'vite-plugin-node-polyfills'\nimport react from '@vitejs/plugin-react'\n\nexport default defineConfig(({ command, mode }) => {\n // Load env file based on `mode` in the current working directory.\n // Set the third parameter to '' to load all env regardless of the `VITE_` prefix.\n const env = loadEnv(mode, process.cwd(), '')\n return {\n plugins: [\n nodePolyfills(), // this is necessary to avoid \"process is not defined issue\"\n react()]\n }\n\n})\n```\n\n\r\n\r\n\r\n\n**You can customize it when you need**\n\n\r\n\r\n\n```\nimport { defineConfig } from 'vite'\nimport { nodePolyfills } from 'vite-plugin-node-polyfills'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n nodePolyfills({\n // To add only specific polyfills, add them here. If no option is passed, adds all polyfills\n include: ['path'],\n // To exclude specific polyfills, add them to this list. Note: if include is provided, this has no effect\n exclude: [\n 'http', // Excludes the polyfill for `http` and `node:http`.\n ],\n // Whether to polyfill specific globals.\n globals: {\n Buffer: true, // can also be 'build', 'dev', or false\n global: true,\n process: true,\n },\n // Override the default polyfills for specific modules.\n overrides: {\n // Since `fs` is not supported in browsers, we can use the `memfs` package to polyfill it.\n fs: 'memfs',\n },\n // Whether to polyfill `node:` protocol imports.\n protocolImports: true,\n }),\n ],\n})\n```\n\n\r\n\r\n\r\n\nI hope this will help everybody a lot.\nGood Luck\n\n========================================\n\nCode:\n```text\nimport { Buffer } from 'buffer';\nimport process from 'process';\n\nwindow.global = window;\nwindow.Buffer = Buffer;\nwindow.process = process;\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\n//import Buffer from 'buffer';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  server: {\n    port: 5000,\n  },\n  resolve: {\n    alias: [{ find: '@', replacement: '/src' }],\n  },\n  define: {\n    // global: 'window',\n    // Buffer: Buffer,\n    // process: process,\n  },\n});\n```\n\n```html\n<!-- node // buffer-->\n<script>window.global = window;</script>\n<script type=\"module\">\n    import { Buffer } from \"buffer/\"; // <-- no typo here (\"/\")\n    import process from \"process\";\n   \n    window.Buffer = Buffer;\n    window.process = process;\n</script>\n```\n\n```js\nexport default defineConfig({\n  [...]\n\n  resolve: {\n    alias: {\n      process: \"process/browser\"\n    }\n  }\n})\n```\n\n```text\nimport { Buffer } from 'buffer/'\n\n[...]\n```\n\n```text\nnpm install buffer process\n```\n\n```text\nindex.html\n```\n\n```text\nvite.config.js\n```\n\n```text\nresolve.alias\n```\n\n```text\n/\n```\n\n```text\nUint8Array\n```\n\n```js\nimport { defineConfig, loadEnv  } from 'vite'\nimport { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'\nimport { nodePolyfills } from 'vite-plugin-node-polyfills'\nimport react from '@vitejs/plugin-react'\n\nexport default defineConfig(({ command, mode }) => {\n  // Load env file based on `mode` in the current working directory.\n  // Set the third parameter to '' to load all env regardless of the `VITE_` prefix.\n  const env = loadEnv(mode, process.cwd(), '')\n  return {\n    plugins: [\n      nodePolyfills(), // this is necessary to avoid \"process is not defined issue\"\n      react()]\n  }\n\n})\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport { nodePolyfills } from 'vite-plugin-node-polyfills'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    nodePolyfills({\n      // To add only specific polyfills, add them here. If no option is passed, adds all polyfills\n      include: ['path'],\n      // To exclude specific polyfills, add them to this list. Note: if include is provided, this has no effect\n      exclude: [\n        'http', // Excludes the polyfill for `http` and `node:http`.\n      ],\n      // Whether to polyfill specific globals.\n      globals: {\n        Buffer: true, // can also be 'build', 'dev', or false\n        global: true,\n        process: true,\n      },\n      // Override the default polyfills for specific modules.\n      overrides: {\n        // Since `fs` is not supported in browsers, we can use the `memfs` package to polyfill it.\n        fs: 'memfs',\n      },\n      // Whether to polyfill `node:` protocol imports.\n      protocolImports: true,\n    }),\n  ],\n})\n```\n\n========================================\n\nComments:\n- You can't use back end Node modules in the front end. Either do whatever you're trying to do on the back end, or find front end modules to do it in the browser.\n- Error: Directory import '/builds/...node_modules/buffer/' is not supported resolving ES modules imported from /builds/.../node_modules/vitest/dist/chunk-vite-node-client.&zwnj;&#8203;da0a17ff.mjs Did you mean to import buffer/index.js? I got this error with the above method though...\n- Hi again, I solved the problem by import {Buffer} from 'buffer/index.js'; in where I need to use the buffer in the component.\n- @Annie could give more details about your setup ? The published project on stackblitz run/build with no error on vite v3.x & v4.x\n- the right way in 2024\n- Hello @Matija , I added `nodePolyfills` in my `vite.config.ts` but if I try to call it from my App.tsx main component, like as `import { process } from 'nodePolyfills'` or also `import { Process } from 'process'` but it seems not recognized due it saiys in both cases `'Cannot find module... '` , maybe I missed something or shall I have to call it someway different?... Thanks in advance....\n- Hi, @Luigino. Thanks for asking that... it's a bit tricky to find right answer for you, I will find out solution for you if you me more details with your problem. please send me your issues via my email: micunovicmatija629@gmail.com or via telegram t.me/matijabusiness","metadata":{"transformedAt":"2026-08-18T18:33:46.428Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":298,"estimatedTokens":1981}}442{"id":"stack-72902089","source":"stackoverflow","questionId":72902089,"title":"Enviroment variables in Vite + React coming back undefined","tags":["reactjs","environment-variables","vite"],"text":"Title: Enviroment variables in Vite + React coming back undefined\nTags: reactjs, environment-variables, vite\nSource: Stack Overflow\n\nQuestion:\nI am trying to get some environment variables to work but for the life of me I can not...I have looked through a few SO answers and they all seem to point to how I have set things up.\n\nYet I keep getting undefined. This is how I am testing the variable.\n\n```\nimport {useState} from 'react'\nimport {FaCog} from 'react-icons/fa'\n\nfunction App() {\n const [data, setData] = useState([])\n const [dealId, setDealId] = useState('')\n const [loading, setLoading] = useState(null)\n const [error, setError] = useState('')\n\n // Counter\n const [count, setCounter] = useState(0)\n\n console.log('HOST:', import.meta.env.HOST) // returns undefined\n```\n\nThis is my `.env` file, which is placed in the root\n\n```\n# .env\nHOST=127.0.0.1:8000\n```\n\nThis is my structure (removed node_modules) for ease\n\n```\n.\n├── .env\n├── index.html\n├── package-lock.json\n├── package.json\n├── postcss.config.js\n├── src\n│ ├── App.jsx\n│ ├── favicon.svg\n│ ├── index.css\n│ ├── logo.svg\n│ └── main.jsx\n├── tailwind.config.js\n└── vite.config.js\n```\n\nWhere am I going wrong? I have restated the vite server many times already...i am stumped\n\n========================================\n\nCode:\n```js\nimport {useState} from 'react'\nimport {FaCog} from 'react-icons/fa'\n\nfunction App() {\n  const [data, setData] = useState([])\n  const [dealId, setDealId] = useState('')\n  const [loading, setLoading] = useState(null)\n  const [error, setError] = useState('')\n\n  // Counter\n  const [count, setCounter] = useState(0)\n\n  console.log('HOST:', import.meta.env.HOST) // returns undefined\n```\n\n```bash\n# .env\nHOST=127.0.0.1:8000\n```\n\n```text\n.\n├── .env\n├── index.html\n├── package-lock.json\n├── package.json\n├── postcss.config.js\n├── src\n│   ├── App.jsx\n│   ├── favicon.svg\n│   ├── index.css\n│   ├── logo.svg\n│   └── main.jsx\n├── tailwind.config.js\n└── vite.config.js\n```\n\n```text\n.env\n```\n\n```text\n# .env\nVITE_HOST=127.0.0.1:8000\n```\n\n```text\n// .js-file\nconsole.log('HOST:', import.meta.env.VITE_HOST)\n```\n\n```text\nVITE_\n```\n\n```text\nVITE_HOST\n```\n\n```text\n.env\n```\n\n========================================\n\nComments:\n- Thanks resolved this ages ago...but thanks for the input this will help others out. Good to mention that this is only if you need to expose the variables client side.","metadata":{"transformedAt":"2026-08-18T18:33:46.428Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":124,"estimatedTokens":593}}443{"id":"stack-72037842","source":"stackoverflow","questionId":72037842,"title":"how can i import and use a local .csv file in vuejs","tags":["vue.js","csv","nuxt.js","vite"],"text":"Title: how can i import and use a local .csv file in vuejs\nTags: vue.js, csv, nuxt.js, vite\nSource: Stack Overflow\n\nQuestion:\ni have a csv file in this structure\n\n```\nname,year,href,src\nParasite,2019,parasite-2019,film-poster/4/2/6/4/0/6/426406-parasite-0-460-0-690-crop.jpg\n```\n\ni would like to import this file as a list with each line as a dict in this way:\n\n```\n[{'name':'Parasite','year':'2019','href':'parasite-2019','src':'film-poster/4/2/6/4/0/6/426406-parasite-0-460-0-690-crop.jpg'}]\n```\n\ni tried using `import csv from './filmList.csv'` inside the `` tag, but that only gives me an error on load:\n\n```\n[plugin:vite:import-analysis] Failed to parse source for import analysis because the content contains invalid JS syntax. You may need to install appropriate plugins to handle the .csv file format.\n```\n\n========================================\n\nCode:\n```text\nname,year,href,src\nParasite,2019,parasite-2019,film-poster/4/2/6/4/0/6/426406-parasite-0-460-0-690-crop.jpg\n```\n\n```js\n[{'name':'Parasite','year':'2019','href':'parasite-2019','src':'film-poster/4/2/6/4/0/6/426406-parasite-0-460-0-690-crop.jpg'}]\n```\n\n```text\n[plugin:vite:import-analysis] Failed to parse source for import analysis because the content contains invalid JS syntax. You may need to install appropriate plugins to handle the .csv file format.\n```\n\n```text\nimport csv from './filmList.csv'\n```\n\n```text\n<script>\n```\n\n```text\nnpm i -D @rollup/plugin-dsv\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport dsv from '@rollup/plugin-dsv' 👈\n\nexport default defineConfig({\n  plugins: [\n    vue(),\n    dsv(), 👈\n  ],\n})\n```\n\n```html\n<script>\n// MyComponent.vue\nimport csv from './filmList.csv'\nconsole.log(csv) // => [{'name':'Parasite','year':'2019','href':'parasite-2019','src':'film-poster/4/2/6/4/0/6/426406-parasite-0-460-0-690-crop.jpg'}]\n</script>\n```\n\n```text\n@rollup/plugin-dsv\n```\n\n```text\n.csv\n```\n\n========================================\n\nComments:\n- I spent a few hours trying to understand, so if it may help someone else, **using it with TypeScript**, you need to add these lines in your .d.ts file: ``` declare module \"*.csv\" { export default Array; } ```","metadata":{"transformedAt":"2026-08-18T18:33:46.428Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":86,"estimatedTokens":552}}444{"id":"stack-77091329","source":"stackoverflow","questionId":77091329,"title":"move html files out of src folder in dist vite","tags":["vue.js","compilation","bundle","vite","bundler"],"text":"Title: move html files out of src folder in dist vite\nTags: vue.js, compilation, bundle, vite, bundler\nSource: Stack Overflow\n\nQuestion:\nI'm currently engaged in a Vue.js project that utilizes Vite as the build tool. My objective is to adjust the Vite configuration in a way that the HTML files are situated directly within the 'dist' folder, alongside the 'assets' folder upon building the project. Presently, the HTML files are being placed in subfolders within the 'dist' directory. Here's the current configuration I'm using in Vite:\n\n```\nimport { defineConfig } from 'vite';\nimport { resolve } from 'path';\nimport vue from '@vitejs/plugin-vue';\n\nexport default defineConfig({\n publicDir: false,\n build: {\n outDir: resolve(__dirname, 'dist'),\n emptyOutDir: true,\n rollupOptions: {\n input: {\n login: resolve(__dirname, 'src/login/login.html'),\n cadastro: resolve(__dirname, 'src/cadastro/cadastro.html'),\n home: resolve(__dirname, 'src/home/home.html')\n }\n }\n },\n plugins: [vue()]\n});\n```\n\nmy outdir looks like this:\n\n```\ndist/\n├── assets/\n│ ├── cadastro-118e7637.css\n│ ├── cadastro-669bfe7b.js\n│ ├── home-7dbac266.js\n│ ├── home-a84cd419.css\n│ ├── login-572efaa1.css\n│ ├── login-9a4f8a3b.js\n│ ├── modulepreload-polyfill-3cfb730f.js\n│ └── runtime-dom.esm-bundler-4af65d94.js\n└── src/\n ├── cadastro/\n │ └── cadastro.html\n ├── home/\n │ └── home.html\n └── login/\n └── login.html\n```\n\nHow do I make outdir look like this:\n\n```\ndist/\n├── assets/\n│ ├── cadastro-118e7637.css\n│ ├── cadastro-669bfe7b.js\n│ ├── home-7dbac266.js\n│ ├── home-a84cd419.css\n│ ├── login-572efaa1.css\n│ ├── login-9a4f8a3b.js\n│ ├── modulepreload-polyfill-3cfb730f.js\n│ └── runtime-dom.esm-bundler-4af65d94.js\n├── cadastro/\n│ └── cadastro.html\n├── home/\n│ └── home.html\n└── login/\n └── login.html\n```\n\n?\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite';\nimport { resolve } from 'path';\nimport vue from '@vitejs/plugin-vue';\n\nexport default defineConfig({\n  publicDir: false,\n  build: {\n    outDir: resolve(__dirname, 'dist'),\n    emptyOutDir: true,\n    rollupOptions: {\n      input: {\n        login: resolve(__dirname, 'src/login/login.html'),\n        cadastro: resolve(__dirname, 'src/cadastro/cadastro.html'),\n        home: resolve(__dirname, 'src/home/home.html')\n      }\n    }\n  },\n  plugins: [vue()]\n});\n```\n\n```text\ndist/\n├── assets/\n│   ├── cadastro-118e7637.css\n│   ├── cadastro-669bfe7b.js\n│   ├── home-7dbac266.js\n│   ├── home-a84cd419.css\n│   ├── login-572efaa1.css\n│   ├── login-9a4f8a3b.js\n│   ├── modulepreload-polyfill-3cfb730f.js\n│   └── runtime-dom.esm-bundler-4af65d94.js\n└── src/\n    ├── cadastro/\n    │   └── cadastro.html\n    ├── home/\n    │   └── home.html\n    └── login/\n        └── login.html\n```\n\n```text\ndist/\n├── assets/\n│   ├── cadastro-118e7637.css\n│   ├── cadastro-669bfe7b.js\n│   ├── home-7dbac266.js\n│   ├── home-a84cd419.css\n│   ├── login-572efaa1.css\n│   ├── login-9a4f8a3b.js\n│   ├── modulepreload-polyfill-3cfb730f.js\n│   └── runtime-dom.esm-bundler-4af65d94.js\n├── cadastro/\n│   └── cadastro.html\n├── home/\n│   └── home.html\n└── login/\n    └── login.html\n```\n\n```text\n// vite.config.js\nexport default defineConfig({\n  ...\n  root: 'src',\n  publicDir: '../public', // relative to root\n  emptyOutDir: true, // if you still want to clear outDir without warning\n  build: {\n    outDir: '../dist/', // relative to root\n    ...\n  }\n})\n```\n\n```text\n// vite.config.js\nexport default defineConfig({\n  plugins: [\n    ...\n    {\n      name: 'remove-src-dir-from-html-path',\n      enforce: 'post',\n      generateBundle(_,bundle) {\n        const htmlFileInSrcFolderPattern = /^src\\/.*\\.html$/\n        for (const outputItem of Object.values(bundle)) {\n          if (!htmlFileInSrcFolderPattern.test(outputItem.fileName)) {\n            continue\n          }\n          outputItem.fileName = outputItem.fileName.replace('src/', '')\n        }\n      }\n    }\n  ],\n```\n\n========================================\n\nComments:\n- Your homemade plugin works, but then we have a different directory structure while developing. Links aren't the same. How do we deal with that?\n- Exactly what i was looking for in order to rename output html dir like `about&#47;index.html` -> `apropos&#47;index.html` In order to change route name without renaming folder (like if a client want this kind of change) I searched for a while before finding your plugin. Thx a lot!\n- Thank you very much, the first approach works for me. But it seems a bit hacky so i created a Discussion in Vitejs Github, see here: github.com/vitejs/vite/discussions/18047","metadata":{"transformedAt":"2026-08-18T18:33:46.428Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":179,"estimatedTokens":1138}}445{"id":"stack-66071399","source":"stackoverflow","questionId":66071399,"title":"Why is toRaw(obj) maintaining reactivity?","tags":["vuejs3","vue-reactivity","vite"],"text":"Title: Why is toRaw(obj) maintaining reactivity?\nTags: vuejs3, vue-reactivity, vite\nSource: Stack Overflow\n\nQuestion:\nI have a reactivity confusion regarding toRaw().\n\nApp.vue\n\n```\n\n \n \n \n\n import TheForm from \"./components/TheForm.vue\";\n import TheList from \"./components/TheList.vue\";\n\n import { ref } from \"vue\";\n\n const allTheThings = ref([]);\n const addNewThing = (thing) => allTheThings.value.push(thing);\n\n```\n\nTheForm.vue\n\n```\n\n \n\n### Add New Thing\n\n \n \n \n Add New Thing\n \n\n import { reactive, defineEmit, toRaw } from \"vue\";\n\n const emit = defineEmit([\"newThing\"]);\n\n const thing = reactive({\n desc: \"\",\n number: 0,\n });\n\n const addNewThing = () => emit(\"newThing\", thing);\n\n```\n\nTheList.vue\n\n```\n\n \n\n### The List\n\n \n \n {{ thing.desc }} || {{ thing.number }}\n \n \n\n import { defineProps } from \"vue\";\n\n defineProps({\n allTheThings: Array,\n });\n\n```\n\nAs the code is passing around proxies to the data, it acts as suspected: after submitting the form, if you re-edit the data in the form fields it also edits the output of the list. Fine.\n\nSo I want to pass in a non-reactive copy of `thing` in `addNewThing`:\n\n```\nconst addNewThing = () => {\n const clone = { ...thing };\n emit(\"newThing\", clone);\n };\n```\n\nAnd it works as expected.\n\nWhat doesn’t work is if I use `const clone = toRaw(thing);` instead.\nIf I log the output of each, `{ …thing}` is EXACTLY the same as `toRaw(thing)` so why does `toRaw()` not seem to lose it’s reactivity?\n\nAny light shone would be, well… enlightening.\n\n========================================\n\nCode:\n```text\n<template>\n  <img alt=\"Vue logo\" src=\"./assets/logo.png\" />\n  <TheForm @newThing=\"addNewThing\" />\n  <TheList :allTheThings=\"allTheThings\" />\n</template>\n\n<script setup>\n  import TheForm from \"./components/TheForm.vue\";\n  import TheList from \"./components/TheList.vue\";\n\n  import { ref } from \"vue\";\n\n  const allTheThings = ref([]);\n  const addNewThing = (thing) => allTheThings.value.push(thing);\n</script>\n```\n\n```text\n<template>\n  <h3>Add New Thing</h3>\n  <form @submit.prevent=\"addNewThing\">\n    <input type=\"text\" placeholder=\"description\" v-model=\"thing.desc\" />\n    <input type=\"number\" placeholder=\"number\" v-model=\"thing.number\" />\n    <button type=\"submit\">Add New Thing</button>\n  </form>\n</template>\n\n<script setup>\n  import { reactive, defineEmit, toRaw } from \"vue\";\n\n  const emit = defineEmit([\"newThing\"]);\n\n  const thing = reactive({\n    desc: \"\",\n    number: 0,\n  });\n\n  const addNewThing = () => emit(\"newThing\", thing);\n</script>\n```\n\n```text\n<template>\n  <h3>The List</h3>\n  <ol>\n    <li v-for=\"(thing, idx) in allTheThings\" :key=\"idx\">\n      {{ thing.desc }} || {{ thing.number }}\n    </li>\n  </ol>\n</template>\n\n<script setup>\n  import { defineProps } from \"vue\";\n\n  defineProps({\n    allTheThings: Array,\n  });\n</script>\n```\n\n```text\nconst addNewThing = () => {\n    const clone = { ...thing };\n    emit(\"newThing\", clone);\n  };\n```\n\n```text\nthing\n```\n\n```text\naddNewThing\n```\n\n```text\nconst clone = toRaw(thing);\n```\n\n```text\n{ …thing}\n```\n\n```text\ntoRaw(thing)\n```\n\n```text\ntoRaw()\n```\n\n```text\ntoRaw\n```\n\n```text\nreactive\n```\n\n```text\nreadonly\n```\n\n```text\ntoRaw\n```\n\n```text\nconst clone = { ...thing };\n```\n\n========================================\n\nComments:\n- Thanks Daniel. In the detail is the Devil and all that.\n- \"toRaw will return the raw Proxy\" but the doc says \"Returns the raw, original object\". If to toRaw just disable reactivity but maintains Proxy it's turned out the doc is misleading. Proxy is not a raw Object.","metadata":{"transformedAt":"2026-08-18T18:33:46.428Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":212,"estimatedTokens":876}}446{"id":"stack-76182972","source":"stackoverflow","questionId":76182972,"title":"How to serve Vite development server behind an Nginx reverse proxy","tags":["reactjs","nginx","vite","monorepo","turborepo"],"text":"Title: How to serve Vite development server behind an Nginx reverse proxy\nTags: reactjs, nginx, vite, monorepo, turborepo\nSource: Stack Overflow\n\nQuestion:\nI'm working on a `Typescript` **monorepo** using `turborepo` that holds multiple microservices (`nextjs`, `expressjs`, `create-react-app`).\neach of these microservices is served in its own `PORT`.\nIn order to make the development experience more fluid, we decided to add a `Nginx` server (in a `docker` image) that will collect all the ports from each Microservice and reserve them all under one `PORT`.\n\nWhen I tried to add a `Vite react app` and put it behind the same Nginx server, it didn't work because it is trying to access the files in node_modules in my local machine.\n\nDoes anyone have a workaround?\n\nBelow is a sample of my configs:\n\nNginx config file :\n\n```\nupstream imgproxy {\n server imgproxy:3000;\n}\n\nserver {\n listen 80;\n\n location / {\n return 301 https://$host:3000$request_uri;\n }\n}\n\nserver {\n listen 443 ssl;\n client_max_body_size 240M;\n ssl_certificate cert/localhost3000.crt;\n ssl_certificate_key cert/localhost3000.key;\n\n location /api/v1/auth {\n proxy_pass http://host.docker.internal:4001;\n }\n\n location /dashboard {\n proxy_pass https://host.docker.internal:3001;\n }\n\n location /api/v1/blogs {\n proxy_pass http://host.docker.internal:4010;\n }\n\n location / {\n proxy_pass http://host.docker.internal:4200;\n }\n\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header Host $host;\n\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection \"upgrade\";\n include h5bp/tls/policy_balanced.conf;\n # Custom error pages\n include h5bp/errors/custom_errors.conf;\n\n # Include the basic h5bp config set\n include h5bp/basic.conf;\n\n}\n```\n\nMy vite.conf.ts\n\n```\nimport { defineConfig, loadEnv } from \"vite\";\nimport react from \"@vitejs/plugin-react-swc\";\nimport fs from \"fs\";\nimport tsconfigPaths from \"vite-tsconfig-paths\";\n// https://vitejs.dev/config/\nexport default defineConfig(({ mode }) => {\n return {\n base: \"/dashboard\",\n server: {\n port: 3001,\n https: {\n cert: fs.readFileSync(\"../../nginx/cert/localhost3000.crt\"),\n key: fs.readFileSync(\"../../nginx/cert/localhost3000.key\"),\n },\n },\n plugins: [react(), tsconfigPaths()],\n };\n});\n```\n\nNginx's errors :\n\n```\n2023/05/05 13:54:02 [error] 33#33: *2 open() \"/etc/nginx/html/dashboard/node_modules/.vite/deps/react_jsx-dev-runtime.js\" failed (2: No such file or directory), client: 172.20.0.1, server: , request: \"GET /dashboard/node_modules/.vite/deps/react_jsx-dev-runtime.js?v=12d55949 HTTP/1.1\", host: \"localhost:3000\", referrer: \"https://localhost:3000/dashboard/src/index.tsx\"\n172.20.0.1 - - [05/May/2023:13:54:02 +0000] \"GET /dashboard/node_modules/.vite/deps/react_jsx-dev-runtime.js?v=12d55949 HTTP/1.1\" 404 178 \"https://localhost:3000/dashboard/src/index.tsx\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" \"-\"\n172.20.0.1 - - [05/May/2023:13:54:02 +0000] \"GET /dashboard/@react-refresh HTTP/1.1\" 200 3393 \"https://localhost:3000/dashboard\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" \"-\"\n2023/05/05 13:54:03 [error] 33#33: *2 open() \"/etc/nginx/html/dashboard/node_modules/.vite/deps/react.js\" failed (2: No such file or directory), client: 172.20.0.1, server: , request: \"GET /dashboard/node_modules/.vite/deps/react.js?v=12d55949 HTTP/1.1\", host: \"localhost:3000\", referrer: \"https://localhost:3000/dashboard/src/index.tsx\"\n172.20.0.1 - - [05/May/2023:13:54:03 +0000] \"GET /dashboard/node_modules/.vite/deps/react.js?v=12d55949 HTTP/1.1\" 404 178 \"https://localhost:3000/dashboard/src/index.tsx\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" \"-\"\n2023/05/05 13:54:03 [error] 35#35: *6 open() \"/etc/nginx/html/dashboard/node_modules/.vite/deps/react-redux.js\" failed (2: No such file or directory), client: 172.20.0.1, server: , request: \"GET /dashboard/node_modules/.vite/deps/react-redux.js?v=12d55949 HTTP/1.1\", host: \"localhost:3000\", referrer: \"https://localhost:3000/dashboard/src/index.tsx\"\n172.20.0.1 - - [05/May/2023:13:54:03 +0000] \"GET /dashboard/node_modules/.vite/deps/react-redux.js?v=12d55949 HTTP/1.1\" 404 178 \"https://localhost:3000/dashboard/src/index.tsx\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" \"-\"\n172.20.0.1 - - [05/May/2023:13:54:03 +0000] \"GET /dashboard/@fs/C:/Users/nader/Documents/devProjects/boilerplate/packages/browser/core-ui/DarkModeProvider/index.tsx HTTP/1.1\" 200 2026 \"https://localhost:3000/dashboard/src/index.tsx\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" \"-\"\n```\n\n========================================\n\nTop Answer:\nI'm assuming you have expose Nginx's container port `80` to docker host port `3000`, that's why requests to proxy are coming at `localhost:3000`.Thus request to `localhost:3000` are proxied requests.\n\nMost likely your configuration file has not been picked up by the Nginx, that's why it doesn't detect the reverse proxy configuration and tries to read the file from it's static content directory.\n\nIf it had detected proxy configuration and for some reason target application is down or cannot be reached, you'll see `502` error like below instead of `404`\n\n```\n172.17.0.1 - - [13/May/2023:19:43:13 +0000] \"GET /foo/hello HTTP/1.1\" 502 497 \"-\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36\" \"-\"\n```\n\nYou can test this by accessing the proxy URL after killing your react app, if Nginx still logs 404 instead of 502, it hasn't detected the proxy settings.\n\nAlso, **location context path must end with a forward slash** to work, like below\n\n```\nlocation /foo/ {\n proxy_pass http://Lan-IP-Of-Docker-Host:8080/;\n}\n```\n\nAlso, I'm not sure what `host.docker.internal` is set to, if you're running container on localhost then check if your hosts file has an entry made by docker for `host.docker.internal` mapped to `127.0.0.1`\n\nWindows 10 hosts file: `C:\\Windows\\System32\\drivers\\etc\\hosts`\n\nLinux hosts file: `/etc/hosts`\n\nIf it's set to `127.0.0.1`, then proxy will not forward request correctly, as it will resolve to the loopback address inside the container itself. You can initially test this configuration by replacing `host.docker.internal` hostname with LAN IP address of Docker host. For me it's my local LAN address like `10.0.1.x`\n\nFinally, I created a simple `Dockerfile` for Nginx and test the proxy by modifying `default.conf` file, see the code below. Try running proxy with this configuration to see if this works\n\n**Dockerfie**\n\n```\nFROM nginx:1.23.4\n\nCOPY default.conf /etc/nginx/conf.d/default.conf\n```\n\n**default.conf**\n\n```\nserver {\n listen 80;\n listen [::]:80;\n server_name localhost;\n\n #access_log /var/log/nginx/host.access.log main;\n\n# REVERSE PROXY SETTING, Context path ends with forward slash\n location /foo/ {\n proxy_pass http://Lan-IP-Of-Docker-Host:8080/;\n }\n\n location / {\n root /usr//nginx/html;\n index index.html index.htm;\n }\n\n #error_page 404 /404.html;\n\n # redirect server error pages to the static page /50x.html\n #\n error_page 500 502 503 504 /50x.html;\n location = /50x.html {\n root /usr//nginx/html;\n }\n\n # proxy the PHP scripts to Apache listening on 127.0.0.1:80\n #\n #location ~ \\.php$ {\n # proxy_pass http://127.0.0.1;\n #}\n\n # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000\n #\n #location ~ \\.php$ {\n # root html;\n # fastcgi_pass 127.0.0.1:9000;\n # fastcgi_index index.php;\n # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;\n # include fastcgi_params;\n #}\n\n # deny access to .htaccess files, if Apache's document root\n # concurs with nginx's one\n #\n #location ~ /\\.ht {\n # deny all;\n #}\n}\n```\n\nDocker build, run and stop commands\n\n```\ndocker build -t test-nginx ./\n\n//Container will be removed after its stopped because of --rm\ndocker run --rm --name test-nginx -p 3000:80 test-nginx\n\n//Stops immediately\ndocker stop test-nginx -t 0\n```\n\n========================================\n\nCode:\n```text\nupstream imgproxy {\n    server imgproxy:3000;\n}\n\n\nserver {\n    listen 80;\n\n    location / {\n        return 301 https://$host:3000$request_uri;\n    }\n}\n\n\nserver {\n    listen 443 ssl;\n    client_max_body_size 240M;\n    ssl_certificate    cert/localhost3000.crt;\n    ssl_certificate_key    cert/localhost3000.key;\n\n    location /api/v1/auth {\n          proxy_pass http://host.docker.internal:4001;\n    }\n\n    location /dashboard {\n          proxy_pass https://host.docker.internal:3001;\n    }\n\n    location /api/v1/blogs {\n          proxy_pass http://host.docker.internal:4010;\n    }\n\n    location / {\n          proxy_pass http://host.docker.internal:4200;\n    }\n\n    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n    proxy_set_header Host $host;\n\n    proxy_http_version 1.1;\n    proxy_set_header Upgrade $http_upgrade;\n    proxy_set_header Connection \"upgrade\";\n    include h5bp/tls/policy_balanced.conf;\n    # Custom error pages\n    include h5bp/errors/custom_errors.conf;\n\n    # Include the basic h5bp config set\n    include h5bp/basic.conf;\n\n}\n```\n\n```text\nimport { defineConfig, loadEnv } from \"vite\";\nimport react from \"@vitejs/plugin-react-swc\";\nimport fs from \"fs\";\nimport tsconfigPaths from \"vite-tsconfig-paths\";\n// https://vitejs.dev/config/\nexport default defineConfig(({ mode }) => {\n  return {\n    base: \"/dashboard\",\n    server: {\n      port: 3001,\n      https: {\n        cert: fs.readFileSync(\"../../nginx/cert/localhost3000.crt\"),\n        key: fs.readFileSync(\"../../nginx/cert/localhost3000.key\"),\n      },\n    },\n    plugins: [react(), tsconfigPaths()],\n  };\n});\n```\n\n```text\n2023/05/05 13:54:02 [error] 33#33: *2 open() \"/etc/nginx/html/dashboard/node_modules/.vite/deps/react_jsx-dev-runtime.js\" failed (2: No such file or directory), client: 172.20.0.1, server: , request: \"GET /dashboard/node_modules/.vite/deps/react_jsx-dev-runtime.js?v=12d55949 HTTP/1.1\", host: \"localhost:3000\", referrer: \"https://localhost:3000/dashboard/src/index.tsx\"\n172.20.0.1 - - [05/May/2023:13:54:02 +0000] \"GET /dashboard/node_modules/.vite/deps/react_jsx-dev-runtime.js?v=12d55949 HTTP/1.1\" 404 178 \"https://localhost:3000/dashboard/src/index.tsx\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" \"-\"\n172.20.0.1 - - [05/May/2023:13:54:02 +0000] \"GET /dashboard/@react-refresh HTTP/1.1\" 200 3393 \"https://localhost:3000/dashboard\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" \"-\"\n2023/05/05 13:54:03 [error] 33#33: *2 open() \"/etc/nginx/html/dashboard/node_modules/.vite/deps/react.js\" failed (2: No such file or directory), client: 172.20.0.1, server: , request: \"GET /dashboard/node_modules/.vite/deps/react.js?v=12d55949 HTTP/1.1\", host: \"localhost:3000\", referrer: \"https://localhost:3000/dashboard/src/index.tsx\"\n172.20.0.1 - - [05/May/2023:13:54:03 +0000] \"GET /dashboard/node_modules/.vite/deps/react.js?v=12d55949 HTTP/1.1\" 404 178 \"https://localhost:3000/dashboard/src/index.tsx\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" \"-\"\n2023/05/05 13:54:03 [error] 35#35: *6 open() \"/etc/nginx/html/dashboard/node_modules/.vite/deps/react-redux.js\" failed (2: No such file or directory), client: 172.20.0.1, server: , request: \"GET /dashboard/node_modules/.vite/deps/react-redux.js?v=12d55949 HTTP/1.1\", host: \"localhost:3000\", referrer: \"https://localhost:3000/dashboard/src/index.tsx\"\n172.20.0.1 - - [05/May/2023:13:54:03 +0000] \"GET /dashboard/node_modules/.vite/deps/react-redux.js?v=12d55949 HTTP/1.1\" 404 178 \"https://localhost:3000/dashboard/src/index.tsx\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" \"-\"\n172.20.0.1 - - [05/May/2023:13:54:03 +0000] \"GET /dashboard/@fs/C:/Users/nader/Documents/devProjects/boilerplate/packages/browser/core-ui/DarkModeProvider/index.tsx HTTP/1.1\" 200 2026 \"https://localhost:3000/dashboard/src/index.tsx\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" \"-\"\n```\n\n```text\nTypescript\n```\n\n```text\nturborepo\n```\n\n```text\nnextjs\n```\n\n```text\nexpressjs\n```\n\n```text\ncreate-react-app\n```\n\n```text\nPORT\n```\n\n```text\nNginx\n```\n\n```text\ndocker\n```\n\n```text\nPORT\n```\n\n```text\nVite react app\n```\n\n```text\nvolume:\n    -  react_app/node_modules : /etc/nginx/html/dashboard/node_modules\n```\n\n```text\n172.17.0.1 - - [13/May/2023:19:43:13 +0000] \"GET /foo/hello HTTP/1.1\" 502 497 \"-\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36\" \"-\"\n```\n\n```text\nlocation /foo/ {\n    proxy_pass http://Lan-IP-Of-Docker-Host:8080/;\n}\n```\n\n```text\nFROM nginx:1.23.4\n\nCOPY default.conf /etc/nginx/conf.d/default.conf\n```\n\n```text\nserver {\n    listen       80;\n    listen  [::]:80;\n    server_name  localhost;\n\n    #access_log  /var/log/nginx/host.access.log  main;\n\n# REVERSE PROXY SETTING, Context path ends with forward slash\n    location /foo/ {\n        proxy_pass http://Lan-IP-Of-Docker-Host:8080/;\n    }\n\n    location / {\n        root   /usr/share/nginx/html;\n        index  index.html index.htm;\n    }\n\n    #error_page  404              /404.html;\n\n    # redirect server error pages to the static page /50x.html\n    #\n    error_page   500 502 503 504  /50x.html;\n    location = /50x.html {\n        root   /usr/share/nginx/html;\n    }\n\n    # proxy the PHP scripts to Apache listening on 127.0.0.1:80\n    #\n    #location ~ \\.php$ {\n    #    proxy_pass   http://127.0.0.1;\n    #}\n\n    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000\n    #\n    #location ~ \\.php$ {\n    #    root           html;\n    #    fastcgi_pass   127.0.0.1:9000;\n    #    fastcgi_index  index.php;\n    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;\n    #    include        fastcgi_params;\n    #}\n\n    # deny access to .htaccess files, if Apache's document root\n    # concurs with nginx's one\n    #\n    #location ~ /\\.ht {\n    #    deny  all;\n    #}\n}\n```\n\n```text\ndocker build -t test-nginx ./\n\n//Container will be removed after its stopped because of --rm\ndocker run --rm --name test-nginx -p 3000:80 test-nginx\n\n//Stops immediately\ndocker stop test-nginx -t 0\n```\n\n```text\n80\n```\n\n```text\n3000\n```\n\n```text\nlocalhost:3000\n```\n\n```text\nlocalhost:3000\n```\n\n```text\n502\n```\n\n```text\n404\n```\n\n```text\nhost.docker.internal\n```\n\n```text\nhost.docker.internal\n```\n\n```text\n127.0.0.1\n```\n\n```text\nC:\\Windows\\System32\\drivers\\etc\\hosts\n```\n\n```text\n/etc/hosts\n```\n\n```text\n127.0.0.1\n```\n\n```text\nhost.docker.internal\n```\n\n```text\n10.0.1.x\n```\n\n```text\nDockerfile\n```\n\n```text\ndefault.conf\n```\n\n```text\nserver {\n    listen       443 ssl;\n    server_name  bogus-dev-server.com;\n\n    ssl_certificate /usr/local/etc/ssl/bogus-dev-server.com/public.pem;\n    ssl_certificate_key /usr/local/etc/ssl/bogus-dev-server.com/private.pem;\n\n    access_log /usr/local/var/log/nginx/nginx.vhost.access.log;\n    error_log /usr/local/var/log/nginx/nginx.vhost.error.log;\n\n    location / {\n        proxy_pass http://localhost:5173;\n\n        proxy_set_header Upgrade $http_upgrade;\n        proxy_set_header Connection 'upgrade';\n        proxy_set_header Host $host;\n        proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;\n        proxy_set_header X-Forwarded-Proto  $scheme;\n        proxy_http_version 1.1;\n        proxy_cache_bypass $http_upgrade;\n        proxy_buffering off;\n\n    }\n}\n```\n\n```text\nserver {\n    listen       443 ssl default_server;\n    server_name  \"\";\n\n    ssl_certificate /usr/local/etc/ssl/public.pem;\n    ssl_certificate_key /usr/local/etc/ssl/private.pem;\n\n    access_log /usr/local/var/log/nginx/nginx.vhost.access.log;\n    error_log /usr/local/var/log/nginx/nginx.vhost.error.log;\n\n    location / {\n        proxy_pass http://localhost:5173;\n\n        proxy_set_header Upgrade $http_upgrade;\n        proxy_set_header Connection 'upgrade';\n        proxy_set_header Host $host;\n        proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;\n        proxy_set_header X-Forwarded-Proto  $scheme;\n        proxy_http_version 1.1;\n        proxy_cache_bypass $http_upgrade;\n        proxy_buffering off;\n\n    }\n}\n```\n\n```text\n/etc/hosts\n```\n\n```text\nlocal-ssl-proxy\n```\n\n```text\nmkcert\n```\n\n```text\nmkcert companydomain.com\n```\n\n```text\nhosts\n```\n\n```text\nmkcert\n```\n\n```text\nlocalhost\n```\n\n```text\n127.0.0.1\n```\n\n```text\n::1\n```\n\n```text\nmkcert *.bogusdevserver.com *.companydomain.com localhost 127.0.0.1 ::1\n```\n\n========================================\n\nComments:\n- Is there a reason you're not trying to serve the vite production build?\n- Hello Zack, thanks for your question, I am not trying to serve the product build I'm only forwarding the development port from localhost:3001/dashboard to localhost:3000/dashboard for a more streamlined development experience","metadata":{"transformedAt":"2026-08-18T18:33:46.428Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":47,"totalLines":585,"estimatedTokens":4287}}447{"id":"stack-73469689","source":"stackoverflow","questionId":73469689,"title":"VueJS/Tailwind CSS/VITE: use env variables as colors for a Tailwind theme","tags":["vue.js","tailwind-css","vite"],"text":"Title: VueJS/Tailwind CSS/VITE: use env variables as colors for a Tailwind theme\nTags: vue.js, tailwind-css, vite\nSource: Stack Overflow\n\nQuestion:\nI have a VueJS setup with Vite, Tailwind CSS and postcss, and would like to define different colors using variables in a `.env.name` file so that I can apply different color themes depending where the code is deployed.\n\nI tried with a `.env` file containing\n\n```\nVITE_COLOR=\"FF0000\"\n```\n\nand an import within the `tailwind.config.js`\n\n```\n...\ntheme: {\n colors: {\n primary: import.meta.env.COLOR\n }\n}\n...\n```\n\nHowever, I get the following error:\n\nSyntaxError: Cannot use 'import.meta' outside a module\n\nWhat do I have to change to get this to work or is there an even better method?\n\n========================================\n\nCode:\n```text\nVITE_COLOR=\"FF0000\"\n```\n\n```js\n...\ntheme: {\n    colors: {\n       primary: import.meta.env.COLOR\n    }\n}\n...\n```\n\n```text\n.env.name\n```\n\n```text\n.env\n```\n\n```text\ntailwind.config.js\n```\n\n```bash\nnpm i dotenv\n```\n\n```js\nrequire('dotenv').config()\n\nmodule.exports = {/** */}\n```\n\n```text\nANY_COLOR='#ffc8dd'\n```\n\n```js\ntheme: {\n    colors: {\n       primary: process.env.ANY_COLOR\n    }\n}\n```\n\n```css\n:root {\n    --theme-color: #ffc8dd;\n}\n```\n\n```js\ntheme: {\n    colors: {\n       primary: 'var(--theme-color)'\n    }\n}\n```\n\n```text\nimport\n```\n\n```text\n.env\n```\n\n```text\nVITE_\n```\n\n```text\n.env\n```\n\n```text\nstyle\n```\n\n```text\n<head>\n```\n\n```text\nindex.html\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.428Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":123,"estimatedTokens":361}}448{"id":"stack-77934659","source":"stackoverflow","questionId":77934659,"title":"How can I dynamically import images stored in $lib within a component in Svelte?","tags":["image","dynamic","vite","svelte","sveltekit"],"text":"Title: How can I dynamically import images stored in $lib within a component in Svelte?\nTags: image, dynamic, vite, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm using an array of dummy data to test how I could display information from an api. In that data, I have a relative image path, for some images I've stored locally in `$lib` for simplicity in testing.\n\nI loop through each object in this dataset, and create a component with the relative image path passed to the object. In my testing the relative paths are resolving correctly, but I'm unable to load the images dynamically.\n\nAfter doing a bit of digging, it seems that this is because of the file structure and permissions with `$lib`. It seems that image import is easy to do if I use a static solution with the images, and just dynamically adjust the relative url, but I want to be able to use Vite's performance improvements when it comes to images. Indeed, Sveltekit documentation recommends storing images in a directory within `$lib` for this exact reason.\n\nIn the component I can manually import each image from `$lib` and it works as expected like so:\n\n```\n\nimport img from '$lib/assets/sample-image.jpg'; \n\n```\n\nBut for the life of me I can't figure out how I can change the import path using a dynamic prop. I imagine it would look something like this:\n\n```\nimport img from '$lib/assets/{object.imageUrlProp}';\n```\n\nOr some type of direct access in the image `src` similar to how static usage would look like:\n\n```\n\n```\n\nBut neither of these are valid syntax.\n\nHow can I dynamically import images stored in `$lib` within a component in Svelte?\n\n### Edit\n\nBrunnerh's answer works great for files with the same extension. As he explains in the comments, for files with differing extensions, a glob import is required. Here is the specific implementation solution I was able to get working. I had some trouble understanding how to access the modules structure normally passed back from the import, so using `as: url` simplified that process for me. Here is the specific implementation solution I was able to get working:\n\n### General Implementation\n\n```\n\nconst images: any = import.meta.glob(['$lib/assets/**.jpg', '$lib/assets/**.png', '$lib/assets/**.svg'], { eager: true, as: 'url' });\n\n```\n\n### My Specific Use Case Implementation\n\nI was trying to iterate through JSON data containing relative image URLs:\n\n```\n\n import { pages } from '$lib/data/sample_data.json';\n const images: any = import.meta.glob(['$lib/images/**.jpg', '$lib/images/**.png', '$lib/images/**.svg'], { eager: true, as: 'url' });\n\n{#each Object.entries(pages) as [key, page], index (key)}\n \n \n \n\n### {page.title}\n\n \n{/each}\n\n{\n \"pages\": [\n {\n \"title\": \"First Page\",\n \"featured_image\": \"image.png\",\n \"image_alt\": \"alt for page 1\"\n },\n {\n \"title\": \"Second Page\",\n \"featured_image\": \"image2.jpg\",\n \"image_alt\": \"alt for page 2\"\n },\n {\n \"title\": \"Third Page\",\n \"featured_image\": \"image3.svg\",\n \"image_alt\": \"alt for page 3\"\n },\n ]\n}\n```\n\n========================================\n\nCode:\n```text\n<script>\nimport img from '$lib/assets/sample-image.jpg'; \n</script>\n\n<img src={img} />\n```\n\n```text\nimport img from '$lib/assets/{object.imageUrlProp}';\n```\n\n```text\n<img src=\"$lib/assets/{object.imageUrlProp}\" alt=\"Image\" />\n```\n\n```text\n<script lang=\"ts\">\nconst images: any = import.meta.glob(['$lib/assets/**.jpg', '$lib/assets/**.png', '$lib/assets/**.svg'], { eager: true, as: 'url' });\n<!--You can change allowed extensions here, or you could do something like '$lib/assets/**' without an extension to allow imports for any file types. The '**' allows for nested folders, so you can replace it with '*' if all assets are directly stored in the assets folder-->\n<script>\n\n<!--imageURL will look something like image1.png or folder1/image1.png-->\n<img src={images[\"/src/lib/assets/\" + imageURL} />\n```\n\n```text\n<script lang=\"ts\">\n    import { pages } from '$lib/data/sample_data.json';\n    const images: any = import.meta.glob(['$lib/images/**.jpg', '$lib/images/**.png', '$lib/images/**.svg'], { eager: true, as: 'url' });\n</script>\n\n{#each Object.entries(pages) as [key, page], index (key)}\n    <div class=\"page\">\n        <img src={images[\"/src/lib/images/\" + page.featured_image]} alt={page.image_alt} />\n        <h2>{page.title}</h2>\n    </div>\n{/each}\n\n<!--Sample JSON Data-->\n{\n    \"pages\": [\n        {\n            \"title\": \"First Page\",\n            \"featured_image\": \"image.png\",\n            \"image_alt\": \"alt for page 1\"\n        },\n        {\n            \"title\": \"Second Page\",\n            \"featured_image\": \"image2.jpg\",\n            \"image_alt\": \"alt for page 2\"\n        },\n        {\n            \"title\": \"Third Page\",\n            \"featured_image\": \"image3.svg\",\n            \"image_alt\": \"alt for page 3\"\n        },\n    ]\n}\n```\n\n```text\n$lib\n```\n\n```text\n$lib\n```\n\n```text\n$lib\n```\n\n```text\n$lib\n```\n\n```text\nsrc\n```\n\n```text\n$lib\n```\n\n```text\nas: url\n```\n\n```html\n{#await import(`$lib/assets/${object.imageUrlProp}.jpg`) then { default: src }}\n  <img {src} alt=\"Image\" />\n{/await}\n```\n\n```js\nconst images = import.meta.glob(\n    '$lib/assets/*.jpg',\n    { eager: true, import: 'default' },\n);\n```\n\n```html\n<Component imgSrc={images[`$lib/assets/${object.imageName}.jpg`]} />\n```\n\n```text\neager\n```\n\n```text\nawait\n```\n\n```text\nsrc\n```\n\n========================================\n\nComments:\n- This does indeed work, but requires that all my images have the same extension. For now this is not a problem, but ideally I’d like to be able to show any images from that. Also, do await and glob import impact performance? Perhaps I’m going about this in a way that doesn’t make sense?\n- The await is kind of pointless since it imports just a path, not the contents, it will mostly cost the time of a round trip, if the bundler does not inline the path during build. Globbing happens at build time, should not drastically affect runtime as long as you don't have thousands of pictures. You can use multiple patterns to support different locations/extensions.\n- What would the syntax look like using multiple patterns? I imagine the import would look something like const images = import.meta.glob('$lib/assets/*.jpg', '$lib/assets/*.png', '$lib/assets/*.svg', { eager: true }); perhaps? But how do you reference the path in the array call without the extension? Also, what if you're only importing a single image, would you still have to use glob import so you could use different extensions?\n- See docs on multiple patterns, the first argument becomes an array. If you import via a path like `.&#47;files&#47;*`, you don't need an extension and the result of the import is a plain object, you can iterate over the imported modules by just getting the values with `Object.values`. You will need a glob import for a single file if the name the file is not fixed.\n- Can I call a glob import in the middle of the svelte file (right now I have an {#each} block iterating through a JSON file and importing data), or does it have to be at the beginning, all at once?\n- Don't know, consult docs or try it.\n- I couldn't find anything in the docs, and nothing I tried worked. For now it will remain a mystery. Thanks again for all your help, the solution I have now works great for my needs! I suppose if someone has to dynamically import different file extensions, and they don't know what the locations will be until after the page is loaded then they may need to find an alternate solution.","metadata":{"transformedAt":"2026-08-18T18:33:46.428Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":218,"estimatedTokens":1858}}449{"id":"stack-76332347","source":"stackoverflow","questionId":76332347,"title":"Chrome hangs with Vite Dev Server","tags":["javascript","reactjs","google-chrome","vite"],"text":"Title: Chrome hangs with Vite Dev Server\nTags: javascript, reactjs, google-chrome, vite\nSource: Stack Overflow\n\nQuestion:\nI just migrated a big react application from **Webpack** to **Vite**. I configured to make use of the dev server with HMR. The project is kind of big and it has a lot of dependencies and many pages that I thinkg are loaded in the first load. I am using react-router for the routing and I don't have the time to lazy load the components yet.\n\nThis is my vite.config.js:\n\n```\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport path from \"path\";\n\nexport default defineConfig({\n root: \"src\",\n envDir: \"../\",\n envPrefix: \"REACT_\", // To mantain compatibility with our current env vars\n build: {\n target: \"esnext\",\n commonjsOptions: {\n transformMixedEsModules: true,\n },\n },\n plugins: [react()],\n resolve: {\n alias: {\n \"@\": path.resolve(__dirname, \"./src\"),\n },\n },\n server: {\n port: 8080,\n host: \"0.0.0.0\",\n\n proxy: {\n \"/api\": {\n target: \"http://localhost:5000\",\n changeOrigin: true,\n rewrite: (path) => path.replace(\"/api\", \"\"),\n },\n },\n },\n});\n```\n\nWhen I run the dev server I can access it with no problems using Firefox but when I use Chrome the tabs hangs and if I get to open the devtools I see many static files are pending and won't load.\n\nhttps://i.sstatic.net/CGpen.png\n\nA huge bunch of file are being loaded but Firefox has no issue loading them so I don't know if it's a Chrome issue or I missed something.\n\nDoing my research and deductions I think it has something to do with the cache but I am not sure what is the issue.\n\nLet me know if you need more details!\n\n========================================\n\nTop Answer:\nAs Vite's troubleshooting section will also mention, VS Code devcontainers do not work with the dev server by default because they do not support IPv6.\n\nYou can fix this by passing the `--host` flag to `vite` like `vite host` or if using npm, `npm run dev -- --host`. (`--` forwards further flags to the `dev` script).\n\nOr you can set server.host option to `127.0.0.1`.\n\n========================================\n\nCode:\n```js\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport path from \"path\";\n\nexport default defineConfig({\n  root: \"src\",\n  envDir: \"../\",\n  envPrefix: \"REACT_\", // To mantain compatibility with our current env vars\n  build: {\n    target: \"esnext\",\n    commonjsOptions: {\n      transformMixedEsModules: true,\n    },\n  },\n  plugins: [react()],\n  resolve: {\n    alias: {\n      \"@\": path.resolve(__dirname, \"./src\"),\n    },\n  },\n  server: {\n    port: 8080,\n    host: \"0.0.0.0\",\n\n    proxy: {\n      \"/api\": {\n        target: \"http://localhost:5000\",\n        changeOrigin: true,\n        rewrite: (path) => path.replace(\"/api\", \"\"),\n      },\n    },\n  },\n});\n```\n\n```text\n* - nofile 65536\n```\n\n```text\n--host\n```\n\n```text\nvite\n```\n\n```text\nvite host\n```\n\n```text\nnpm run dev -- --host\n```\n\n```text\n--\n```\n\n```text\ndev\n```\n\n```text\n127.0.0.1\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.428Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":134,"estimatedTokens":743}}450{"id":"stack-76754734","source":"stackoverflow","questionId":76754734,"title":"Error in production build with Vite & React: Error in Uncaught TypeError: _ is not a function","tags":["reactjs","typescript","axios","vite","production"],"text":"Title: Error in production build with Vite & React: Error in Uncaught TypeError: _ is not a function\nTags: reactjs, typescript, axios, vite, production\nSource: Stack Overflow\n\nQuestion:\nI am using Vite, React, React Router and TypeScript for my website.\nI have a problem when running the production build, in dev mode everything works fine.\n\nWhen using the production build my browser shows a white background and I get the following error in my browser console:\n\nhttps://i.sstatic.net/ucCFs.png\n\nThe upper link brings me to the following (minified?) source code in line 70:\n\nhttps://i.sstatic.net/MP1Hl.png\n\nSo maybe it has something to do with React Router?\n\nBut I am unsure what exactly causes this error.\nTherefore, I will try to provide as much relevant information as I can below.\n\nMy results when running `npm run build`:\n\nhttps://i.sstatic.net/mlMRO.png\n\npackage.json:\n\n```\n{\n \"name\": \"frontend\",\n \"private\": true,\n \"version\": \"0.0.0\",\n \"type\": \"module\",\n \"scripts\": {\n \"start\": \"vite\",\n \"build\": \"tsc && vite build\",\n \"lint\": \"eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0\",\n \"preview\": \"vite preview\",\n \"test\": \"jest\"\n },\n \"dependencies\": {\n \"@faker-js/faker\": \"^8.0.2\",\n \"@vitejs/plugin-react\": \"^4.0.3\",\n \"axios\": \"^1.4.0\",\n \"chart.js\": \"^4.3.0\",\n \"daisyui\": \"^3.1.7\",\n \"dayjs\": \"^1.11.9\",\n \"i18next\": \"^23.2.7\",\n \"i18next-browser-languagedetector\": \"^7.1.0\",\n \"lucide-react\": \"^0.258.0\",\n \"react\": \"^18.2.0\",\n \"react-chartjs-2\": \"^5.2.0\",\n \"react-dom\": \"^18.2.0\",\n \"react-i18next\": \"^13.0.1\",\n \"react-router-dom\": \"^6.14.2\",\n \"vite\": \"^4.4.6\"\n },\n \"devDependencies\": {\n \"@tailwindcss/typography\": \"^0.5.9\",\n \"@types/axios\": \"^0.14.0\",\n \"@types/node\": \"^20.1.1\",\n \"@types/react\": \"^18.0.28\",\n \"@types/react-dom\": \"^18.0.11\",\n \"@typescript-eslint/eslint-plugin\": \"^5.57.1\",\n \"@typescript-eslint/parser\": \"^5.57.1\",\n \"autoprefixer\": \"^10.4.14\",\n \"eslint\": \"^8.2.0\",\n \"eslint-config-airbnb\": \"^19.0.4\",\n \"eslint-config-prettier\": \"^8.8.0\",\n \"eslint-plugin-import\": \"^2.25.3\",\n \"eslint-plugin-jsx-a11y\": \"^6.5.1\",\n \"eslint-plugin-prettier\": \"^4.2.1\",\n \"eslint-plugin-react\": \"^7.28.0\",\n \"eslint-plugin-react-hooks\": \"^4.3.0\",\n \"eslint-plugin-react-refresh\": \"^0.3.4\",\n \"jest\": \"^29.5.0\",\n \"postcss\": \"^8.4.23\",\n \"prettier\": \"^2.8.8\",\n \"prettier-plugin-tailwindcss\": \"^0.2.8\",\n \"tailwindcss\": \"^3.3.2\",\n \"typescript\": \"^5.0.2\"\n }\n}\n```\n\nvite.config.ts:\n\n```\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n});\n```\n\ntsconfig.json:\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"ESNext\",\n \"lib\": [\"DOM\", \"DOM.Iterable\", \"ESNext\"],\n \"module\": \"ESNext\",\n \"skipLibCheck\": true,\n\n /* Bundler mode */\n \"moduleResolution\": \"bundler\",\n \"allowImportingTsExtensions\": true,\n \"resolveJsonModule\": true,\n \"isolatedModules\": true,\n \"noEmit\": true,\n \"jsx\": \"react-jsx\",\n\n /* Linting */\n \"strict\": true,\n \"noUnusedLocals\": true,\n \"noUnusedParameters\": true,\n \"noFallthroughCasesInSwitch\": true\n },\n \"include\": [\"src\"],\n \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\ntsconfig.node.json:\n\n```\n{\n \"compilerOptions\": {\n \"composite\": true,\n \"skipLibCheck\": true,\n \"module\": \"ESNext\",\n \"moduleResolution\": \"bundler\",\n \"allowSyntheticDefaultImports\": true\n },\n \"include\": [\"vite.config.ts\"]\n}\n```\n\nWhen using `npm start` everything works as expected, but if I use `npm run build` and then `npm run preview` I get the error mentioned above and my browser shows a white background.\n\n### What I already tried\n\nI already tried to disable code splitting in Vite by using the following vite.config.ts:\n\n```\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n build: {\n rollupOptions: {\n output: {\n manualChunks: {},\n },\n },\n },\n});\n```\n\nThis did not have any effect however.\n\nI tried replacing out all my fragments in React:\n\n```\n<>\n ...\n\n```\n\nwith:\n\n```\n\n ...\n\n```\n\nBut this also did not have any effect.\n\n========================================\n\nTop Answer:\nThe issue is typescript version issue , if you are using the vite + react + typescript then you need to convert the app to create-react-app with typescript template `npx create-react-app app-name --template typescript` then you need to convert the vite configuration to react app configuration like env setting.\n\n```\nvite - import.meta.env.VITE_ENV_NAME\n\ncra - process.env.REACT_APP_ENV_NAME\n```\n\nthen build the app and run the build locally.\n\n========================================\n\nCode:\n```json\n{\n    \"name\": \"frontend\",\n    \"private\": true,\n    \"version\": \"0.0.0\",\n    \"type\": \"module\",\n    \"scripts\": {\n        \"start\": \"vite\",\n        \"build\": \"tsc && vite build\",\n        \"lint\": \"eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0\",\n        \"preview\": \"vite preview\",\n        \"test\": \"jest\"\n    },\n    \"dependencies\": {\n        \"@faker-js/faker\": \"^8.0.2\",\n        \"@vitejs/plugin-react\": \"^4.0.3\",\n        \"axios\": \"^1.4.0\",\n        \"chart.js\": \"^4.3.0\",\n        \"daisyui\": \"^3.1.7\",\n        \"dayjs\": \"^1.11.9\",\n        \"i18next\": \"^23.2.7\",\n        \"i18next-browser-languagedetector\": \"^7.1.0\",\n        \"lucide-react\": \"^0.258.0\",\n        \"react\": \"^18.2.0\",\n        \"react-chartjs-2\": \"^5.2.0\",\n        \"react-dom\": \"^18.2.0\",\n        \"react-i18next\": \"^13.0.1\",\n        \"react-router-dom\": \"^6.14.2\",\n        \"vite\": \"^4.4.6\"\n    },\n    \"devDependencies\": {\n        \"@tailwindcss/typography\": \"^0.5.9\",\n        \"@types/axios\": \"^0.14.0\",\n        \"@types/node\": \"^20.1.1\",\n        \"@types/react\": \"^18.0.28\",\n        \"@types/react-dom\": \"^18.0.11\",\n        \"@typescript-eslint/eslint-plugin\": \"^5.57.1\",\n        \"@typescript-eslint/parser\": \"^5.57.1\",\n        \"autoprefixer\": \"^10.4.14\",\n        \"eslint\": \"^8.2.0\",\n        \"eslint-config-airbnb\": \"^19.0.4\",\n        \"eslint-config-prettier\": \"^8.8.0\",\n        \"eslint-plugin-import\": \"^2.25.3\",\n        \"eslint-plugin-jsx-a11y\": \"^6.5.1\",\n        \"eslint-plugin-prettier\": \"^4.2.1\",\n        \"eslint-plugin-react\": \"^7.28.0\",\n        \"eslint-plugin-react-hooks\": \"^4.3.0\",\n        \"eslint-plugin-react-refresh\": \"^0.3.4\",\n        \"jest\": \"^29.5.0\",\n        \"postcss\": \"^8.4.23\",\n        \"prettier\": \"^2.8.8\",\n        \"prettier-plugin-tailwindcss\": \"^0.2.8\",\n        \"tailwindcss\": \"^3.3.2\",\n        \"typescript\": \"^5.0.2\"\n    }\n}\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n    plugins: [react()],\n});\n```\n\n```json\n{\n    \"compilerOptions\": {\n        \"target\": \"ESNext\",\n        \"lib\": [\"DOM\", \"DOM.Iterable\", \"ESNext\"],\n        \"module\": \"ESNext\",\n        \"skipLibCheck\": true,\n\n        /* Bundler mode */\n        \"moduleResolution\": \"bundler\",\n        \"allowImportingTsExtensions\": true,\n        \"resolveJsonModule\": true,\n        \"isolatedModules\": true,\n        \"noEmit\": true,\n        \"jsx\": \"react-jsx\",\n\n        /* Linting */\n        \"strict\": true,\n        \"noUnusedLocals\": true,\n        \"noUnusedParameters\": true,\n        \"noFallthroughCasesInSwitch\": true\n    },\n    \"include\": [\"src\"],\n    \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\n```json\n{\n    \"compilerOptions\": {\n        \"composite\": true,\n        \"skipLibCheck\": true,\n        \"module\": \"ESNext\",\n        \"moduleResolution\": \"bundler\",\n        \"allowSyntheticDefaultImports\": true\n    },\n    \"include\": [\"vite.config.ts\"]\n}\n```\n\n```js\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n    plugins: [react()],\n    build: {\n        rollupOptions: {\n            output: {\n                manualChunks: {},\n            },\n        },\n    },\n});\n```\n\n```text\n<>\n    ...\n</>\n```\n\n```text\n<Fragment>\n    ...\n<Fragment/>\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm start\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm run preview\n```\n\n```text\nimport * as dayjs from \"dayjs\";\nimport * as customParseFormat from \"dayjs/plugin/customParseFormat\";\n```\n\n```text\nimport dayjs from \"dayjs\";\nimport customParseFormat from \"dayjs/plugin/customParseFormat\";\n```\n\n```text\nvite - import.meta.env.VITE_ENV_NAME\n\ncra - process.env.REACT_APP_ENV_NAME\n```\n\n```text\nnpx create-react-app app-name  --template typescript\n```\n\n========================================\n\nComments:\n- Line 70 in that minified code screenshot appears to be related to axios, returning some axios headers. Can you edit to replace all the screen captures of errors and code with ***actual*** formatted and readable text and code snippets? If there is an accompanying error stacktrace please also include that.\n- @DrewReese Your reply made me take a close look at the minified code and I found the problem :) I posted an answer explaining how to fix it. Thank you so much for pointing me in the right direction :)\n- This was the same issue for me and your solution helped me, thanks!\n- Had this same problem in a Vue.js build without typescript, and your solution worked. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:46.429Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":380,"estimatedTokens":2273}}451{"id":"stack-74450389","source":"stackoverflow","questionId":74450389,"title":"How do I use Vue3 + TypeScript v-model on textfield? \"ERROR: Invalid assignment target\"","tags":["typescript","vue.js","vuejs3","vite","v-model"],"text":"Title: How do I use Vue3 + TypeScript v-model on textfield? \"ERROR: Invalid assignment target\"\nTags: typescript, vue.js, vuejs3, vite, v-model\nSource: Stack Overflow\n\nQuestion:\n### *Full Error:*\n\n```\n[plugin:vite:vue] Transform failed with 1 error:\n/home/projects/vue3-vite-typescript-starter-jkcbyx/src/App.vue:33:73: \nERROR: Invalid assignment target\n\n\"/home/projects/vue3-vite-typescript-starter-jkcbyx/src/App.vue:33:73\"\n\nInvalid assignment target\n31 | ? (_openBlock(), _createElementBlock(\"div\", _hoisted_2, [\n32 | _withDirectives(_createElementVNode(\"textarea\", {\n33 | \"onUpdate:modelValue\": _cache[0] || (_cache[0] = $event => (($setup.np?.description) = $event))\n | ^\n34 | }, null, 512 /* NEED_PATCH */), [\n35 | [\n```\n\n### Here is the `App.vue`:\n\n```\n\nimport { ref } from 'vue'\n\ninterface Thing {\n description: string\n}\n\nconst np = ref({\n description: 'asdf asdf asdf',\n})\n\n {{ np?.description }}\n \n\n \n\n```\n\n### HERE is a Full recreation of the error:\n\n- https://stackblitz.com/edit/vue3-vite-typescript-starter-jkcbyx?file=src/App.vue\n\nAny help here is appreciated <3\n\nThis problem is rather confounding.\n\n========================================\n\nCode:\n```js\n[plugin:vite:vue] Transform failed with 1 error:\n/home/projects/vue3-vite-typescript-starter-jkcbyx/src/App.vue:33:73: \nERROR: Invalid assignment target\n\n\"/home/projects/vue3-vite-typescript-starter-jkcbyx/src/App.vue:33:73\"\n\nInvalid assignment target\n31 |        ? (_openBlock(), _createElementBlock(\"div\", _hoisted_2, [\n32 |            _withDirectives(_createElementVNode(\"textarea\", {\n33 |              \"onUpdate:modelValue\": _cache[0] || (_cache[0] = $event => (($setup.np?.description) = $event))\n   |                                                                           ^\n34 |            }, null, 512 /* NEED_PATCH */), [\n35 |              [\n```\n\n```html\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\n\ninterface Thing {\n  description: string\n}\n\nconst np = ref<Thing>({\n  description: 'asdf asdf asdf',\n})\n</script>\n\n<template>\n  {{ np?.description }}\n  <br />\n  <textarea v-model.trim=\"np?.description\"></textarea>\n</template>\n```\n\n```text\nApp.vue\n```\n\n```js\nconst description = computed({\n  get() {\n    return np.value?.description || ''\n  },\n  set(description) {\n    if (typeof np.value?.description === 'string') {\n      np.value = { ...np.value, description }\n    }\n  },\n})\n```\n\n```text\nv-model\n```\n\n```text\nnp?.description\n```\n\n```text\nnp\n```\n\n```text\nv-if\n```\n\n```text\nv-model\n```\n\n```text\nundefined\n```\n\n```text\ndescription\n```\n\n```text\nnp.description\n```\n\n```text\nnp\n```\n\n```text\nv-model\n```\n\n```text\n<textarea>\n```\n\n```text\nv-if=\"np\"\n```\n\n```text\nv-model\n```\n\n```text\nv-model.trim=\"np?.description\"\n```\n\n```text\nv-model.trim=\"np.description\"\n```\n\n========================================\n\nComments:\n- may be worth noting the same error is given if `const np = reactive<>()` is used instead.\n- Your code is fine, but the template doesn't seem to be able to handle the optional chaining operator at `v-model=\"np?.description\"`. This may be due to the versions of Vite/compilers that stackblitz is using. If you remove the operator it compiles fine.\n- Yep, that was it, Thank you so much. I didn't question the `?` because when I hit \"tab\" in my editor to auto-complete, it put a `?` in there. I feel dumb\n- Don't! JavaScript is tricky, by nature. I learn things about it every day, and I've been at it for quite some time now. Happy coding!\n- Thank you for this, it solved my issue too. v-model binding & typescript with nullable values are a nasty cocktail. This isn't pretty but it fixes the issue","metadata":{"transformedAt":"2026-08-18T18:33:46.429Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":176,"estimatedTokens":898}}452{"id":"stack-77666669","source":"stackoverflow","questionId":77666669,"title":"VSCode - EsLint warning \"Classname is not a Tailwind CSS class\" shown mistakenly","tags":["reactjs","visual-studio-code","tailwind-css","eslint","vite"],"text":"Title: VSCode - EsLint warning \"Classname is not a Tailwind CSS class\" shown mistakenly\nTags: reactjs, visual-studio-code, tailwind-css, eslint, vite\nSource: Stack Overflow\n\nQuestion:\nIn my vite + react + tailwind project, I get the following warning by VsCode:\n\nhttps://i.sstatic.net/j2kB2.png\n\nHowever, the font-size `myLarge` is correctly defined in my `tailwind.config.js`:\n\n```\nmodule.exports = {\n content: [\"./src/**/*.{ts,tsx}\"],\n theme: {\n extend: {\n fontSize: {\n myLarge: \"10rem\",\n },\n },\n },\n};\n```\n\n- As we can see in the screenshot, the IDE correctly recognizes the css rule for `text-myLarge`\n\n- If I run `npm run lint` in a terminal outside of the IDE the warning is NOT shown\n\n- The font-size is CORRECTLY applied in the app, when I view it in the browser\n\n- I do not want to disable the `\"tailwindcss/no-custom-classname\"` rule. I just want it to be correctly applied in VsCode\n\nCan you help me on how to fix that warning in VsCode? Are there any settings I'm missing? I've already restarted the VsCode Eslint-server and also the whole IDE. Do you have any hints on how to track down that issue?\n\nFor reference, this is my `.eslintrc.js`:\n\n```\nmodule.exports = {\n root: true,\n env: { browser: true, es2020: true, node: true },\n extends: [\n \"eslint:recommended\",\n \"plugin:@typescript-eslint/recommended\",\n \"plugin:react-hooks/recommended\",\n \"prettier\",\n \"plugin:tailwindcss/recommended\",\n ],\n ignorePatterns: [\"dist\"],\n parser: \"@typescript-eslint/parser\",\n plugins: [\"react\"],\n rules: {\n \"tailwindcss/no-custom-classname\": [\n \"warn\",\n {\n cssFiles: [\"src/**/*.css\"],\n callees: [\"classnames\", \"clsx\", \"twMerge\", \"cn\"],\n },\n ],\n },\n};\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n    content: [\"./src/**/*.{ts,tsx}\"],\n    theme: {\n        extend: {\n            fontSize: {\n                myLarge: \"10rem\",\n            },\n        },\n    },\n};\n```\n\n```text\nmodule.exports = {\n    root: true,\n    env: { browser: true, es2020: true, node: true },\n    extends: [\n        \"eslint:recommended\",\n        \"plugin:@typescript-eslint/recommended\",\n        \"plugin:react-hooks/recommended\",\n        \"prettier\",\n        \"plugin:tailwindcss/recommended\",\n    ],\n    ignorePatterns: [\"dist\"],\n    parser: \"@typescript-eslint/parser\",\n    plugins: [\"react\"],\n    rules: {\n        \"tailwindcss/no-custom-classname\": [\n            \"warn\",\n            {\n                cssFiles: [\"src/**/*.css\"],\n                callees: [\"classnames\", \"clsx\", \"twMerge\", \"cn\"],\n            },\n        ],\n    },\n};\n```\n\n```text\nmyLarge\n```\n\n```text\ntailwind.config.js\n```\n\n```text\ntext-myLarge\n```\n\n```text\nnpm run lint\n```\n\n```text\n\"tailwindcss/no-custom-classname\"\n```\n\n```text\n.eslintrc.js\n```\n\n```text\nsettings: {\n        tailwindcss: {\n            config: path.join(__dirname, \"./tailwind.config.js\"),\n        },\n    },\n```\n\n```text\ntailwind.config.js\n```\n\n```text\n.eslintrc.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.429Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":143,"estimatedTokens":726}}453{"id":"stack-77241807","source":"stackoverflow","questionId":77241807,"title":"How to change the build directory in SvelteKit?","tags":["svelte","vite","sveltekit"],"text":"Title: How to change the build directory in SvelteKit?\nTags: svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nIn SvelteKit, I can't figure out a way to change the path of the actual build directory (not the app or the generated directory) via configuration. I've tried changing it in Vite configuration (1) but I get the message (2).\n\n1.\n\n```\n// vite.config.ts\nimport { sveltekit } from \"@sveltejs/kit/vite\"\nimport { defineConfig } from \"vite\"\n\nexport default defineConfig({\n plugins: [ sveltekit() ],\n build: { outDir: \"builds\" }\n})\n```\n\n- \n\n```\nThe following Vite config options will be overridden by SvelteKit:\n - build.outDir\n```\n\nFor context, I'm making a mono-repo for a cross-platform app with the Vite generated SvelteKit build as a basis for the native platform apps.\n\n========================================\n\nCode:\n```js\n// vite.config.ts\nimport { sveltekit } from \"@sveltejs/kit/vite\"\nimport { defineConfig } from \"vite\"\n\nexport default defineConfig({\n    plugins: [ sveltekit() ],\n    build: { outDir: \"builds\" }\n})\n```\n\n```bash\nThe following Vite config options will be overridden by SvelteKit:\n  - build.outDir\n```\n\n```js\n// svelte.config.js\nimport adapter from \"@sveltejs/adapter-static\"\nimport { vitePreprocess } from \"@sveltejs/kit/vite\"\n\n/** @type {import(\"@sveltejs/kit\").Config} */\nconst config = {\n    // Consult https://kit.svelte.dev/docs/integrations#preprocessors\n    // for more information about preprocessors\n    preprocess: vitePreprocess(),\n\n    kit: {\n        adapter: adapter({ pages: \"builds\" })\n    }\n}\n\nexport default config\n```\n\n```text\npages\n```\n\n========================================\n\nComments:\n- Not sure if this help, you can define your own build route when using sveltekit `adapter-static` kit.svelte.dev/docs/adapter-static","metadata":{"transformedAt":"2026-08-18T18:33:46.429Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":75,"estimatedTokens":445}}454{"id":"stack-71104342","source":"stackoverflow","questionId":71104342,"title":"Unable to access process variable in Vue3JS Vite project","tags":["javascript","vue.js","web3js","vite","ipfs"],"text":"Title: Unable to access process variable in Vue3JS Vite project\nTags: javascript, vue.js, web3js, vite, ipfs\nSource: Stack Overflow\n\nQuestion:\nI am creating a vue3 application (created with Vite) that interacts with a smart contract written in Solidity and stored on Ropsten. Therefore I am using web3js to interact with my smart contracts and also web3.storage in order to store some images on IPFS. I have a `.env` file at the root of my project storing my API key for web3.storage :\n\n```\nVUE_APP_API_TOKEN=VALUE\nVITE_API_TOKEN=VALUE\n```\n\nThe problem is that apparently web3.storage expects the API token to be stored in process.env and I am unable to access the global `process` variable from my application. I am always getting an error `Uncaught ReferenceError: process is not defined`.\n\nI think, this is linked to my usage of Vite instead of pure Vue3.\nI tried to export process env in the `vite.config.ts` file with that code but it didn't work:\n\n```\nexport default ({ mode }) => {\n process.env = { ...process.env, ...loadEnv(mode, process.cwd(), '') };\n\n console.log(process.env.VITE_API_TOKEN) //Works fine: VALUE is logged\n console.log(process.env.VUE_APP_API_TOKEN) //Works fine: VALUE is logged\n\n return defineConfig({\n plugins: [vue()]\n });\n}\n```\n\nHow could I access the `process` variable from my vue files in order to get the values of my environment variable and make web3.storage work?\n\n========================================\n\nTop Answer:\nIf you're running the build script in CI you will need to make sure that you're creating / populating the relevant `.env` file before you run the build script.\n\n========================================\n\nCode:\n```text\nVUE_APP_API_TOKEN=VALUE\nVITE_API_TOKEN=VALUE\n```\n\n```text\nexport default ({ mode }) => {\n   process.env = { ...process.env, ...loadEnv(mode, process.cwd(), '') };\n\n   console.log(process.env.VITE_API_TOKEN)         //Works fine: VALUE is logged\n   console.log(process.env.VUE_APP_API_TOKEN)      //Works fine: VALUE is logged\n\n   return defineConfig({\n       plugins: [vue()]\n   });\n}\n```\n\n```text\n.env\n```\n\n```text\nprocess\n```\n\n```text\nUncaught ReferenceError: process is not defined\n```\n\n```text\nvite.config.ts\n```\n\n```text\nprocess\n```\n\n```text\nVITE_WEB3_STORAGE_TOKEN=\"your_token\"\n```\n\n```text\nconsole.log(import.meta.env.VITE_WEB3_STORAGE_TOKEN) // \"your_token\"\n```\n\n```text\nVITE_\n```\n\n```text\nVITE_\n```\n\n```text\n.env\n```\n\n========================================\n\nComments:\n- Docs might help.\n- @tao thanks for the tip, I already tried with the documentation but it didn't help\n- Okay thank you for your solution, I feel like this is the only way. The \"process\" global variable doesn't seem to be accessible anymore in Vue3 projects\n- It's not, for precisely the reason quoted in my answer. Considering what `process` has access to, and what people tend to put in those environment variables, I personally think it's a sensible only to expose what's been prefixed with `VITE`. You can now safely use other names for stuff that should not be visible anywhere in the client.","metadata":{"transformedAt":"2026-08-18T18:33:46.429Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":105,"estimatedTokens":763}}455{"id":"stack-76297888","source":"stackoverflow","questionId":76297888,"title":"React (vite) hmr is breaking the app, the page goes blank","tags":["reactjs","vite"],"text":"Title: React (vite) hmr is breaking the app, the page goes blank\nTags: reactjs, vite\nSource: Stack Overflow\n\nQuestion:\nI migrated from cra to vite and now have the this problem:\n\nWhen hmr is triggered, or when I visit another page (sometimes), the page goes blank and I get many errors:\n\n```\nUncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.\n```\n\n```\nThe above error occurred in the component:\n```\n\n```\nThe above error occurred in the component:\n```\n\nAlso:\n\n```\nWarning: You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before. Instead, call root.render() on the existing root instead if you want to update it.\n```\n\nHowever, I call createRoot only once in main.tsx file.\n\nI use **react-router-dom**: version \"**^6.4.2**\".\n\nI see the **removeChild** error after build too, unfortunately.\n\nWhat did I wrong during the migration process?\n\n========================================\n\nCode:\n```text\nUncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.\n```\n\n```text\nThe above error occurred in the <Fragment> component:\n```\n\n```text\nThe above error occurred in the <StrictMode> component:\n```\n\n```text\nWarning: You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before. Instead, call root.render() on the existing root instead if you want to update it.\n```\n\n```text\nconst ContextWrappers = ({chidlren}) => (\n   <SomeContextProvider>{chidlren}</SomeContextProvider> \n)\n\nconst App = () => (\n   <div className=\"mega-app\">\n     <ContextWrappers>\n         <YourSexyAppCode />\n     </ContextWrapper>\n   </div>\n\n)\n\nroot.render(\n  <App />\n);\n```\n\n```text\nhmr: { clientPort: 3000 },\n  origin: 'https://localhost:3000',\n```\n\n========================================\n\nComments:\n- Thank you, you saved my day! I naively placed everything in a single `main.tsx` file, which magically led to the `Node.removeChild` exception after a simple `Ctrl+S` on a `main.tsx`. Moving `App` to `App.tsx` solves the issue.","metadata":{"transformedAt":"2026-08-18T18:33:46.429Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":82,"estimatedTokens":532}}456{"id":"stack-71795143","source":"stackoverflow","questionId":71795143,"title":"How to use Bootstrap5 with Vite and Nuxt3?","tags":["twitter-bootstrap","bootstrap-5","bootstrap-vue","vite","nuxt3.js"],"text":"Title: How to use Bootstrap5 with Vite and Nuxt3?\nTags: twitter-bootstrap, bootstrap-5, bootstrap-vue, vite, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nTailwind makes it easy to use its CSS in projects set up with Vite as you can see here.\n\nHowever, Bootstrap 5 only has information available for using with Webpack.\n\nI can not find anything about how to set Bootstrap 5 CSS with Vite. Does anyone have any tips on how to successfully and optimally set up Bootstrap 5 with Vite? I am using Nuxt3 but it should not matter which framework one uses.\n\n========================================\n\nTop Answer:\nNow you can find the official words from bootstrap v5.2 Document\n\nhttps://getbootstrap.com/docs/5.2/getting-started/vite/\n\nAfter install Nuxt3 this is official guide:\n\n1- Install Vite. Unlike our Webpack guide, there’s only a single build tool dependency here. We use --save-dev to signal that this dependency is only for development use and not for production.\n\n```\nnpm i --save-dev vite\n```\n\n2- Install Bootstrap. Now we can install Bootstrap. We’ll also install Popper since our dropdowns, popovers, and tooltips depend on it for their positioning. If you don’t plan on using those components, you can omit Popper here.\n\n```\nnpm i --save bootstrap @popperjs/core\n```\n\n3- Install additional dependency. In addition to Vite and Bootstrap, we need another dependency (Sass) to properly import and bundle Bootstrap’s CSS\n\n```\nnpm i --save-dev sass\n```\n\n========================================\n\nCode:\n```text\nimport { defineNuxtConfig } from 'nuxt'\nexport default defineNuxtConfig({\n  app: {\n    head: {\n      link: [\n        { rel: 'stylesheet', href: 'https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css', integrity: 'sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor', crossorigin: 'anonymous' }\n      ],\n      script: [\n        { src: 'https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.bundle.min.js', integrity: 'sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2', crossorigin: 'anonymous' }\n      ]\n    }\n  }\n})\n```\n\n```bash\nyarn add bootstrap @popperjs/core\n```\n\n```text\nimport bootstrap from 'bootstrap/dist/js/bootstrap.bundle'\n\nexport default defineNuxtPlugin(nuxtApp => {\n  nuxtApp.provide('bootstrap', bootstrap)\n})\n```\n\n```text\nconst { $bootstrap } = useNuxtApp()\n```\n\n```scss\n@import 'bootstrap/scss/bootstrap';\n```\n\n```text\nimport { defineNuxtConfig } from 'nuxt'\n\nexport default defineNuxtConfig({\n  css: ['~/assets/styles/main.scss']\n})\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nplugins/useBootstrap.client.ts\n```\n\n```text\nassets/styles/main.scss\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nimport Alert from 'bootstrap/js/dist/alert';\n```\n\n```text\nimport { Tooltip, Toast, Popover } from 'bootstrap';\n```\n\n```text\nnpm i --save-dev vite\n```\n\n```text\nnpm i --save bootstrap @popperjs/core\n```\n\n```text\nnpm i --save-dev sass\n```\n\n========================================\n\nComments:\n- Hi, what did you tried so far?\n- Is it possible to just import a single plugin instead of ALL of bootstrap JS plugins? For example, just want to use the Dropdown component.\n- for me all solutions are note working, for CSS ok but for js , nothing happen even if js is present, for example menu toggle collapse\n- With variant 2 I always get \"Document is not defined\"\n- Not sure this works becasue some of the jS components such as the modal and drop down will break on SSR, thus need to set it up as a plugin using the `.client` format extension.\n- While this link may answer the question, you should also include the essential parts into the answer itself. Link-only answers usually get deleted. - From Review\n- sorry, I edit my answer to add new extra info thanks @tdy","metadata":{"transformedAt":"2026-08-18T18:33:46.429Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":131,"estimatedTokens":939}}457{"id":"stack-70516746","source":"stackoverflow","questionId":70516746,"title":"How to use Pug in Nuxt 3.x?","tags":["nuxt.js","pug","vite","nuxt3.js"],"text":"Title: How to use Pug in Nuxt 3.x?\nTags: nuxt.js, pug, vite, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nIf we create the Nuxt 3 application by `npx nuxi init nuxt3-app` and change the content of `app.vue` from\n\n```\n\n \n \n \n\n```\n\nto\n\n```\n\n div\n NuxtWelcome\n\n```\n\nwe'll get\n\n```\nERROR [unhandledRejection] Cannot find module 'pug' 17:05:54\nRequire stack:\n- D:\\IntelliJ IDEA\\Experiments\\nuxt3-app\\node_modules\\@vue\\compiler-sfc\\dist\\compiler-sfc.cjs.js\n- D:\\IntelliJ IDEA\\Experiments\\nuxt3-app\\node_modules\\vue\\compiler-sfc\\index.js\n- D:\\IntelliJ IDEA\\Experiments\\nuxt3-app\\node_modules\\@vitejs\\plugin-vue\\dist\\index.js\n```\n\nI did not expected the build-in Pug support but there is also no hint how to provide.\n\nAFAIK default Nuxt 3 setup use the Vite istead of Webpack. Maybe the answer is in Vite setup overriding?\n\n========================================\n\nTop Answer:\nI know it's been over a year since this question, but I recently had the same question and found an easier solution.\n\nYou can just install `pug` and it will work. No need for any plugins or other extra configs.\n\nJust in case: I am using `Nuxt@3.6.5` and `Pug@3.0.2`\n\nUPD: There is actually a need for a little bit of config. Mainly for IDE support. You should also add `@vue/language-plugin-pug` and extend your `tsconfig.json` with `vueCompilerOptions` like it shown below:\n\n```\n{\n // https://nuxt.com/docs/guide/concepts/typescript\n \"extends\": \"./.nuxt/tsconfig.json\",\n \"vueCompilerOptions\": {\n \"plugins\": [\"@vue/language-plugin-pug\"]\n }\n}\n```\n\n========================================\n\nCode:\n```xml\n<template>\n  <div>\n    <NuxtWelcome />\n  </div>\n</template>\n```\n\n```text\n<template lang=\"pug\">\n\n  div\n    NuxtWelcome\n\n</template>\n```\n\n```text\nERROR  [unhandledRejection] Cannot find module 'pug'                                                                                                                                                                                                      17:05:54\nRequire stack:\n- D:\\IntelliJ IDEA\\Experiments\\nuxt3-app\\node_modules\\@vue\\compiler-sfc\\dist\\compiler-sfc.cjs.js\n- D:\\IntelliJ IDEA\\Experiments\\nuxt3-app\\node_modules\\vue\\compiler-sfc\\index.js\n- D:\\IntelliJ IDEA\\Experiments\\nuxt3-app\\node_modules\\@vitejs\\plugin-vue\\dist\\index.js\n```\n\n```text\nnpx nuxi init nuxt3-app\n```\n\n```text\napp.vue\n```\n\n```json\n{\n  // https://nuxt.com/docs/guide/concepts/typescript\n  \"extends\": \"./.nuxt/tsconfig.json\",\n  \"vueCompilerOptions\": {\n    \"plugins\": [\"@vue/language-plugin-pug\"]\n  }\n}\n```\n\n```text\npug\n```\n\n```text\nNuxt@3.6.5\n```\n\n```text\nPug@3.0.2\n```\n\n```text\n@vue/language-plugin-pug\n```\n\n```text\ntsconfig.json\n```\n\n```text\nvueCompilerOptions\n```\n\n========================================\n\nComments:\n- If you're taking the Pug path, be careful of a lot of bugs actually because when you add a middleware between your HTML and your code, you will have some issues at some point.\n- Also, please accept this answer.\n- @kissu Thank you for the comment! I will accept this answer once Stack Overflow will permit it (own answers could be accepted in 3 days).\n- you can include this in `eslintrc` to IDE support `{ \"extends\": [ \"@nuxt&#47;eslint-config\", \"plugin:prettier&#47;recommended\", \"plugin:vue-pug&#47;vue3-recommended\" ] }`","metadata":{"transformedAt":"2026-08-18T18:33:46.429Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":136,"estimatedTokens":809}}458{"id":"stack-72889805","source":"stackoverflow","questionId":72889805,"title":"Yarn 3.1, Vite 2.9, cannot find package vite","tags":["javascript","node.js","vite","yarnpkg-v2"],"text":"Title: Yarn 3.1, Vite 2.9, cannot find package vite\nTags: javascript, node.js, vite, yarnpkg-v2\nSource: Stack Overflow\n\nQuestion:\nWhen trying to build the app with Vite I'm seeing an error. If I understand it correctly there seems to be an issue with Yarn PnP resolving dependencies (no more `node_modules`), and Vite does not seem to pick up on this? How can I make Vite understand that `node_modules` no longer exist?\n\n**Update:** Reproduced test case here: https://github.com/michaeljohansen/vite-test-case - Error seems to go away if removing `\"type\": \"module\"` from `package.json`, but that makes no sense to me yet, and creates other problems for my Node backend.\n\n```\n$ yarn run vite --config vite.config.js\nError [ERR_MODULE_NOT_FOUND]: Cannot find package 'vite' imported from /Users/me/project/vite.config.js\nDid you mean to import vite-virtual-ec56a6c02a/0/cache/vite-npm-2.9.13-cda1bb45b9-a5e501b920.zip/node_modules/vite/dist/node/index.js?\n at new NodeError (node:internal/errors:377:5)\n at packageResolve (node:internal/modules/esm/resolve:910:9)\n ...\n```\n\n```\n// vite.config.js excerpt\nimport { defineConfig } from 'vite';\n\nexport default defineConfig(({ command, mode }) => {\n ...\n});\n```\n\n========================================\n\nCode:\n```text\n$ yarn run vite --config vite.config.js\nError [ERR_MODULE_NOT_FOUND]: Cannot find package 'vite' imported from /Users/me/project/vite.config.js\nDid you mean to import vite-virtual-ec56a6c02a/0/cache/vite-npm-2.9.13-cda1bb45b9-a5e501b920.zip/node_modules/vite/dist/node/index.js?\n    at new NodeError (node:internal/errors:377:5)\n    at packageResolve (node:internal/modules/esm/resolve:910:9)\n    ...\n```\n\n```js\n// vite.config.js excerpt\nimport { defineConfig } from 'vite';\n\nexport default defineConfig(({ command, mode }) => {\n  ...\n});\n```\n\n```text\nnode_modules\n```\n\n```text\nnode_modules\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\npackage.json\n```\n\n```bash\nyarn set version stable \n# or \nyarn set version 3.2.0\n```\n\n```text\nyarn install\n```\n\n```text\n.pnp.cjs\n```\n\n========================================\n\nComments:\n- I cannot reproduce the issue. Can you a link to a reproduction of the problem?\n- Absolutely, here you go: github.com/michaeljohansen/vite-test-case - Also, the error seems to go away if removing `\"type\": \"module\"` from `package.json`, but that makes no sense to me yet.\n- If I set yarn to 3.1.1, I get a different error related to `pnp.cjs`. On the other hand, setting yarn to the latest berry version (3.2.1), no errors occur at all. Is there a reason you're still on 3.1?\n- The same thing happened with Yarn v3.2.1 unfortunately.\n- What's your environment? Mine: macOS Big Sur, Node 17.4.0\n- macOS Monterey, M1 processor, Node 18.5.0, Yarn 3.2.1, Vite 2.9.13.\n- That repo works just for me with Node 18.3 and 18.5. Fails on 18.6. Can you include your .pnp.cjs and .yarnrc.yml in there?\n- It turns out that I needed to upgrade Yarn to 3.2.1, but I had forgotten to update the `packageManager` field in `package.json` with Yarn 3.2.1. Bounty awarded to answer that told me to upgrade Yarn version. Also, pushed .pnp.cjs now @AntonMihaylov, I don't have a .yarnrc.yml for this repo yet.\n- Unfortunately still doesn't work. It only starts working if I remove `\"type\": \"module\"` from `package.json`, but that creates problems for my Node backend so not really an option. I had to stop using Yarn PnP and go back to using `nodeLinker: node-modules` in my `.yarnrc.yml`. Node 18.5.0, Yarn 3.2.1, Vite 2.9.13.\n- Update: Seems it works when I also changed the version of Yarn in `package.json`, so with that your answer seems to be correct. Awarding the bounty now. Thanks!\n- what did you change the version to? this does not work for me...\n- It doesn't work for me either.","metadata":{"transformedAt":"2026-08-18T18:33:46.429Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":93,"estimatedTokens":938}}459{"id":"stack-77666915","source":"stackoverflow","questionId":77666915,"title":"How to run a Vite React app from a subfolder","tags":["reactjs","typescript","react-router","react-router-dom","vite"],"text":"Title: How to run a Vite React app from a subfolder\nTags: reactjs, typescript, react-router, react-router-dom, vite\nSource: Stack Overflow\n\nQuestion:\nI use Vite to create a React app.\n\nRoutes.tsx\n\n```\nimport { RouteObject, createBrowserRouter } from \"react-router-dom\";\nimport App from \"../layout/App\";\nimport HomePage from \"../../feautures/home/HomePage\";\nimport CreateRegistration from \"../../feautures/createRegistration/createRegistration\";\n\nexport const routes: RouteObject[] = [\n {\n path: '/',\n element: ,\n children: [\n { path: '', element: },\n { path: 'createRegistrationForm', element: }\n ]\n }\n];\n\nexport const router = createBrowserRouter(routes);\n```\n\nIn my vite.config.ts I have\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n //base: '/registration/',\n server:{\n port: 3000\n },\n plugins: [react()],\n})\n```\n\nand everything works great at `\"http://127.0.0.1:3000/\"` but the moment in my `vite.config.ts` when I uncomment `base: '/registration/',` and go to `\"http://127.0.0.1:3000/registration/\"` I get all 404 errors for all routes. I'm not sure what I am missing to run a React app using Vite in a subfolder.\n\n========================================\n\nCode:\n```text\nimport { RouteObject, createBrowserRouter } from \"react-router-dom\";\nimport App from \"../layout/App\";\nimport HomePage from \"../../feautures/home/HomePage\";\nimport CreateRegistration from \"../../feautures/createRegistration/createRegistration\";\n\nexport const routes: RouteObject[] = [\n    {\n        path: '/',\n        element: <App />,\n        children: [\n            { path: '', element: <HomePage /> },\n            { path: 'createRegistrationForm', element: <CreateRegistration /> }\n        ]\n    }\n];\n\nexport const router = createBrowserRouter(routes);\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  //base: '/registration/',\n  server:{\n    port: 3000\n  },\n  plugins: [react()],\n})\n```\n\n```text\n\"http://127.0.0.1:3000/\"\n```\n\n```text\nvite.config.ts\n```\n\n```text\nbase: '/registration/',\n```\n\n```text\n\"http://127.0.0.1:3000/registration/\"\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react-swc';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  base: '/registration/',\n  server:{\n    port: 3000\n  },\n  plugins: [react()],\n});\n```\n\n```text\nexport const routes: RouteObject[] = [\n  {\n    path: '/',\n    element: <App />,\n    children: [\n      { index: true, element: <HomePage /> },\n      { path: 'createRegistrationForm', element: <CreateRegistration /> }\n    ]\n  }\n];\n\nexport const router = createBrowserRouter(routes, {\n  basename: \"/registration/\",\n});\n```\n\n```text\nbasename\n```\n\n```text\nBrowserRouter\n```\n\n```text\nbasename\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.429Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":142,"estimatedTokens":718}}460{"id":"stack-73549633","source":"stackoverflow","questionId":73549633,"title":"Vite+SvelteKit Build Failing","tags":["svelte","vite","sveltekit"],"text":"Title: Vite+SvelteKit Build Failing\nTags: svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm building a website using `SvelteKit`, scaffolded using `pnpm create svelte`. However, when I run `pnpm build`, I get the following error:\n\n```\nvite v3.0.9 building for production...\n✓ 77 modules transformed.\n.svelte-kit/output/client/vite-manifest.json 2.96 KiB\n[vite-plugin-svelte-kit] Error running plugin hook writeBundle for vite-plugin-svelte-kit, expected a function hook.\nerror during build:\nError: Error running plugin hook closeBundle for vite-plugin-svelte-kit, expected a function hook.\n at error (file:///home/leo/code/keo-website/node_modules/.pnpm/rollup@2.77.3/node_modules/rollup/dist/es/shared/rollup.js:1858:30)\n at throwInvalidHookError (file:///home/leo/code/keo-website/node_modules/.pnpm/rollup@2.77.3/node_modules/rollup/dist/es/shared/rollup.js:22551:12)\n at file:///home/leo/code/keo-website/node_modules/.pnpm/rollup@2.77.3/node_modules/rollup/dist/es/shared/rollup.js:22692:24\n at async Promise.all (index 0)\n at async Object.close (file:///home/leo/code/keo-website/node_modules/.pnpm/rollup@2.77.3/node_modules/rollup/dist/es/shared/rollup.js:23662:13)\n at async Promise.all (index 0)\n at async build (file:///home/leo/code/keo-website/node_modules/.pnpm/vite@3.0.9_sass@1.54.7/node_modules/vite/dist/node/chunks/dep-0fc8e132.js:43473:13)\n at async CAC. (file:///home/leo/code/keo-website/node_modules/.pnpm/vite@3.0.9_sass@1.54.7/node_modules/vite/dist/node/cli.js:747:9)\n ELIFECYCLE  Command failed with exit code 1.\n```\n\nHere is my `svelte.config.js`:\n\n```\nimport adapter from \"@sveltejs/adapter-static\";\nimport preprocess from \"svelte-preprocess\";\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: preprocess({\n scss: { includePaths: [\"./src/styles\"] },\n }),\n\n kit: {\n adapter: adapter({\n pages: \"build\",\n assets: \"build\",\n }),\n },\n};\n\nexport default config;\n```\n\nMost things that I've done here are what I've done in the past. The only difference is that I have a `export const prerender = true;` in `src/routes/+layout.svelte` since it appears that they overhauled their route system.\n\n========================================\n\nCode:\n```text\nvite v3.0.9 building for production...\n✓ 77 modules transformed.\n.svelte-kit/output/client/vite-manifest.json                                           2.96 KiB\n[vite-plugin-svelte-kit] Error running plugin hook writeBundle for vite-plugin-svelte-kit, expected a function hook.\nerror during build:\nError: Error running plugin hook closeBundle for vite-plugin-svelte-kit, expected a function hook.\n    at error (file:///home/leo/code/keo-website/node_modules/.pnpm/rollup@2.77.3/node_modules/rollup/dist/es/shared/rollup.js:1858:30)\n    at throwInvalidHookError (file:///home/leo/code/keo-website/node_modules/.pnpm/rollup@2.77.3/node_modules/rollup/dist/es/shared/rollup.js:22551:12)\n    at file:///home/leo/code/keo-website/node_modules/.pnpm/rollup@2.77.3/node_modules/rollup/dist/es/shared/rollup.js:22692:24\n    at async Promise.all (index 0)\n    at async Object.close (file:///home/leo/code/keo-website/node_modules/.pnpm/rollup@2.77.3/node_modules/rollup/dist/es/shared/rollup.js:23662:13)\n    at async Promise.all (index 0)\n    at async build (file:///home/leo/code/keo-website/node_modules/.pnpm/vite@3.0.9_sass@1.54.7/node_modules/vite/dist/node/chunks/dep-0fc8e132.js:43473:13)\n    at async CAC.<anonymous> (file:///home/leo/code/keo-website/node_modules/.pnpm/vite@3.0.9_sass@1.54.7/node_modules/vite/dist/node/cli.js:747:9)\n ELIFECYCLE  Command failed with exit code 1.\n```\n\n```js\nimport adapter from \"@sveltejs/adapter-static\";\nimport preprocess from \"svelte-preprocess\";\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n  // Consult https://github.com/sveltejs/svelte-preprocess\n  // for more information about preprocessors\n  preprocess: preprocess({\n    scss: { includePaths: [\"./src/styles\"] },\n  }),\n\n  kit: {\n    adapter: adapter({\n      pages: \"build\",\n      assets: \"build\",\n    }),\n  },\n};\n\nexport default config;\n```\n\n```text\nSvelteKit\n```\n\n```text\npnpm create svelte\n```\n\n```text\npnpm build\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nexport const prerender = true;\n```\n\n```text\nsrc/routes/+layout.svelte\n```\n\n```json\n{\n ...\n \"devDependencies\": {\n  ...\n  \"vite\": \"^3.1.0-beta.1\"\n }\n}\n```\n\n```text\nnpm update\n```\n\n```text\nimport.meta.glob\n```\n\n```text\nwriteBundle\n```\n\n```text\npackage.json\n```\n\n```text\nnpm update\n```\n\n========================================\n\nComments:\n- It looks like a bug on their part. SvelteKit is going through heavy refactor so turbulence is kinda expected. Try revert to earlier version.","metadata":{"transformedAt":"2026-08-18T18:33:46.429Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":154,"estimatedTokens":1191}}461{"id":"stack-69088889","source":"stackoverflow","questionId":69088889,"title":"Vue3: how to avoid Vitejs to erase/replace all DOM content when mounting the app?","tags":["javascript","vue.js","vuejs3","vite"],"text":"Title: Vue3: how to avoid Vitejs to erase/replace all DOM content when mounting the app?\nTags: javascript, vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI come from Vue 2 and I was used to have my wordpress standard html pages and use some Vue components inside them. Just passed the container to the main app `el` property, and then I could use components on the container, where I wanted to, without having all the default container's content be erased or replaced. Basically, passing a dom element to the `el` property, maked that element a Vue app, with all its contents (even without any Vue components).\n\nWith Vue 3 and createApp, it seems there's no way of doing it, since as soon as I mount the app to a container (say #app), then all the container's contents are erased or replaced with component's template (if a component is passed). Even the following, which doesn't use any component, is going to clear all the #app original contents:\n\n```\nimport { createApp } from 'vue'\n\ncreateApp({\n\n}).mount('#app');\n```\n\nHow to avoid? How to just use some spare components on a free html page? And how about SFC used the same way?\n\n========================================\n\nCode:\n```text\nimport { createApp } from 'vue'\n\ncreateApp({\n\n}).mount('#app');\n```\n\n```text\nel\n```\n\n```text\nel\n```\n\n```js\nconst app = Vue.createApp({\n}).mount(\"#app\")\n```\n\n```html\n<script src=\"https://unpkg.com/vue@3.2.9/dist/vue.global.js\"></script>\n<div id='app'>\n  <div>\n    <h2>Hello from HTML!</h2>\n  </div>\n</div>\n```\n\n```text\ntemplate\n```\n\n```text\nrender\n```\n\n========================================\n\nComments:\n- You need to be more specific than that, Vue 3 still supports in DOM templates\n- Thank you, I edited my question. Basically, what is changed is that with Vue2's `el` property, you could pass an existing piece of html page and get it as a Vue app. This is not the case anymore. It seems there's no way to retain existing markup.\n- Mmm I'm using Vitejs: could it be the issue?\n- @LucaReghellin Check this","metadata":{"transformedAt":"2026-08-18T18:33:46.429Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":67,"estimatedTokens":502}}462{"id":"stack-75938410","source":"stackoverflow","questionId":75938410,"title":"How to get Jest working with Vite - Support for the experimental syntax 'jsx' isn't currently enabled","tags":["vite"],"text":"Title: How to get Jest working with Vite - Support for the experimental syntax 'jsx' isn't currently enabled\nTags: vite\nSource: Stack Overflow\n\nQuestion:\nI've added the various dependencies as shown below here but I am still getting the message\n\n```\nSupport for the experimental syntax 'jsx' isn't currently enabled (8:12):\n```\n\nNote this is for a brand new Vite project to see how to get jest working with react in a vite project. I have not added any specific application code yet so whatever the issue and solution is, it should apply to many others as a template\n\nHere are my dependencies:\n\n```\n\"dependencies\": {\n \"jest\": \"^29.5.0\",\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\"\n },\n \"devDependencies\": {\n \"@testing-library/jest-dom\": \"^4.2.4\",\n \"@testing-library/react\": \"^14.0.0\",\n \"@testing-library/user-event\": \"^14.4.3\",\n \"@types/jest\": \"^29.5.0\",\n \"@types/react\": \"^18.0.28\",\n \"@types/react-dom\": \"^18.0.11\",\n \"@vitejs/plugin-react-swc\": \"^3.0.0\",\n \"jest-dom\": \"^4.0.0\",\n \"react-testing-library\": \"^8.0.1\",\n \"typescript\": \"^4.9.3\",\n \"vite\": \"^4.2.0\"\n }\n SyntaxError: /home/durrantm/Dropnot/vite/thedeiscorecard-vite/src/App.test.tsx:\n Support for the experimental syntax 'jsx' isn't currently enabled (8:12):\n \n 6 | describe('Main app test', () => { \n 7 | it('renders the App', () => { \n > 8 | render(); \n | ^ \n 9 | const title = screen.getByText(/Vite \\+ React/i); \n 10 | expect(title).toBeInTheDocument(); \n 11 | }); \n \n Add @babel/preset-react (https://github.com/babel/babel/tree/main/packages/babel-preset-react) to\n the 'presets' section of your Babel config to enable transformation.\n If you want to leave it as-is, add @babel/plugin-syntax-jsx\n (https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-jsx)\n to the 'plugins' section to enable parsing.\n```\n\nThe problem seems to be the ability of Vite to use ESM but Jest is still in commonJS world.\n\nThere is a solution to this which is to use the experimental feature for ESM in jest as detailed at https://jestjs.io/docs/ecmascript-modules\n\nHowever, even though I followed the advice given there I am still getting the error about \"'jsx' isn't current enabled\"\n\nI followed the advice to add a babel.config.json (even though esm doesn't use bable), so I added a `babel.config.json` file. Unfortunately this gave me\n\n```\nSyntaxError: Cannot use import statement outside a module\n```\n\nso this is not the correct solution and I am stuck\n\n========================================\n\nTop Answer:\ninstall ts-jest & put this in your jest config file.\n\n```\n\"transform\": {\n \"^.+\\\\.(ts|tsx|js|jsx)$\": \"ts-jest\"\n },\n```\n\nBabel throwing Support for the experimental syntax 'jsx' isn't currently enabled\n\n========================================\n\nCode:\n```text\nSupport for the experimental syntax 'jsx' isn't currently enabled (8:12):\n```\n\n```text\n\"dependencies\": {\n    \"jest\": \"^29.5.0\",\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\"\n  },\n  \"devDependencies\": {\n    \"@testing-library/jest-dom\": \"^4.2.4\",\n    \"@testing-library/react\": \"^14.0.0\",\n    \"@testing-library/user-event\": \"^14.4.3\",\n    \"@types/jest\": \"^29.5.0\",\n    \"@types/react\": \"^18.0.28\",\n    \"@types/react-dom\": \"^18.0.11\",\n    \"@vitejs/plugin-react-swc\": \"^3.0.0\",\n    \"jest-dom\": \"^4.0.0\",\n    \"react-testing-library\": \"^8.0.1\",\n    \"typescript\": \"^4.9.3\",\n    \"vite\": \"^4.2.0\"\n  }\n SyntaxError: /home/durrantm/Dropnot/vite/thedeiscorecard-vite/src/App.test.tsx:\n Support for the experimental syntax 'jsx' isn't currently enabled (8:12):\n                                                                                                                                                                        \n       6 | describe('Main app test', () => {                                                                                                                            \n       7 |   it('renders the App', () => {                                                                                                                              \n    >  8 |     render(<App />);                                                                                                                                         \n         |            ^                                                                                                                                                 \n       9 |     const title = screen.getByText(/Vite \\+ React/i);                                                                                                        \n      10 |     expect(title).toBeInTheDocument();                                                                                                                       \n      11 |   });                                                                                                                                                        \n                                                                                                                                                                        \n    Add @babel/preset-react (https://github.com/babel/babel/tree/main/packages/babel-preset-react) to\n    the 'presets' section of your Babel config to enable transformation.\n    If you want to leave it as-is, add @babel/plugin-syntax-jsx\n    (https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-jsx)\n    to the 'plugins' section to enable parsing.\n```\n\n```text\nSyntaxError: Cannot use import statement outside a module\n```\n\n```text\nbabel.config.json\n```\n\n```json\n\"transform\": {\n       \"^.+\\\\.(ts|tsx|js|jsx)$\": \"ts-jest\"\n    },\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.429Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":136,"estimatedTokens":1388}}463{"id":"stack-72264173","source":"stackoverflow","questionId":72264173,"title":"TS Config nested alias for absolute path not working","tags":["reactjs","typescript","vite"],"text":"Title: TS Config nested alias for absolute path not working\nTags: reactjs, typescript, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to set up path aliases in my `tsconfig.json` for a React app bundled with Vite. Here is the relevant part of my `tsconfig.json`:\n\n```\n{\n \"compilerOptions\": {\n \"baseUrl\": \".\",\n ...\n \"paths\": {\n \"*\": [\"src/*\", \"node_modules/*\"],\n \"components/*\": [\"src/components/*\"],\n \"containers/*\": [\"src/containers/*\"],\n \"pages/*\": [\"src/constants/*\"],\n \"store/*\": [\"src/store/*\"],\n \"types/*\": [\"src/types/*\"],\n \"NestedFolder/*\": [\n \"src/components/NestedFolder/*\"\n ],\n }\n },\n \"include\": [\"src/**/*\", \"*\"]\n}\n```\n\nThe only issue is with the `NestedFolder`. When I import this way, everything works:\n\n```\nimport { ComponentName } from \"components/NestedFolder/types\";\n```\n\nHowever, the nested alias fails:\n\n```\nimport { ComponentName } from \"NestedFolder/types\";\n\n// error \nEslintPluginImportResolveError: typescript with invalid interface loaded as resolver\nOccurred while linting .../src/components/NestedFolder/canvas/index.ts:1\nRule: \"import/namespace\"\n\n// error on hover in VS Code\nUnable to resolve path to module 'NestedFolder/types'.eslintimport/no-unresolved\n```\n\nI would like to do nested components because I have several folders that are nested 3-4 levels and it would be nice to have a cleaner view of my imports. Is there a way to do this?\n\n========================================\n\nTop Answer:\nThe accepted answer did not work for me. I found that I had to install the following packages:\n\n`npm i eslint-plugin-import eslint-import-resolver-alias eslint-import-resolver-typescript`\n\nAnd then add the following configurations, with the important ingredient being strongly-defined alias paths:\n\n```\nconst path = require('path');\n\nmodule.exports = {\n root: true, // important to ensure nested eslint scoping in monorepos\n plugins: ['@typescript-eslint', 'import'],\n extends: [\n 'airbnb-typescript-prettier',\n 'plugin:import/typescript'\n ],\n parser: '@typescript-eslint/parser',\n parserOptions: {\n project: path.join(__dirname, './tsconfig.json'),\n tsconfigRootDir: './src',\n },\n settings: {\n \"import/parsers\": { // add this definition\n \"@typescript-eslint/parser\": [\".ts\", \".tsx\"],\n },\n 'import/resolver': {\n alias: {\n map: [\n // define each alias here\n ['components', path.join(__dirname, './src/components')],\n ],\n extensions: ['.ts', '.tsx', '.js', '.jsx', '.json']\n },\n typescript: {\n project: path.join(__dirname, './tsconfig.json'),\n },\n },\n },\n}\n```\n\nI think this could be improved on by harmonizing the aliases between the .eslintrc and vite.config so aliases only need to be defined once, using a tactic like the one defined here: https://stackoverflow.com/a/68908814/14198287\n\n========================================\n\nCode:\n```json\n{\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    ...\n    \"paths\": {\n      \"*\": [\"src/*\", \"node_modules/*\"],\n      \"components/*\": [\"src/components/*\"],\n      \"containers/*\": [\"src/containers/*\"],\n      \"pages/*\": [\"src/constants/*\"],\n      \"store/*\": [\"src/store/*\"],\n      \"types/*\": [\"src/types/*\"],\n      \"NestedFolder/*\": [\n        \"src/components/NestedFolder/*\"\n      ],\n    }\n  },\n  \"include\": [\"src/**/*\", \"*\"]\n}\n```\n\n```js\nimport { ComponentName } from \"components/NestedFolder/types\";\n```\n\n```js\nimport { ComponentName } from \"NestedFolder/types\";\n\n// error \nEslintPluginImportResolveError: typescript with invalid interface loaded as resolver\nOccurred while linting .../src/components/NestedFolder/canvas/index.ts:1\nRule: \"import/namespace\"\n\n// error on hover in VS Code\nUnable to resolve path to module 'NestedFolder/types'.eslintimport/no-unresolved\n```\n\n```text\ntsconfig.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\nNestedFolder\n```\n\n```text\nCtrl+Shift+P\n```\n\n```text\nCmd+Shift+P\n```\n\n```text\nrestart\n```\n\n```text\nTypeScript: Restart TS server\n```\n\n```text\nconst path = require('path');\n\nmodule.exports = {\n  root: true, // important to ensure nested eslint scoping in monorepos\n  plugins: ['@typescript-eslint', 'import'],\n  extends: [\n    'airbnb-typescript-prettier',\n    'plugin:import/typescript'\n  ],\n  parser: '@typescript-eslint/parser',\n  parserOptions: {\n    project: path.join(__dirname, './tsconfig.json'),\n    tsconfigRootDir: './src',\n  },\n  settings: {\n    \"import/parsers\": { // add this definition\n      \"@typescript-eslint/parser\": [\".ts\", \".tsx\"],\n    },\n    'import/resolver': {\n      alias: {\n        map: [\n          // define each alias here\n          ['components', path.join(__dirname, './src/components')],\n        ],\n        extensions: ['.ts', '.tsx', '.js', '.jsx', '.json']\n      },\n      typescript: {\n        project: path.join(__dirname, './tsconfig.json'),\n      },\n    },\n  },\n}\n```\n\n```text\nnpm i eslint-plugin-import eslint-import-resolver-alias eslint-import-resolver-typescript\n```\n\n```bash\nnpm install vite-tsconfig-paths@latest\n```\n\n```text\nv4.0.0\n```\n\n```text\nv4.0.1\n```\n\n```text\nv4.0.1\n```\n\n========================================\n\nComments:\n- I assume you have tried restarting your TS server if you are using VSCode. I recommend using vite-tsconfig-paths plugin and see if this works\n- I restarted my server, VS Code, and ran the build command, and the build breaks as is. Thanks, I'll look into the plugin. I was hoping to avoid adding additional libraries/plugins, but that may be my only choice now.\n- Update: the plugin did solve my issue, thank you!\n- No problem! I will make my comment an answer so it's more clear for others that may need to find this plugin\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:46.429Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":227,"estimatedTokens":1445}}464{"id":"stack-71400046","source":"stackoverflow","questionId":71400046,"title":"Why is the favicon only shown in the root page?","tags":["reactjs","favicon","vite"],"text":"Title: Why is the favicon only shown in the root page?\nTags: reactjs, favicon, vite\nSource: Stack Overflow\n\nQuestion:\nI have a react app and a favicon icon in the folder src. It is only shown for the root path, the other pages cannot find it. In the developer tools, it show a wrong path for a subpage, it tries to get the favicon from http://localhost:3000/faq/src/favicon.ico\n\nindex.html\n\n```\n\n```\n\nit works for http://localhost:3000/ but not for\n\n```\nhttp://localhost:3000/faq\n```\n\n========================================\n\nCode:\n```text\n<link rel=\"icon\" type=\"image/svg+xml\" href=\"src/favicon.ico\">\n```\n\n```text\nhttp://localhost:3000/faq\n```\n\n```text\n|\n `--- public\n     |\n      `--- favicon.ico\n```\n\n```html\n<link rel=\"icon\" href=\"/favicon.ico\" />\n```\n\n```html\n<link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n```\n\n```text\nfavicon\n```\n\n```text\nindex.html\n```\n\n========================================\n\nComments:\n- try `href=\"favicon.ico\"` and put the favicon file in the `public` folder\n- Can you tell why favicon should be put inside the public directory. As it is not loading when put in the src folder.\n- @Neeraj-Kumar-Coder It should be placed in the public directory (root directory), but there is no obligation to prevent you from putting it elsewhere. This answer approximately describes the reason.","metadata":{"transformedAt":"2026-08-18T18:33:46.429Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":59,"estimatedTokens":329}}465{"id":"stack-74038347","source":"stackoverflow","questionId":74038347,"title":"How to add Flowbite Tailwind plugin to my Laravel 9 + Vite project?","tags":["vuejs3","tailwind-css","vite","laravel-9","flowbite"],"text":"Title: How to add Flowbite Tailwind plugin to my Laravel 9 + Vite project?\nTags: vuejs3, tailwind-css, vite, laravel-9, flowbite\nSource: Stack Overflow\n\nQuestion:\nI tried adding flowbite to my Laravel project. I am using Laravel version 9 with Vite.\n\nSo far, I did the following steps:\n\n- Installed `flowbite` as a dependency:\n\n```\nnpm i flowbite\n```\n\n- Added plugin in `tailwind.config.js`:\n\n```\nplugins: [\n require('@tailwindcss/forms'),\n require('@tailwindcss/typography'),\n require('flowbite/plugin')\n],\n```\n\n- I imported it in `App.js`:\n\n```\nimport Flowbite from 'flowbite';\n\n4. Then I ran the app:\n```shell\nnpm run dev\n```\n\nI also tried adding it using CDN links, but it's not working.\n\nCould someone please tell me what I am doing wrong? Or maybe you can suggest me a better library to use with Tailwind CSS, as Tailwind doesn't provide js components like tooltip, dropdown, etc.\n\n```\ncreateInertiaApp({\n title: (title) => `${title} - ${appName}`,\n resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),\n setup({ el, app, props, plugin }) {\n return createApp({ render: () => h(app, props) })\n .use(plugin)\n .use(ZiggyVue, Ziggy)\n .mixin({ components: { FilePond } })\n .mount(el);\n },\n});\n```\n\n========================================\n\nTop Answer:\nFor me worked to add this line of code in to the app.js\n\n```\nimport 'flowbite';\n```\n\n========================================\n\nCode:\n```bash\nnpm i flowbite\n```\n\n```js\nplugins: [\n  require('@tailwindcss/forms'),\n  require('@tailwindcss/typography'),\n  require('flowbite/plugin')\n],\n```\n\n```js\nimport Flowbite from 'flowbite';\n\n\n4. Then I ran the app:\n```shell\nnpm run dev\n```\n\n```text\ncreateInertiaApp({\n    title: (title) => `${title} - ${appName}`,\n    resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),\n    setup({ el, app, props, plugin }) {\n        return createApp({ render: () => h(app, props) })\n            .use(plugin)\n            .use(ZiggyVue, Ziggy)\n            .mixin({ components: { FilePond } })\n            .mount(el);\n    },\n});\n```\n\n```text\nflowbite\n```\n\n```text\ntailwind.config.js\n```\n\n```text\nApp.js\n```\n\n```js\nimport { initFlowbite } from 'flowbite';\n    \nonMounted(() => {\n  initFlowbite();\n});\n```\n\n```text\nApp.vue\n```\n\n```text\ninitFlowbite\n```\n\n```text\n'flowbite'\n```\n\n```text\nonMounted\n```\n\n```text\nApp.vue\n```\n\n```html\n<link href=\"{{ url('css/flowbite.min.css') }}\" rel=\"stylesheet\" />\n<script src=\"{{ url('js/flowbite.js') }}\" type=\"text/javascript\"></script>\n```\n\n```js\nimport \"../../path/to/node_modules/flowbite/dist/flowbite\"; // @see https://flowbite.com/docs/getting-started/laravel/\n```\n\n```php\n<script src=\"{{ \\Illuminate\\Support\\Facades\\Vite::asset('resources/js/app.js') }}\"></script>\n```\n\n```text\nimport 'flowbite';\n```\n\n========================================\n\nComments:\n- Keep your question properly formatted rather than rollback'ing it to a previous state, your question is self-answered anyway so I don't really see the benefit of making the question look worse.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:46.429Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":162,"estimatedTokens":835}}466{"id":"stack-73244322","source":"stackoverflow","questionId":73244322,"title":"How to specify what will be the export build js and css filenames in svelte","tags":["svelte","vite"],"text":"Title: How to specify what will be the export build js and css filenames in svelte\nTags: svelte, vite\nSource: Stack Overflow\n\nQuestion:\nI am using vite for svelte, I have attached vite.config.js below, I tried looking for references on the web but couldn't find any\n\n```\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n server: {\n port: 4000\n },\n preview: {\n port: 4000\n },\n plugins: [\n svelte({\n compilerOptions: {\n customElement: true,\n }\n }),\n ]})\n```\n\nhttps://i.sstatic.net/oH28m.png\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  server: {\n    port: 4000\n  },\n  preview: {\n    port: 4000\n  },\n  plugins: [\n    svelte({\n      compilerOptions: {\n        customElement: true,\n      }\n    }),\n  ]})\n```\n\n```js\nexport default defineConfig({\n    build: {\n        rollupOptions: {\n            output: {\n                entryFileNames: '[name].js',\n                assetFileNames: '[name].[ext]',\n            },\n        },\n    },\n    plugins: [\n        svelte(),\n    ],\n});\n```\n\n```text\nbuild > rollupOptions\n```\n\n```text\nbuild.manifest\n```\n\n```text\n<script src=\"...\">\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.429Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":81,"estimatedTokens":334}}467{"id":"stack-74341025","source":"stackoverflow","questionId":74341025,"title":"Type unknown[] is not assignable to type React.ReactNode","tags":["javascript","reactjs","jsx","vite"],"text":"Title: Type unknown[] is not assignable to type React.ReactNode\nTags: javascript, reactjs, jsx, vite\nSource: Stack Overflow\n\nQuestion:\n```\nimport * as React from 'react';\nimport { List, ListItemButton, ListItemIcon, ListItemText, ListItem} from '@mui/material';\nimport LightbulbOutlinedIcon from '@mui/icons-material/LightbulbOutlined';\nimport NotificationsNoneOutlinedIcon from '@mui/icons-material/NotificationsNoneOutlined';\nimport DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';\n\nconst mainListItems = () => {\n const navList = [\n { id: 1, name: 'Notes', icon: },\n { id: 2, name: 'Reminders', icon: },\n { id: 3, name: 'Bin', icon: },\n ]\n\n return (\n \n {\n navList.map( list => (\n \n \n \n {list.icon}\n \n \n \n \n ))\n }\n \n )\n}\n```\n\nI tried reducing the amount of code by using map to assign icon information. But it shows this error and I can't understand why it happens. Should I assign types to the attributes in the list?\n\nline where error occurs :\n\n```\nnavList.map( list => (\n```\n\nFull error message :\n\nType unknown[] is not assignable to type React.ReactNode ...   Type\nunknown[] is not assignable to type ReactElement | string | number | Iterable |\nReactPortal | boolean     Type unknown[] is not assignable to type\nboolean\n\n========================================\n\nTop Answer:\nThis code runs fine given that there's no problems with any of the imports. The only thing wrong here is that `mainListItems`should be `MainListItems` as all React components should have names starting with uppercase letters.\n\n========================================\n\nCode:\n```text\nimport * as React from 'react';\nimport { List, ListItemButton, ListItemIcon, ListItemText, ListItem} from '@mui/material';\nimport LightbulbOutlinedIcon from '@mui/icons-material/LightbulbOutlined';\nimport NotificationsNoneOutlinedIcon from '@mui/icons-material/NotificationsNoneOutlined';\nimport DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';\n\n\nconst mainListItems = () => {\n    const navList = [\n        { id: 1, name: 'Notes', icon: <LightbulbOutlinedIcon />},\n        { id: 2, name: 'Reminders', icon:  <NotificationsNoneOutlinedIcon /> },\n        { id: 3, name: 'Bin', icon: <DeleteOutlinedIcon /> },\n    ]\n\n    return (\n            <List>\n                {\n                    navList.map( list => (\n                        <ListItem key={list.id} disablePadding sx={{display: 'block'}}>\n                            <ListItemButton sx={{minHeight: 48, justifyContent: open ? 'initial' : 'center', px: 2.5}}>\n                                <ListItemIcon sx={{minWidth: 0, mr: open ? 3 : 'auto', justifyContent: 'center'}}>\n                                    {list.icon}\n                                </ListItemIcon>\n                                <ListItemText primary={list.name} sx={{opacity: open ? 1 : 0}}/>\n                            </ListItemButton>\n                        </ListItem>\n                    ))\n                }\n            </List>\n    )\n}\n```\n\n```text\nnavList.map( list => (\n```\n\n```js\ntype NavItem = {\n  id: number;\n  name: string;\n  icon: JSX.Element;\n};\nconst MainListItems = () => {\n  const navList: NavItem[] = [\n    { id: 1, name: \"Notes\", icon: <LightbulbOutlinedIcon /> },\n    { id: 2, name: \"Reminders\", icon: <NotificationsNoneOutlinedIcon /> },\n    { id: 3, name: \"Bin\", icon: <DeleteOutlinedIcon /> }\n  ];\n\n  return (\n    <List>\n      {navList.map((list) => (\n        <ListItem key={list.id} disablePadding sx={{ display: \"block\" }}>\n          <ListItemButton\n            sx={{\n              minHeight: 48,\n              justifyContent: open ? \"initial\" : \"center\",\n              px: 2.5\n            }}\n          >\n            <ListItemIcon\n              sx={{\n                minWidth: 0,\n                mr: open ? 3 : \"auto\",\n                justifyContent: \"center\"\n              }}\n            >\n              {list.icon}\n            </ListItemIcon>\n            <ListItemText primary={list.name} sx={{ opacity: open ? 1 : 0 }} />\n          </ListItemButton>\n        </ListItem>\n      ))}\n    </List>\n  );\n};\n```\n\n```text\nconst navList: NavItem[]\n```\n\n```text\n<div>\n```\n\n```text\n<section>\n```\n\n```text\n<mainListItems>\n```\n\n```text\n<MainListItems/>\n```\n\n```text\n<Components/>\n```\n\n```text\nmainListItems\n```\n\n```text\nMainListItems\n```\n\n```text\nnavList.map((list): React.ReactNode => (\n  // ...\n))\n```\n\n```text\nmap()\n```\n\n```text\nunknown\n```\n\n```text\nmap()\n```\n\n```text\nReactNode[]\n```\n\n```text\nmap()\n```\n\n```text\nimport React, {FC, Fragment, ... other imports ...} from \"react\"\n```\n\n```text\nconst MainListItems = () => {\n    const navList:Array<{ id: number, name: string, icon: JSX.Element }> = [\n        { id: 1, name: 'Notes', icon: <LightbulbOutlinedIcon />},\n        { id: 2, name: 'Reminders', icon:  <NotificationsNoneOutlinedIcon /> },\n        { id: 3, name: 'Bin', icon: <DeleteOutlinedIcon /> },\n    ]\n\n    return (\n            <List>\n                {\n                    navList.map( list => (\n                        <ListItem key={list.id} disablePadding sx={{display: 'block'}}>\n                            <ListItemButton sx={{minHeight: 48, justifyContent: open ? 'initial' : 'center', px: 2.5}}>\n                                <ListItemIcon sx={{minWidth: 0, mr: open ? 3 : 'auto', justifyContent: 'center'}}>\n                                    {list.icon}\n                                </ListItemIcon>\n                                <ListItemText primary={list.name} sx={{opacity: open ? 1 : 0}}/>\n                            </ListItemButton>\n                        </ListItem>\n                    ))\n                }\n            </List>\n    )\n}\n```\n\n```text\nReact\n```\n\n```text\nJSX\n```\n\n```text\nReact\n```\n\n```text\nJSX\n```\n\n```text\nh1\n```\n\n```text\ndiv\n```\n\n```text\np\n```\n\n```text\nimport * as React from 'react'\n```\n\n```text\nnewList\n```\n\n```text\nTypeScript\n```\n\n```text\nJSX\n```\n\n```text\nReact\n```\n\n```text\nJSX\n```\n\n```text\nReactNode\n```\n\n```text\nJSX.Element\n```\n\n```text\nJSX.Element\n```\n\n```text\nReactNode\n```\n\n========================================\n\nComments:\n- does your file has the correct extension? (.jsx or .tsx). Also maybe it can be a cache issue, restart your dev server to make sure it's not coming from that. I don't see any issues concerning the error you are receiving.\n- is navList a state variable?\n- Please take the tour. Solutions should be posted as answers below. Don't forget to accept it to resolve this post. Or delete the post.\n- Component name is not a factor in my case. I don't consider that a general solution.\n- I tested your code and it does not give any typescript warning or any kind of error and it renders\n- Please show your tsconfig and package.json in your post.\n- No one has mentioned TypeScript, nor is it tagged.\n- @AshwinSamGeorge please approve the answer so that people do not post more answers to this question. I just spent 15 minutes writing an answer without realizing that GoodMan already posted the solution.\n- TypeScript was not mentioned nor tagged.\n- TypeScript was not mentioned nor tagged. Does this answer still apply?\n- The error shared is a typescript error. Typescript might have been configured to parse `.jsx` file extensions, hence the type error. Do you want the question to be tagged appropriately.\n- That's a fair point, and one that I haven't seen come up yet. In that case it's a matter of IDE config and not code.","metadata":{"transformedAt":"2026-08-18T18:33:46.430Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":36,"totalLines":313,"estimatedTokens":1836}}468{"id":"stack-69017658","source":"stackoverflow","questionId":69017658,"title":"Vite + Storybook + SCSS: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):","tags":["node.js","reactjs","storybook","vite"],"text":"Title: Vite + Storybook + SCSS: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):\nTags: node.js, reactjs, storybook, vite\nSource: Stack Overflow\n\nQuestion:\nI struggle for a good 4-5 hours to make SCSS work with Vite + Storybook setup and I need your help.\nI'm getting the following error message when I try to start Storybook:\n\n```\nERROR in ./src/styles/main.scss (./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js!./src/styles/main.scss)\nModule build failed (from ./node_modules/sass-loader/dist/cjs.js):\n```\n\nStorybook `main.js`\n\n```\nconst path = require('path');\nmodule.exports = {\n \"stories\": [\n \"../src/**/*.stories.mdx\",\n \"../src/**/*.stories.@(js|jsx|ts|tsx)\"\n ],\n \"addons\": [\n \"@storybook/addon-links\",\n \"@storybook/addon-essentials\"\n ],\n webpackFinal: async (config) => {\n config.module.rules.push({\n test: /\\.scss$/,\n use: ['style-loader', 'css-loader', 'sass-loader'],\n include: path.resolve(__dirname, '../'),\n });\n\n return config;\n }\n}\n```\n\nI'm importing the SCSS in the Storybook `preview.js`\nThe SCSS works fine in Vite but not loading in Storybook.\n\n```\n...\nimport '../src/styles/main.scss'\n...\n```\n\nAnd finally the `package.json`\n\n```\n{\n \"name\": \"X\",\n \"version\": \"0.0.0\",\n \"scripts\": {\n \"start\": \"vite\",\n \"build\": \"vite build\",\n \"serve\": \"vite preview\",\n \"storybook\": \"start-storybook -p 6006\",\n \"build-storybook\": \"build-storybook\"\n },\n \"dependencies\": {\n \"css-loader\": \"^3.6.0\",\n \"history\": \"^4.10.1\",\n \"react\": \"^17.0.0\",\n \"react-dom\": \"^17.0.0\",\n \"react-redux\": \"^7.2.4\",\n \"react-router\": \"^5.2.0\",\n \"react-router-dom\": \"^5.2.0\",\n \"sass-loader\": \"^12.1.0\",\n \"style-loader\": \"^1.3.0\",\n \"styled-components\": \"^5.3.1\"\n },\n \"devDependencies\": {\n \"@babel/core\": \"^7.15.0\",\n \"@storybook/addon-actions\": \"^6.3.7\",\n \"@storybook/addon-docs\": \"^6.3.7\",\n \"@storybook/addon-essentials\": \"^6.3.7\",\n \"@storybook/addon-links\": \"^6.3.7\",\n \"@storybook/react\": \"^6.3.7\",\n \"@vitejs/plugin-react-refresh\": \"^1.3.1\",\n \"babel-loader\": \"^8.2.2\",\n \"sass\": \"^1.35.2\",\n \"vite\": \"^2.4.3\"\n }\n}\n```\n\nWould appreciate your help with this. Thanks!\n\n========================================\n\nCode:\n```text\nERROR in ./src/styles/main.scss (./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js!./src/styles/main.scss)\nModule build failed (from ./node_modules/sass-loader/dist/cjs.js):\n```\n\n```text\nconst path = require('path');\nmodule.exports = {\n  \"stories\": [\n    \"../src/**/*.stories.mdx\",\n    \"../src/**/*.stories.@(js|jsx|ts|tsx)\"\n  ],\n  \"addons\": [\n    \"@storybook/addon-links\",\n    \"@storybook/addon-essentials\"\n  ],\n  webpackFinal: async (config) => {\n    config.module.rules.push({\n      test: /\\.scss$/,\n      use: ['style-loader', 'css-loader', 'sass-loader'],\n      include: path.resolve(__dirname, '../'),\n    });\n\n    return config;\n  }\n}\n```\n\n```text\n...\nimport '../src/styles/main.scss'\n...\n```\n\n```text\n{\n  \"name\": \"X\",\n  \"version\": \"0.0.0\",\n  \"scripts\": {\n    \"start\": \"vite\",\n    \"build\": \"vite build\",\n    \"serve\": \"vite preview\",\n    \"storybook\": \"start-storybook -p 6006\",\n    \"build-storybook\": \"build-storybook\"\n  },\n  \"dependencies\": {\n    \"css-loader\": \"^3.6.0\",\n    \"history\": \"^4.10.1\",\n    \"react\": \"^17.0.0\",\n    \"react-dom\": \"^17.0.0\",\n    \"react-redux\": \"^7.2.4\",\n    \"react-router\": \"^5.2.0\",\n    \"react-router-dom\": \"^5.2.0\",\n    \"sass-loader\": \"^12.1.0\",\n    \"style-loader\": \"^1.3.0\",\n    \"styled-components\": \"^5.3.1\"\n  },\n  \"devDependencies\": {\n    \"@babel/core\": \"^7.15.0\",\n    \"@storybook/addon-actions\": \"^6.3.7\",\n    \"@storybook/addon-docs\": \"^6.3.7\",\n    \"@storybook/addon-essentials\": \"^6.3.7\",\n    \"@storybook/addon-links\": \"^6.3.7\",\n    \"@storybook/react\": \"^6.3.7\",\n    \"@vitejs/plugin-react-refresh\": \"^1.3.1\",\n    \"babel-loader\": \"^8.2.2\",\n    \"sass\": \"^1.35.2\",\n    \"vite\": \"^2.4.3\"\n  }\n}\n```\n\n```text\nmain.js\n```\n\n```text\npreview.js\n```\n\n```text\npackage.json\n```\n\n```text\nyarn add -D @storybook/preset-scss\n```\n\n```sh\nyarn remove sass-loader style-loader css-loader\n```\n\n```sh\nyarn add -D sass-loader@10.1.1 style-loader@2.0.0 css-loader@5.2.6\n```\n\n```js\n// .storybook/main.js\nmodule.exports = {\n  stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],\n  addons: [\n    '@storybook/addon-links',\n    '@storybook/addon-essentials',\n    '@storybook/preset-scss',\n  ],\n};\n```\n\n```json\npackage.json\n...\n\"devDependencies\": {\n    \"@storybook/addon-actions\": \"^6.3.6\",\n    \"@storybook/addon-essentials\": \"^6.3.6\",\n    \"@storybook/addon-links\": \"^6.3.6\",\n    \"@storybook/html\": \"^6.3.6\",\n    \"@storybook/preset-scss\": \"^1.0.3\",\n    \"css-loader\": \"5.2.6\",\n    \"sass-loader\": \"10\",\n    \"style-loader\": \"2.0.0\",\n  },\n...\n```\n\n```text\n@storybook/scss-loader\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.430Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":219,"estimatedTokens":1169}}469{"id":"stack-76400226","source":"stackoverflow","questionId":76400226,"title":"Storybook asks me to choose if my project is using Vite or Webpack 5, but I am using Rollup","tags":["webpack","vite","storybook","rollup"],"text":"Title: Storybook asks me to choose if my project is using Vite or Webpack 5, but I am using Rollup\nTags: webpack, vite, storybook, rollup\nSource: Stack Overflow\n\nQuestion:\nI am trying to build my first component library. Following a guide, I've simply initiatd a new empty npm project added rollup as the builder and started adding all my components in the src directory (in the components folder).\n\nWhen trying to ad Storybook, it says: `We were not able to detect the right builder for your project. Please select one:` and lets me choose between Vite or Webpack 5, but it's neither. What should I do? Should one of them work better than the other? Would they both cause issues?\n\n========================================\n\nCode:\n```text\nWe were not able to detect the right builder for your project. Please select one:\n```\n\n========================================\n\nComments:\n- Good to know! I thought they are both doing the same thing just differently. Thank you","metadata":{"transformedAt":"2026-08-18T18:33:46.430Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":20,"estimatedTokens":242}}470{"id":"stack-74518199","source":"stackoverflow","questionId":74518199,"title":"I keep getting an error in Vite version 3.2.4 which says `[vite:esbuild] The service is no longer running: write EPIPE`","tags":["javascript","reactjs","typescript","npm","vite"],"text":"Title: I keep getting an error in Vite version 3.2.4 which says `[vite:esbuild] The service is no longer running: write EPIPE`\nTags: javascript, reactjs, typescript, npm, vite\nSource: Stack Overflow\n\nQuestion:\nAfter creating a vite app. I run the command `npm run dev` and I get this error\n\n```\n[vite:esbuild] The service is no longer running: write EPIPE\n```\n\nhttps://i.sstatic.net/MZuyK.png\n\n**Please, How do I solve this error.**\n\nI have tried the following solutions\n\nVite build fails with esbuild error\n\nerror while transforming /app/client/vite.config.ts with esbuild in Docker image\n\n========================================\n\nTop Answer:\nRemoving packages and re-installing (if you are not using npm ci) helped me.\n\n- Deleting packages\n\n```\nrm -rf ./node_modules ./package-lock.json\n```\n\n- Re-installing packages\n\n```\nnpm i\n```\n\n- Running the server\n\n```\nnpm run dev\n```\n\n========================================\n\nCode:\n```bash\n[vite:esbuild] The service is no longer running: write EPIPE\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run dev\n```\n\n```bash\nrm -rf ./node_modules ./package-lock.json\n```\n\n```bash\nnpm i\n```\n\n```bash\nnpm run dev\n```\n\n========================================\n\nComments:\n- Thanks @neil your solutions works. 👌\n- can confirm, SMADAV is the culprit\n- This is not a solution, just a symptom that happened to work for your specific case.\n- @Midiman Okay - What do you propose ?\n- @ayitinya Honestly SMADAV had me chasing ghosts in my codebase for 2 weeks 😤. medium.com/@olawamidemoyinoluwamary/&hellip;\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- I have no antivirus software other than Microsofts Defender running. So this solution is not viable to me. What else could be the root cause of this issue?\n- That's the equivalent of turn it off and on again and it solves the issue, so thank you.","metadata":{"transformedAt":"2026-08-18T18:33:46.430Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":82,"estimatedTokens":515}}471{"id":"stack-72587871","source":"stackoverflow","questionId":72587871,"title":"How to include an WASM npm module in svelte with vite?","tags":["svelte","webassembly","vite","wasm-pack"],"text":"Title: How to include an WASM npm module in svelte with vite?\nTags: svelte, webassembly, vite, wasm-pack\nSource: Stack Overflow\n\nQuestion:\nI'm using vite to run a svelte app, and have a WASM package built with `wasm-pack --target web`. If I use the package directly with vanilla JS, I can write something like:\n\n```\n\n import init, { greet } from \"./pkg/compiler.js\";\n\n init().then(() => {\n greet(\"Hello\");\n });\n\n```\n\nin an HTML file where `greet` is one of my `wasm_bindgen` functions, and that works fine.\n\nHowever, my intended pipeline is to publish the `pkg/` folder that `wasm-pack` generates to npm, and then use this package in svelte with vite, something like so:\n\n```\n\n import init, { greet } from \"@ocr-compiler/compiler\";\n \n init().then(() => {\n greet(\"Hello\");\n });\n\n```\n\nHowever, this throws an error:\n`Unknown file extension \".wasm\" for /home/drbracewell/code/ocr/packages/svelte-editor/node_modules/@ocr-compiler/compiler/compiler_bg.wasm`\nDoes anyone know how I can fix this?\nVite docs mention that it will automatically process `.wasm` files, but does this not happen when they're included from npm packages?\n\n========================================\n\nCode:\n```html\n<script type=\"module\">\n    import init, { greet } from \"./pkg/compiler.js\";\n\n    init().then(() => {\n        greet(\"Hello\");\n    });\n</script>\n```\n\n```html\n<script lang=\"ts\">\n    import init, { greet } from \"@ocr-compiler/compiler\";\n    \n    init().then(() => {\n        greet(\"Hello\");\n    });\n</script>\n```\n\n```text\nwasm-pack --target web\n```\n\n```text\ngreet\n```\n\n```text\nwasm_bindgen\n```\n\n```text\npkg/\n```\n\n```text\nwasm-pack\n```\n\n```text\nUnknown file extension \".wasm\" for /home/drbracewell/code/ocr/packages/svelte-editor/node_modules/@ocr-compiler/compiler/compiler_bg.wasm\n```\n\n```text\n.wasm\n```\n\n```text\n--target web\n```\n\n```text\nwasm-pack\n```\n\n```text\nnpm\n```\n\n```text\nmain\n```\n\n```text\npackage.json\n```\n\n```text\nwasm-pack\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.430Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":110,"estimatedTokens":479}}472{"id":"stack-77843430","source":"stackoverflow","questionId":77843430,"title":"What does `svelte-kit sync` do?","tags":["typescript","vite","svelte","sveltekit"],"text":"Title: What does `svelte-kit sync` do?\nTags: typescript, vite, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI've checked the svelte-kit sync docs and the discussion around it and even tried searching Stack Overflow and asking AI.\n\nMy understanding is it generates `tsconfig.json` and is for setting up the project with typescript. When I delete my `tsconfig.json` and run it, nothing seems to happen.\n\n========================================\n\nCode:\n```text\ntsconfig.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\nload\n```\n\n```text\ndata\n```\n\n```text\nform\n```\n\n```text\ntsconfig.json\n```\n\n```text\n.svelte-kit\n```\n\n```text\nsync\n```\n\n========================================\n\nComments:\n- Awesome, thank you! So, when you say \"running separate builds\" you mean it's useful for having a setup where you can build the same project in different ways?\n- I mean e.g. a clean install in a CI pipeline where the dev server is never run at all, so the types would not be there otherwise.\n- You will also want to ensure that your own tsconfig file inherits from the generated one at `.&#47;svelte-kit.json` eg: ``` { \"extends\": \"./.svelte-kit/tsconfig.json\", \"compilerOptions\": { \"allowJs\": true, \"checkJs\": true, \"esModuleInterop\": true, \"forceConsistentCasingInFileNames\": true, \"resolveJsonModule\": true, \"skipLibCheck\": true, \"sourceMap\": true, \"strict\": true, \"module\": \"NodeNext\", \"moduleResolution\": \"NodeNext\" } } ```\n- You will also want to ensure that your own tsconfig file inherits from the generated one at `.&#47;svelte-kit.json` eg: `{\"extends\": \".&#47;.svelte-kit&#47;tsconfig.json\",\"compilerOptions\": {...}}`\n- @AnthonyHolland: You did not have to list all the other settings and this is set up correctly by default when using `npm create svelte` anyway. (Hence probably only relevant if TS is added manually later.)","metadata":{"transformedAt":"2026-08-18T18:33:46.430Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":52,"estimatedTokens":456}}473{"id":"stack-76041012","source":"stackoverflow","questionId":76041012,"title":"Web Worker written in Typescript does not get built/compiled (using vite) into Javascript","tags":["javascript","typescript","svelte","vite","web-worker"],"text":"Title: Web Worker written in Typescript does not get built/compiled (using vite) into Javascript\nTags: javascript, typescript, svelte, vite, web-worker\nSource: Stack Overflow\n\nQuestion:\nI am using a Web Worker in typescript the following way:\n\n```\nconst url = new URL(\"src/lib/Functions/CalculateRidge.ts\", import.meta.url);\nconst worker = new Worker(url, { type: 'module' })\n```\n\nIn development, this work perfectly fine, the worker is loaded from the given url, and the worker executes the function and gives the correct result. But when building, all files get converted to .js except my worker file. Then in deployment (Github Pages) when the same code above is being executed, the url request IS succesful (it finds the file and makes a valid/succesful request for it), but the code fails with the following error message:\n\n\"Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of \"video/mp2t\". Strict MIME type checking is enforced for module scripts per HTML spec.\"\n\nI believe this error comes because a typescript file (a file with .ts extentions) cannot be executed or read, so i believe the error lays in that the Web Worker typescript file is not being compiled/transformed into Javascript.\n\nThis is an image of the distribution/build folder:\n\nhttps://i.sstatic.net/Oimck.png\n\nI use \"vite build\" to build the project and \"npx gh-pages -d dist\" to deploy the project to Github Pages. The `vite.config.ts` file looks like this:\n\n```\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\nimport path from 'path';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n base: \"/solar-analysis-faroe-island/\",\n plugins: [svelte()],\n resolve: {\n alias: {\n src: path.resolve('src/'),\n }\n },\n})\n```\n\n`tsconfig.node.json` looks like this:\n\n```\n{\n \"compilerOptions\": {\n \"composite\": true,\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Node\"\n },\n \"include\": [\"vite.config.ts\"]\n}\n```\n\n`tsconfig.json` looks like this:\n\n```\n{\n \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n \"compilerOptions\": {\n \"baseUrl\": \".\",\n \"target\": \"ESNext\",\n \"useDefineForClassFields\": true,\n \"module\": \"ESNext\",\n \"resolveJsonModule\": true,\n \"paths\": {\n \"src/*\": [\n \"src/*\"\n ]\n },\n /**\n * Typecheck JS in `.svelte` and `.js` files by default.\n * Disable checkJs if you'd like to use dynamic types in JS.\n * Note that setting allowJs false does not prevent the use\n * of JS in `.svelte` files.\n */\n \"allowJs\": true,\n \"checkJs\": true,\n \"isolatedModules\": true\n },\n \"include\": [\"src/*.ts\",\"src/**/*.d.ts\", \"src/**/*.ts\", \"src/**/*.js\", \"src/**/*.svelte\"],\n \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\nAnd `svelte.config.js` looks like this:\n\n```\nimport { vitePreprocess } from '@sveltejs/vite-plugin-svelte'\n\nexport default {\n // Consult https://svelte.dev/docs#compile-time-svelte-preprocess\n // for more information about preprocessors\n preprocess: vitePreprocess(),\n\n}\n```\n\n========================================\n\nCode:\n```text\nconst url = new URL(\"src/lib/Functions/CalculateRidge.ts\", import.meta.url);\nconst worker = new Worker(url, { type: 'module' })\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\nimport path from 'path';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  base: \"/solar-analysis-faroe-island/\",\n  plugins: [svelte()],\n  resolve: {\n    alias: {\n      src: path.resolve('src/'),\n    }\n  },\n})\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Node\"\n  },\n  \"include\": [\"vite.config.ts\"]\n}\n```\n\n```text\n{\n  \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"target\": \"ESNext\",\n    \"useDefineForClassFields\": true,\n    \"module\": \"ESNext\",\n    \"resolveJsonModule\": true,\n    \"paths\": {\n      \"src/*\": [\n        \"src/*\"\n      ]\n    },\n    /**\n     * Typecheck JS in `.svelte` and `.js` files by default.\n     * Disable checkJs if you'd like to use dynamic types in JS.\n     * Note that setting allowJs false does not prevent the use\n     * of JS in `.svelte` files.\n     */\n    \"allowJs\": true,\n    \"checkJs\": true,\n    \"isolatedModules\": true\n  },\n  \"include\": [\"src/*.ts\",\"src/**/*.d.ts\", \"src/**/*.ts\", \"src/**/*.js\", \"src/**/*.svelte\"],\n  \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\n```text\nimport { vitePreprocess } from '@sveltejs/vite-plugin-svelte'\n\nexport default {\n  // Consult https://svelte.dev/docs#compile-time-svelte-preprocess\n  // for more information about preprocessors\n  preprocess: vitePreprocess(),\n\n}\n```\n\n```text\nvite.config.ts\n```\n\n```text\ntsconfig.node.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\nsvelte.config.js\n```\n\n```js\nimport workerUrl from \"src/lib/Functions/CalculateRidge?worker&url\";\nconst worker = new Worker(workerUrl, { type: 'module' })\n```\n\n```text\n?worker&url\n```\n\n========================================\n\nComments:\n- I tried importing the url as you specified, but now i get the following error when deploying: \"Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit: (vite:worker) transform \"project/location/solar-analysis-faroe-island/src/lib/Functi&zwnj;&#8203;ons/CalculateRidge.t&zwnj;&#8203;s?worker&url\"\". Your suggested change still works for development though. What could cause this error? And imports only work at the top-level of the code, right? Because i cannot place the import just above the const worker = ...\n- I have unfortunately never seen that error before. And yes, the import should be on the top level, in other places one may use a dynamic import but there is not really any point here as the import just provides a URL (i.e. the import itself does not load a large amount of data that might be worth lazy loading later).\n- Well that's no good... do you have any suggestions on how i could work around this error? I see one suggesting installing older versions of rollup, but that did not work for me...\n- Have you seen the SvelteKit issue referencing the linked Vite issue? Here is a suggested workaround, if that helps I would add that to the answer while the issue is resolved.\n- I'm sorry, i'm looking at my problem right now, and i see that i should had mentioned that i keep both the code that creates the worker and the worker itself inside the same script. The reason: so all worker-code is located in one file. I seperated the file, and i believe that solved the issue. But now a new issue regarding GeoTiff.js in build has emerged, i'll open a new issue.\n- New question: stackoverflow.com/questions/76051452/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:46.430Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":208,"estimatedTokens":1662}}474{"id":"stack-79459792","source":"stackoverflow","questionId":79459792,"title":"ShadCN and TailwindCSS V4 causing error [plugin:@tailwindcss/vite:generate:serve] Unexpected semicolon","tags":["reactjs","tailwind-css","vite","shadcnui"],"text":"Title: ShadCN and TailwindCSS V4 causing error [plugin:@tailwindcss/vite:generate:serve] Unexpected semicolon\nTags: reactjs, tailwind-css, vite, shadcnui\nSource: Stack Overflow\n\nQuestion:\nI am currently trying to make a new project on React 19 using Vite, TailwindCSS V4 and ShadCN. Been following the documentation from ShadCN. After initializing the shadCN with command `pnpm dlx shadcn@canary init`, which adds the components.json and sets up the CSS variables, it breaks the application. The error message is the following\n`[vite] Internal server error: Unexpected semicolon`\n\n`Plugin: @tailwindcss/vite:generate:serve`\n\n`File: C:/Users/joni/Documents/GitHub/txtcompare/src/index.css`.\n\nIf I remove the styling it has created to the index.css, it works but of course then the styling is gone. Has anyone else encountered this?\n\n========================================\n\nCode:\n```text\npnpm dlx shadcn@canary init\n```\n\n```text\n[vite] Internal server error: Unexpected semicolon\n```\n\n```text\nPlugin: @tailwindcss/vite:generate:serve\n```\n\n```text\nFile: C:/Users/joni/Documents/GitHub/txtcompare/src/index.css\n```\n\n```text\n--radius: 0.625rem;;\n```\n\n========================================\n\nComments:\n- Yep, this fixed it for me too. Looks like there's an issue in GitHub raised to address this: github.com/shadcn-ui/ui/issues/6737","metadata":{"transformedAt":"2026-08-18T18:33:46.430Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":41,"estimatedTokens":333}}475{"id":"stack-78456635","source":"stackoverflow","questionId":78456635,"title":"Could not convert symbol to string error after adding https certificate","tags":["asp.net","https","vite","sveltekit"],"text":"Title: Could not convert symbol to string error after adding https certificate\nTags: asp.net, https, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am trying to fetch data from asp.net core api to svelte page. I got a self signed certificate error:\n\n```\nTypeError: fetch failed\n at node:internal/deps/undici/undici:12500:13\n at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {\n [cause]: Error: self-signed certificate\n at TLSSocket.onConnectSecure (node:_tls_wrap:1674:34)\n at TLSSocket.emit (node:events:520:28)\n at TLSSocket._finishInit (node:_tls_wrap:1085:8)\n at ssl.onhandshakedone (node:_tls_wrap:871:12)\n at TLSWrap.callbackTrampoline (node:internal/async_hooks:130:17) {\n code: 'DEPTH_ZERO_SELF_SIGNED_CERT'\n }\n}\n```\n\nNext I used mkcert to create a certificate and key inside the project directory and then I updated vite.config.ts to look like this:\n\n```\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vite';\nimport fs from 'fs';\n\nexport default defineConfig({\n\n plugins: [sveltekit()],\n server: {\n https: {\n key: fs.readFileSync(`${__dirname}/cert/key.pem`),\n cert: fs.readFileSync(`${__dirname}/cert/cert.pem`)\n }\n }\n});\n```\n\nFinally, when I start the sveltekit server I am greeted with this error in the browser:\n\n```\nTypeError: Could not convert argument of type symbol to string.\n at webidl.converters.DOMString (node:internal/deps/undici/undici:1940:15)\n at webidl.converters.ByteString (node:internal/deps/undici/undici:1945:35)\n at Object.record (node:internal/deps/undici/undici:1857:30)\n at webidl.converters.HeadersInit (node:internal/deps/undici/undici:3397:67)\n at Object.RequestInit (node:internal/deps/undici/undici:1914:21)\n at new Request (node:internal/deps/undici/undici:4821:34)\n at getRequest (file:///C:/path/to/project/Client/node_modules/@sveltejs/kit/src/exports/node/index.js:107:9)\n at file:///path/to/project/Client/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js:497:2\n```\n\nBTW mkcert -install informed me that firefox is not supported on my platform.\n\nSetting up the certificate for dev environment seems like a simple task, but I've been frustrated that I can't actually develop the website for quite some time now.\n\nI want to fetch data from asp.net core api to a sveltekit front end, but I can't, because I get errors from which I can't make any sense.\n\n========================================\n\nCode:\n```text\nTypeError: fetch failed\n    at node:internal/deps/undici/undici:12500:13\n    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {\n  [cause]: Error: self-signed certificate\n      at TLSSocket.onConnectSecure (node:_tls_wrap:1674:34)\n      at TLSSocket.emit (node:events:520:28)\n      at TLSSocket._finishInit (node:_tls_wrap:1085:8)\n      at ssl.onhandshakedone (node:_tls_wrap:871:12)\n      at TLSWrap.callbackTrampoline (node:internal/async_hooks:130:17) {\n    code: 'DEPTH_ZERO_SELF_SIGNED_CERT'\n  }\n}\n```\n\n```text\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vite';\nimport fs from 'fs';\n\nexport default defineConfig({\n\n    plugins: [sveltekit()],\n    server: {\n        https: {\n            key: fs.readFileSync(`${__dirname}/cert/key.pem`),\n            cert: fs.readFileSync(`${__dirname}/cert/cert.pem`)\n        }\n    }\n});\n```\n\n```text\nTypeError: Could not convert argument of type symbol to string.\n    at webidl.converters.DOMString (node:internal/deps/undici/undici:1940:15)\n    at webidl.converters.ByteString (node:internal/deps/undici/undici:1945:35)\n    at Object.record<ByteString, ByteString> (node:internal/deps/undici/undici:1857:30)\n    at webidl.converters.HeadersInit (node:internal/deps/undici/undici:3397:67)\n    at Object.RequestInit (node:internal/deps/undici/undici:1914:21)\n    at new Request (node:internal/deps/undici/undici:4821:34)\n    at getRequest (file:///C:/path/to/project/Client/node_modules/@sveltejs/kit/src/exports/node/index.js:107:9)\n    at file:///path/to/project/Client/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js:497:2\n```\n\n```js\nexport default defineConfig({\n    plugins: ...,\n    server: {\n        https: {\n            key: ...,\n            cert: ...\n        },\n        // this line fixes it *somehow*\n        proxy: {},\n    }\n});\n```\n\n```text\nproxy: {}\n```\n\n```text\nserver\n```\n\n========================================\n\nComments:\n- Since writing this question I've decided to not use Svelte or any other frontend framework and just stick to ASP.NET Core's MVC. I can't check if this would work for me, so I'll just mark your answer as accepted.","metadata":{"transformedAt":"2026-08-18T18:33:46.430Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":134,"estimatedTokens":1147}}476{"id":"stack-68758939","source":"stackoverflow","questionId":68758939,"title":"Github pages vite JS build not showing the images","tags":["backend","vite"],"text":"Title: Github pages vite JS build not showing the images\nTags: backend, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make simple portfolio using Github pages but something is wrong with the images. I can't load them. Can you help me how to fix that?\n\nhttps://i.sstatic.net/xV7U3.png\n\nhttps://xakepa.github.io/Portfolio/\n\nHere is my build folder. I used Vite and Three libraries\nhttps://github.com/xakepa/Portfolio/tree/main/dist\n\n========================================\n\nTop Answer:\nI had the same problem, I solved it by adding the images in the `public folder` inside the `root` instead of the `src folder`, like this `public/assets/img`\n\nand the img src will be like this\n``\n\n```\n─┬root\n |\n ├─public/assets/img\n ├─src\n ├─.gitignore\n ├─vite.config.js\n ├─README.md\n ├─dist\n ├─.yarn\n```\n\n========================================\n\nCode:\n```text\nconst spaceTexture = new THREE.TextureLoader().load(\"./images/space.jpg\");\n```\n\n```text\n(\"images/space.jpg\");\n```\n\n```text\n─┬root\n  |\n  ├─public/assets/img\n  ├─src\n  ├─.gitignore\n  ├─vite.config.js\n  ├─README.md\n  ├─dist\n  ├─.yarn\n```\n\n```text\npublic folder\n```\n\n```text\nroot\n```\n\n```text\nsrc folder\n```\n\n```text\npublic/assets/img\n```\n\n```text\n<img src=\"/assets/img/downlaod.png\" />\n```\n\n```text\n<img\n    loading=\"lazy\" <--- not necessary \n    src={`/icons/flags/${dynamicImageName}.png`} <--- here \n/>\n```\n\n========================================\n\nComments:\n- Correct and it's worth linking the documentation of Vite about that - You can find more information on \"How to handle static asset\" in Vite here: vitejs.dev/guide/assets.html\n- This *sort of* worked, but I had warnings from the build `new URL('.&#47;assets&#47;images&#47;noentry.jpg', import.meta.url) doesn't exist at build time, it will remain unchanged to be resolved at runtime` and the images were placed in a subfolder of `dist\\assets`","metadata":{"transformedAt":"2026-08-18T18:33:46.430Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":89,"estimatedTokens":465}}477{"id":"stack-72653482","source":"stackoverflow","questionId":72653482,"title":"Flowbite modal not showing","tags":["vue.js","tailwind-css","vite","flowbite"],"text":"Title: Flowbite modal not showing\nTags: vue.js, tailwind-css, vite, flowbite\nSource: Stack Overflow\n\nQuestion:\nI am trying to use flowbite components in my project but they are not working , (e.g dropdown, modal,...).\n\nI followed the documentation but nothing works.\n\nI'm using vuejs 3, Vite v2.9.9.\n\nThis is my `main.js` file:\n\n```\nimport { createApp } from 'vue'\nimport App from \"@/App.vue\";\nimport router from './router/index'\nimport store from './state/store'\n\n// Imported css file [TailwindCSS]\nimport './index.css'\n\n// Imported flowbite\nimport 'flowbite';\n\ncreateApp(App)\n .use(router)\n .use(store)\n .mount('#app')\n```\n\nmodal.vue\n\n```\n\n \n \n Toggle modal\n \n\n \n \n \n \n \n \n \n \n Terms of Service\n \n \n \n \n \n \n test\n \n \n I accept\n Decline\n \n \n \n \n\n```\n\n========================================\n\nTop Answer:\nThis took me 2 weeks to figure out, I am using Vite with Vue.\n\nI followed the instructions here https://flowbite.com/docs/getting-started/vue/\n\nWhere it didn't state to add the `script tag`\n**``**\n\nin my `index.html`\n\nWhich is, stated in #3 https://flowbite.com/docs/getting-started/quickstart/\n\n========================================\n\nCode:\n```js\nimport { createApp } from 'vue'\nimport App from \"@/App.vue\";\nimport router from './router/index'\nimport store from './state/store'\n\n// Imported css file [TailwindCSS]\nimport './index.css'\n\n// Imported flowbite\nimport 'flowbite';\n\ncreateApp(App)\n    .use(router)\n    .use(store)\n    .mount('#app')\n```\n\n```js\n<template>\n\n  <!-- Modal toggle -->\n  <button class=\"block text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800\" type=\"button\" data-modal-toggle=\"default-modal\">\n    Toggle modal\n  </button>\n\n  <!-- Main modal -->\n  <div id=\"default-modal\" aria-hidden=\"true\" class=\"hidden overflow-y-auto overflow-x-hidden fixed right-0 left-0 top-4 z-50 justify-center items-center h-modal md:h-full md:inset-0\">\n      <div class=\"relative px-4 w-full max-w-2xl h-full md:h-auto\">\n          <!-- Modal content -->\n          <div class=\"relative bg-white rounded-lg shadow dark:bg-gray-700\">\n              <!-- Modal header -->\n              <div class=\"flex justify-between items-start p-5 rounded-t border-b dark:border-gray-600\">\n                  <h3 class=\"text-xl font-semibold text-gray-900 lg:text-2xl dark:text-white\">\n                      Terms of Service\n                  </h3>\n                  <button type=\"button\" class=\"text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center dark:hover:bg-gray-600 dark:hover:text-white\" data-modal-toggle=\"default-modal\">\n                      <svg class=\"w-5 h-5\" fill=\"currentColor\" viewBox=\"0 0 20 20\" xmlns=\"http://www.w3.org/2000/svg\"><path fill-rule=\"evenodd\" d=\"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z\" clip-rule=\"evenodd\"></path></svg>  \n                  </button>\n              </div>\n              <!-- Modal body -->\n              test\n              <!-- Modal footer -->\n              <div class=\"flex items-center p-6 space-x-2 rounded-b border-t border-gray-200 dark:border-gray-600\">\n                  <button data-modal-toggle=\"default-modal\" type=\"button\" class=\"text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800\">I accept</button>\n                  <button data-modal-toggle=\"default-modal\" type=\"button\" class=\"text-gray-500 bg-white hover:bg-gray-100 focus:ring-4 focus:ring-gray-300 rounded-lg border border-gray-200 text-sm font-medium px-5 py-2.5 hover:text-gray-900 focus:z-10 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-500 dark:hover:text-white dark:hover:bg-gray-600\">Decline</button>\n              </div>\n          </div>\n      </div>\n  </div>\n</template>\n```\n\n```text\nmain.js\n```\n\n```text\nimport 'flowbite/dist/flowbite.js'\n...\nlet modal = new Modal(document.getElementById('modalId'),{placement:'center'})\n...\n<button on:cllick={()=>modal.show()} >Open</button>\n```\n\n```html\n<template>\n  <!-- Modal toggle -->\n  <button class=\"block text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800\" type=\"button\" @click=\"toggleModal\">\n    Toggle modal\n  </button>\n  \n  <!-- Main modal -->\n  <div id=\"defaultModal\" tabindex=\"-1\" aria-hidden=\"true\" class=\"hidden overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-50 w-full md:inset-0 h-modal md:h-full justify-center items-center\">\n      <div class=\"relative p-4 w-full max-w-2xl h-full md:h-auto\">\n          <!-- Modal content -->\n          <div class=\"relative bg-white rounded-lg shadow dark:bg-gray-700\">\n              <!-- Modal header -->\n              <div class=\"flex justify-between items-start p-4 rounded-t border-b dark:border-gray-600\">\n                  <h3 class=\"text-xl font-semibold text-gray-900 dark:text-white\">\n                      Terms of Service\n                  </h3>\n                  <button type=\"button\" class=\"text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center dark:hover:bg-gray-600 dark:hover:text-white\" @click=\"toggleModal\">\n                      <svg aria-hidden=\"true\" class=\"w-5 h-5\" fill=\"currentColor\" viewBox=\"0 0 20 20\" xmlns=\"http://www.w3.org/2000/svg\"><path fill-rule=\"evenodd\" d=\"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z\" clip-rule=\"evenodd\"></path></svg>\n                      <span class=\"sr-only\">Close modal</span>\n                  </button>\n              </div>\n              <!-- Modal body -->\n              <div class=\"p-6 space-y-6\">\n                  <p class=\"text-base leading-relaxed text-gray-500 dark:text-gray-400\">\n                      With less than a month to go before the European Union enacts new consumer privacy laws for its citizens, companies around the world are updating their terms of service agreements to comply.\n                  </p>\n                  <p class=\"text-base leading-relaxed text-gray-500 dark:text-gray-400\">\n                      The European Union’s General Data Protection Regulation (G.D.P.R.) goes into effect on May 25 and is meant to ensure a common set of data rights in the European Union. It requires organizations to notify users as soon as possible of high-risk data breaches that could personally affect them.\n                  </p>\n              </div>\n              <!-- Modal footer -->\n              <div class=\"flex items-center p-6 space-x-2 rounded-b border-t border-gray-200 dark:border-gray-600\">\n                  <button @click=\"toggleModal\" type=\"button\" class=\"text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800\">I accept</button>\n                  <button @click=\"toggleModal\" type=\"button\" class=\"text-gray-500 bg-white hover:bg-gray-100 focus:ring-4 focus:outline-none focus:ring-blue-300 rounded-lg border border-gray-200 text-sm font-medium px-5 py-2.5 hover:text-gray-900 focus:z-10 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-500 dark:hover:text-white dark:hover:bg-gray-600 dark:focus:ring-gray-600\">Decline</button>\n              </div>\n          </div>\n      </div>\n  </div>\n  </template>\n  \n  <script>\n  export default {\n      data() {\n         return{\n            modal: ''\n        }\n          \n      },\n      methods: {\n          toggleModal() {\n              this.modal.toggle();\n          }\n      },\n      mounted() {\n          // set the modal menu element\n          const targetEl = document.getElementById('defaultModal');\n  \n          // options with default values\n          const options = {\n          placement: 'center',\n          backdropClasses: 'bg-gray-900 bg-opacity-50 dark:bg-opacity-80 fixed inset-0 z-40',\n          onHide: () => {\n              console.log('modal is hidden');\n          },\n          onShow: () => {\n              console.log('modal is shown');\n          },\n          onToggle: () => {\n              console.log('modal has been toggled');\n          }\n          };\n  \n          this.modal = new Modal(targetEl, options);\n    } \n  }\n  </script>\n```\n\n```text\ndata-modal-toggle=\"defaultModal\"\n```\n\n```text\nscript tag\n```\n\n```text\n<script src=\"./node_modules/flowbite/dist/flowbite.js\"></script>\n```\n\n```text\nindex.html\n```\n\n```js\nimport 'flowbite/dist/flowbite.js'\n```\n\n```text\nimport 'flowbite/dist/flowbite.js';\nimport 'flowbite/dist/flowbite.css';\nimport './index.css'\n```\n\n```text\n/** @type {import('tailwindcss').Config} */\nexport default {\n  content: [\n    \"./index.html\",\n    \"./src/**/*.{vue,js,ts,jsx,tsx}\",\n    './node_modules/flowbite/**/*.{js,jsx,ts,tsx}'\n  ],\n  theme: {\n    extend: {},\n  },\n  plugins: [\n    require('flowbite/plugin')\n  ],\n}\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport flowbite from 'flowbite/plugin'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue(), flowbite()],\n})\n```\n\n```text\nimport Sidebar from './Sidebar.vue';\nimport { onMounted } from 'vue';\nimport { Dropdown } from 'flowbite';\n\nonMounted(() => {\n  // Initialize all dropdowns\n  const dropdownElements = document.querySelectorAll('[data-dropdown-toggle]');\n  dropdownElements.forEach(triggerEl => {\n    const targetEl = document.getElementById(triggerEl.getAttribute('data-dropdown-toggle'));\n    new Dropdown(targetEl, triggerEl);\n  });\n});\n```\n\n```text\n<Sidebar />\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.430Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":300,"estimatedTokens":2517}}478{"id":"stack-78325491","source":"stackoverflow","questionId":78325491,"title":"Running standalone scripts and long-running applications with SvelteKit codebase","tags":["vite","svelte","sveltekit"],"text":"Title: Running standalone scripts and long-running applications with SvelteKit codebase\nTags: vite, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a SvelteKit project and'd like to run some maintenance scripts from the command line. I know how to run scripts with node. The maintenance scripts would refer modules in SvelteKit's `$lib` folder which then import other modules and `$env`.\n\nHow can I run a script in a way that the SvelteKit framework specific functionality imports like $lib and $env are available inside the script code?\n\nE.g.\n\n```\nnode src/scripts/myscript.js # How can import $lib here\n```\n\n- How SvelteKit sets up its framework specific modules and imports?\n\n- What of these can be used in command line applications? Naturally some like navigator cannot be made available.\n\n========================================\n\nTop Answer:\nI would proceed like that:\n\n1\nPlace your script in a directory like src/scripts. For example, src/scripts/myscript.js.\n\n2\n\n```\nnpm install --save-dev esbuild vite\n```\n\n3\n\n```\nimport { defineConfig } from 'vite';\nimport { sveltekit } from '@sveltejs/kit/vite';\n\nexport default defineConfig({\n plugins: [sveltekit()],\n build: {\n outDir: './out',\n rollupOptions: {\n input: './src/scripts/myscript.js'\n }\n }\n});\n```\n\n4\nThis configuration ensures that Vite uses the SvelteKit plugin to resolve module paths and other configurations as it would in your SvelteKit application.\n\nc. Modify your script to use async imports if necessary:\nDepending on what you are importing from $lib or other SvelteKit managed directories, you might need to adjust how imports are handled:\n\n5\n\n```\n// Example using dynamic import\n(async () => {\n const { myFunction } = await import('$lib/myLibModule');\n myFunction();\n})();\n```\n\n6 Add a script to package.json:\nAdd a command in your package.json to run your script through Vite:\n\n```\n\"scripts\": {\n \"run-script\": \"vite build --config vite.config.script.js && node ./out/myscript.js\"\n}\n```\n\n7\n\n```\nnpm run run-script\n```\n\nThis setup ensures that your Node.js script can use all SvelteKit-specific aliases and functionalities, except those that are strictly browser-specific (like navigator or DOM APIs).\n\nLimitations and Considerations:\nEnvironment Variables: Ensure that environment variables used by $env are available in the Node.js runtime environment when the script is executed.\nBrowser-Specific APIs: Clearly, APIs that depend on a browser context won't work in this setup and should either be mocked or avoided.\n\n========================================\n\nCode:\n```bash\nnode src/scripts/myscript.js   # How can import $lib here\n```\n\n```text\n$lib\n```\n\n```text\n$env\n```\n\n```bash\nnpx vite-node src/scripts/my-sveltekit-script.js\n```\n\n```text\nprocess.env\n```\n\n```text\nnpm install --save-dev esbuild vite\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport { sveltekit } from '@sveltejs/kit/vite';\n\nexport default defineConfig({\n  plugins: [sveltekit()],\n  build: {\n    outDir: './out',\n    rollupOptions: {\n      input: './src/scripts/myscript.js'\n    }\n  }\n});\n```\n\n```text\n// Example using dynamic import\n(async () => {\n  const { myFunction } = await import('$lib/myLibModule');\n  myFunction();\n})();\n```\n\n```text\n\"scripts\": {\n  \"run-script\": \"vite build --config vite.config.script.js && node ./out/myscript.js\"\n}\n```\n\n```text\nnpm run run-script\n```\n\n```text\nesrun\n```\n\n```text\ndotenv\n```\n\n```text\n$env\n```\n\n```text\ndotenv\n```\n\n```text\n$env\n```\n\n========================================\n\nComments:\n- `$lib` is just an alias. Not sure how exactly `$env` is implemented.\n- I wanted to access private environment variables in my server-side scripts using the regular `$env` accessor, and found the option `vite-node --options.transformMode.ssr='&#47;.*&#47;' src&#47;scripts&#47;my-script.js` thanks to this github discussion: github.com/sveltejs/kit/discussions/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:46.430Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":172,"estimatedTokens":965}}479{"id":"stack-75907894","source":"stackoverflow","questionId":75907894,"title":"Yarn workspace dependency isn't updated in vite cache","tags":["node-modules","vite","yarn-workspaces"],"text":"Title: Yarn workspace dependency isn't updated in vite cache\nTags: node-modules, vite, yarn-workspaces\nSource: Stack Overflow\n\nQuestion:\nTLDR: Vite is not updating workspace dependencies in the `node_modules/.vite` cache.\n\nI am running a vite server locally and use yarn workspaces to organise my project.\n\nMy (simplified) directory:\n\n```\nweb/ # @my_app workspace\n frontend/ # @my_app/frontend workspace\n App.tsx\n node_modules/\n .vite/ # the vite cache\n backend/\n shared/\n foo.ts\n```\n\nIn the frontend I use constants defined in `shared/foo.ts`.\n\nIf I define a new constant `export const bar = 1` in `foo.ts`, try to import it from `App.tsx`, and run `vite` locally, I get the following error:\n\n```\nUncaught SyntaxError: The requested module '/node_modules/.vite/deps/@my_app_foo.js?v=cccdb61c' does not provide an export named 'bar' (at App.tsx)\n```\n\nIndeed, if I check the file `/node_modules/.vite/deps/@my_app_foo.js`, I can see it's not updated with my latest changes.\n\nHow do I make vite update the cached dependency when I make changes?\n\nNote: The concerned dependencies don't change very often, so they don't need to be hot-reloaded on update (just need the cache to be up-to-date when I run vite).\n\n========================================\n\nCode:\n```text\nweb/              # @my_app workspace\n  frontend/       # @my_app/frontend workspace\n    App.tsx\n    node_modules/\n      .vite/      # the vite cache\n  backend/\n  shared/\n    foo.ts\n```\n\n```text\nUncaught SyntaxError: The requested module '/node_modules/.vite/deps/@my_app_foo.js?v=cccdb61c' does not provide an export named 'bar' (at App.tsx)\n```\n\n```text\nnode_modules/.vite\n```\n\n```text\nshared/foo.ts\n```\n\n```text\nexport const bar = 1\n```\n\n```text\nfoo.ts\n```\n\n```text\nApp.tsx\n```\n\n```text\nvite\n```\n\n```text\n/node_modules/.vite/deps/@my_app_foo.js\n```\n\n```js\nexport default defineConfig({\n  optimizeDeps: { exclude: ['@my_app'] },\n  // ...\n});\n```\n\n```text\nnode_modules/.vite/deps\n```\n\n```text\nvite --force\n```\n\n```text\nnode_modules/.vite\n```\n\n```text\nnode_modules/.vite/deps_temp\n```\n\n```text\ndeps\n```\n\n```text\nvite.config.js\n```\n\n```text\n@my_app\n```\n\n```text\nnode_modules/.vite\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.430Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":120,"estimatedTokens":537}}480{"id":"stack-76070899","source":"stackoverflow","questionId":76070899,"title":"Nuxt 3 + Vite fails to build because of fsevents.node","tags":["node.js","vite","nuxt3.js"],"text":"Title: Nuxt 3 + Vite fails to build because of fsevents.node\nTags: node.js, vite, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nAfter updating Nuxt to 3.4.2 and types/node to 18.15.13 I get the following error when trying to build:\n\nnpm run dev:\n\n```\n✘ [ERROR] No loader is configured for \".node\" files: node_modules/fsevents/fsevents.node\n\n node_modules/fsevents/fsevents.js:13:23:\n 13 │ const Native = require(\"./fsevents.node\");\n ╵ ~~~~~~~~~~~~~~~~~\n\n ERROR [unhandledRejection] Build failed with 1 error: 9:03:37 AM\nnode_modules/fsevents/fsevents.js:13:23: ERROR: No loader is configured for \".node\" files: node_modules/fsevents/fsevents.node\n\n node_modules/fsevents/fsevents.js:13:23: ERROR: No loader is configured for \".node\" files: node_modules/fsevents/fsevents.node\n at failureErrorWithLog (node_modules/esbuild/lib/main.js:1636:15)\n at node_modules/esbuild/lib/main.js:1048:25\n at node_modules/esbuild/lib/main.js:1512:9\n at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n```\n\nThis is the package.json:\n\n```\n\"private\": true,\n \"scripts\": {\n \"build\": \"nuxt build\",\n \"dev2\": \"nuxt dev\",\n \"dev\": \"NODE_TLS_REJECT_UNAUTHORIZED=0 nuxt dev --https --ssl-cert localhost.pem --ssl-key localhost-key.pem\",\n \"generate\": \"nuxt generate\",\n \"preview\": \"nuxt preview\",\n \"postinstall\": \"nuxt prepare\"\n },\n \"devDependencies\": {\n \"@fortawesome/fontawesome-free\": \"^6.2.1\",\n \"@types/node\": \"^18.15.11\",\n \"nuxt\": \"^3.4.0\",\n \"sass\": \"^1.57.1\",\n \"vue-gtag-next\": \"^1.14.0\",\n \"vue-sound\": \"^0.1.10\"\n },\n \"dependencies\": {\n \"@mdi/font\": \"^7.1.96\",\n \"@storyblok/nuxt\": \"^5.3.4\",\n \"@vueuse/core\": \"^9.11.1\",\n \"gsap\": \"^3.11.5\",\n \"vuetify\": \"^3.1.14\"\n }\n}\n```\n\nI tried cleaning cache and deleting node_modules but a fresh install did not solve this.\n\n========================================\n\nCode:\n```text\n✘ [ERROR] No loader is configured for \".node\" files: node_modules/fsevents/fsevents.node\n\n    node_modules/fsevents/fsevents.js:13:23:\n      13 │ const Native = require(\"./fsevents.node\");\n         ╵                        ~~~~~~~~~~~~~~~~~\n\n\n ERROR  [unhandledRejection] Build failed with 1 error:                                                                                                     9:03:37 AM\nnode_modules/fsevents/fsevents.js:13:23: ERROR: No loader is configured for \".node\" files: node_modules/fsevents/fsevents.node\n\n  node_modules/fsevents/fsevents.js:13:23: ERROR: No loader is configured for \".node\" files: node_modules/fsevents/fsevents.node\n  at failureErrorWithLog (node_modules/esbuild/lib/main.js:1636:15)\n  at node_modules/esbuild/lib/main.js:1048:25\n  at node_modules/esbuild/lib/main.js:1512:9\n  at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n```\n\n```text\n\"private\": true,\n  \"scripts\": {\n    \"build\": \"nuxt build\",\n    \"dev2\": \"nuxt dev\",\n    \"dev\": \"NODE_TLS_REJECT_UNAUTHORIZED=0 nuxt dev --https --ssl-cert localhost.pem --ssl-key localhost-key.pem\",\n    \"generate\": \"nuxt generate\",\n    \"preview\": \"nuxt preview\",\n    \"postinstall\": \"nuxt prepare\"\n  },\n  \"devDependencies\": {\n    \"@fortawesome/fontawesome-free\": \"^6.2.1\",\n    \"@types/node\": \"^18.15.11\",\n    \"nuxt\": \"^3.4.0\",\n    \"sass\": \"^1.57.1\",\n    \"vue-gtag-next\": \"^1.14.0\",\n    \"vue-sound\": \"^0.1.10\"\n  },\n  \"dependencies\": {\n    \"@mdi/font\": \"^7.1.96\",\n    \"@storyblok/nuxt\": \"^5.3.4\",\n    \"@vueuse/core\": \"^9.11.1\",\n    \"gsap\": \"^3.11.5\",\n    \"vuetify\": \"^3.1.14\"\n  }\n}\n```\n\n```text\n//nuxt.config.ts\n\nexport default defineNuxtConfig({\n  //...\n  \n  vite: {\n    //...\n    optimizeDeps: { exclude: [\"fsevents\"] },\n  }\n})\n```\n\n========================================\n\nComments:\n- I found a solution for React that worked for nuxt: Add fsevents to your Vite optimizeDeps exclude: (In nuxt.config.ts) optimizeDeps: { exclude: [\"fsevents\"] }, stackoverflow.com/questions/75640753/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:46.430Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":124,"estimatedTokens":957}}481{"id":"stack-79491725","source":"stackoverflow","questionId":79491725,"title":"Why does `npm create vite@latest my-app -- --template react -y` trigger the npm warning: \"Unknown CLI config --template\"?","tags":["javascript","reactjs","node.js","npm","vite"],"text":"Title: Why does `npm create vite@latest my-app -- --template react -y` trigger the npm warning: \"Unknown CLI config --template\"?\nTags: javascript, reactjs, node.js, npm, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a new React app using Vite with the following command from Vite official site:\n\n```\nnpm create vite@latest my-react-js-app -- --template react -y\n```\n\nHowever, I get this warning:\n\nnpm WARN Unknown cli config \"--template\"\n\nThe command does not execute as expected. How can I fix this issue?\n\nSystem details:\n\n- Node.js version: v22.14.0\n\n- NPM version: v11.2.0\n\n- OS: Windows 10 Pro\n\n- Vite: v6.2.0\n\nI also tried running:\n\n```\nnpm create vite@latest my-react-js-app --template react\n```\n\nbut the issue persists.\n\nHow can I resolve this and properly create a Vite React project in a single command without being prompted to select the framework (vanilla, Vue, React, etc.) and the variant (JavaScript or TypeScript) I want to use for my app?\n\n========================================\n\nTop Answer:\nTry using `npx` instead of `npm`:\n\n```\nnpx create-vite@latest my-react-js-app --template react\n```\n\n### **Alternative (Explicit Way)**\n\nIf `npm create vite` still causes issues, you can use `yarn` or `pnpm`:\n\n### **Using Yarn**\n\n```\nyarn create vite my-react-js-app --template react\n```\n\n### **Using pnpm**\n\n```\npnpm create vite my-react-js-app --template react\n```\n\n### **Force Clearing NPM Cache**\n\nIf the issue persists, try clearing your npm cache:\n\n```\nnpm cache clean --force\n```\n\nThen retry the command.\n\n### **Ensure Compatibility**\n\nYour Node.js (v22.14.0) is very new, and there might be compatibility issues. Try downgrading to **Node.js v20** (LTS) using nvm or nvm-windows:\n\n```\nnvm install 20\nnvm use 20\n```\n\nThen, rerun the command.\n\n========================================\n\nCode:\n```none\nnpm create vite@latest my-react-js-app -- --template react -y\n```\n\n```none\nnpm create vite@latest my-react-js-app --template react\n```\n\n```none\nnpm create vite@latest my-react-js-app --- --template react -y\n```\n\n```text\nnpm\n```\n\n```text\nnpm create vite@latest my-react-js-app\n```\n\n```text\nnpx create-vite@latest my-app-name --template react\n```\n\n```bash\nnpx create-vite@latest my-react-js-app --template react\n```\n\n```bash\nyarn create vite my-react-js-app --template react\n```\n\n```bash\npnpm create vite my-react-js-app --template react\n```\n\n```bash\nnpm cache clean --force\n```\n\n```bash\nnvm install 20\nnvm use 20\n```\n\n```text\nnpx\n```\n\n```text\nnpm\n```\n\n```text\nnpm create vite\n```\n\n```text\nyarn\n```\n\n```text\npnpm\n```\n\n```none\n# Check your NPM version\nnpm -v\n\n# Update NPM to the latest version\nnpm install -g npm\n\n# Or update to a specific version (example: 11.4.0)\nnpm install -g npm@11.4.0\n```\n\n```text\nnpm/cli\n```\n\n========================================\n\nComments:\n- The bug was patched in the fixes shipped with versions v11.4.0 and v10.9.3, reference: stackoverflow.com/a/79832612/15167500\n- *\"...without being prompted to select the framework\"*\n- You wrote in the question that it doesn't work.\n- Both commands are slightly different if you look at the question and the answer.\n- As you can find in the documentation, `npm create` is an alias for `npm init` and `npm create vite@latest my-react-js-app --template react` is the same as `npx create-vite@latest my-app-name --template react` docs.npmjs.com/cli/v11/commands/npm-init#synopsis\n- Ok i have no idea about this. But how how it worked for me when i use that command insted of the command is in the question.\n- Where did you copy the quote from? I'm just asking for source tracking.\n- The questions contains *\"I also tried running: `npm create vite@latest my-react-js-app --template react`\"* Isn't that the first paragraph in your answer?\n- solution with `npx` worked fine. This should have been the solution, in my opinion. What type of syntax is this --- -- that @papeto suggests? Look more like Morse code.\n- @user16540390 He used `npx` not `npm`. I t solved the problem in my case without producing any warnings.\n- This works now, and it did not work before: github.com/npm/cli/pull/8278\n- Too many tries. This is more of a guess.\n- @rozsazoltan Probably an AI-generated reply\n- What kind of Morse code is this ? --- -- Solution should have been by using `npx` instead which is pretty straight forward.\n- @VaggelisManousakis In this case `npm create` is equivalent to `npx`: docs.npmjs.com/cli/v11/commands/npm-init#synopsis. Btw, it seems like `--` works now, but when I answered this question, both `npx` and `npm create` with double dash does not work. Also, the double dash is literally in vite's documentation, under \"Using create vite with command line options\": vite.dev/guide/#scaffolding-your-first-vite-project\n- I get what documentation says and your response is valid, but it is way simpler to type `npx create-vite@latest my-react-js-app --template react -y` so I suggest you edit your answer so it's up-to-date and people can find it useful since it's working normally now.\n- @VaggelisManousakis (Stackoverflow does not allow level 4 replies) There is no reason to introduce `npx` to answer this question. I do not think we should mention it even if it is more ergonomic.","metadata":{"transformedAt":"2026-08-18T18:33:46.431Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":186,"estimatedTokens":1296}}482{"id":"stack-78239356","source":"stackoverflow","questionId":78239356,"title":"Adding Submodule Paths in a Vite React Library","tags":["javascript","reactjs","typescript","webpack","vite"],"text":"Title: Adding Submodule Paths in a Vite React Library\nTags: javascript, reactjs, typescript, webpack, vite\nSource: Stack Overflow\n\nQuestion:\nI have a Vite-based React library, currently structured like this:\n\n```\nimport { Button, Typography, Box, Flex, Color, TypographyVariant } from '@placeholder-library';\n```\n\nI want to separate the imports to add submodules so that components and shared are imported from different paths:\n\n```\nimport { Button, Typography, Box, Flex } from '@placeholder-library/components’;\nimport { Color, TypographyVariant } from ‘@placeholder-library/shared’;\n```\n\n**index.ts**\n\n```\nimport './index.scss';\nexport * from './components';\nexport * from './shared';\n```\n\n**vite.config.ts:**\n\n```\nimport react from '@vitejs/plugin-react';\nimport path from 'path';\nimport { defineConfig } from 'vite';\nimport dts from 'vite-plugin-dts';\nimport svgr from 'vite-plugin-svgr';\nimport tsconfigPaths from 'vite-tsconfig-paths';\nimport commonjs from 'vite-plugin-commonjs';\n\nexport default defineConfig({\n resolve: {\n alias: {\n src: path.resolve(__dirname, './src'),\n },\n },\n build: {\n outDir: 'build',\n lib: {\n entry: './src/index.ts',\n name: 'Placeholder Library',\n fileName: 'index',\n },\n rollupOptions: {\n external: ['react', 'react-dom'],\n output: [\n {\n globals: {\n react: 'React',\n 'react-dom': 'ReactDOM',\n },\n },\n {\n dir: 'build/cjs',\n format: 'cjs',\n globals: {\n react: 'React',\n 'react-dom': 'ReactDOM',\n },\n },\n {\n dir: 'build/esm',\n format: 'esm',\n globals: {\n react: 'React',\n 'react-dom': 'ReactDOM',\n },\n },\n ],\n },\n sourcemap: true,\n emptyOutDir: true,\n },\n plugins: [\n svgr(),\n react(),\n commonjs(),\n tsconfigPaths(),\n dts({\n outDir: ['build/cjs', 'build/esm', 'build'],\n include: ['./src/**/*'],\n exclude: ['**/*.stories.*'],\n }),\n ],\n});\n```\n\npackage.json:\n\n```\n{\n \"name\": \"@placeholder-library\",\n \"version\": \"0.0.26\",\n \"description\": \"Placeholder Library components library\",\n \"license\": \"ISC\",\n \"main\": \"build/cjs/index.js\",\n \"module\": \"build/index.mjs\",\n \"files\": [\"*\"],\n \"scripts\": {\n \"build\": \"tsc && vite build\",\n \"build-storybook\": \"storybook build\",\n \"build-storybook-docs\": \"storybook build --docs\",\n \"dev\": \"vite\",\n \"format\": \"prettier --write .\",\n \"lint:fix\": \"eslint . --fix --ignore-path .gitignore\",\n \"prepare\": \"husky install\",\n \"preview\": \"vite preview\",\n \"storybook\": \"storybook dev -p 6006\",\n \"storybook-docs\": \"storybook dev --docs\"\n },\n \"dependencies\": {\n \"...\"\n },\n \"devDependencies\": {\n \"...\"\n },\n \"peerDependencies\": {\n \"react\": \"^18.2.0\"\n }\n}\n```\n\nmy folder structure:\nMy folder structure\n\n```\nsrc\n index.ts\n components\n index.ts\n Button\n index.ts\n shared\n hooks\n index.ts\n```\n\nindex.ts in components:\n\n```\nexport * from './Button'\n```\n\nHow can I configure Vite and my package structure to achieve this separation of components and shared/utils? Any advice or examples would be greatly appreciated.\n\nI attempted to modify the **`vite.config.ts`** file to include separate entries for components and shared/utils, but I couldn't figure out how to properly configure the paths. I also tried to adjust the **`package.json`** file to specify different entry points for components and shared/utils, but I wasn't sure how to structure it correctly.\n\n`import { Button, Typography, Box, Flex } from '@placeholder-library/components’;`\n\n`import { Color, TypographyVariant } from ‘@placeholder-library/shared’;`\n\nHowever, I couldn't find a clear example or documentation on how to set this up in a Vite-based React library. Any guidance or examples on how to achieve this would be greatly appreciated.\n\n========================================\n\nCode:\n```text\nimport { Button, Typography, Box, Flex, Color, TypographyVariant } from '@placeholder-library';\n```\n\n```text\nimport { Button, Typography, Box, Flex } from '@placeholder-library/components’;\nimport { Color, TypographyVariant } from ‘@placeholder-library/shared’;\n```\n\n```text\nimport './index.scss';\nexport * from './components';\nexport * from './shared';\n```\n\n```text\nimport react from '@vitejs/plugin-react';\nimport path from 'path';\nimport { defineConfig } from 'vite';\nimport dts from 'vite-plugin-dts';\nimport svgr from 'vite-plugin-svgr';\nimport tsconfigPaths from 'vite-tsconfig-paths';\nimport commonjs from 'vite-plugin-commonjs';\n\nexport default defineConfig({\n  resolve: {\n    alias: {\n      src: path.resolve(__dirname, './src'),\n    },\n  },\n  build: {\n    outDir: 'build',\n    lib: {\n      entry: './src/index.ts',\n      name: 'Placeholder Library',\n      fileName: 'index',\n    },\n    rollupOptions: {\n      external: ['react', 'react-dom'],\n      output: [\n        {\n          globals: {\n            react: 'React',\n            'react-dom': 'ReactDOM',\n          },\n        },\n        {\n          dir: 'build/cjs',\n          format: 'cjs',\n          globals: {\n            react: 'React',\n            'react-dom': 'ReactDOM',\n          },\n        },\n        {\n          dir: 'build/esm',\n          format: 'esm',\n          globals: {\n            react: 'React',\n            'react-dom': 'ReactDOM',\n          },\n        },\n      ],\n    },\n    sourcemap: true,\n    emptyOutDir: true,\n  },\n  plugins: [\n    svgr(),\n    react(),\n    commonjs(),\n    tsconfigPaths(),\n    dts({\n      outDir: ['build/cjs', 'build/esm', 'build'],\n      include: ['./src/**/*'],\n      exclude: ['**/*.stories.*'],\n    }),\n  ],\n});\n```\n\n```text\n{\n  \"name\": \"@placeholder-library\",\n  \"version\": \"0.0.26\",\n  \"description\": \"Placeholder Library components library\",\n  \"license\": \"ISC\",\n  \"main\": \"build/cjs/index.js\",\n  \"module\": \"build/index.mjs\",\n  \"files\": [\"*\"],\n  \"scripts\": {\n    \"build\": \"tsc && vite build\",\n    \"build-storybook\": \"storybook build\",\n    \"build-storybook-docs\": \"storybook build --docs\",\n    \"dev\": \"vite\",\n    \"format\": \"prettier --write .\",\n    \"lint:fix\": \"eslint . --fix --ignore-path .gitignore\",\n    \"prepare\": \"husky install\",\n    \"preview\": \"vite preview\",\n    \"storybook\": \"storybook dev -p 6006\",\n    \"storybook-docs\": \"storybook dev --docs\"\n  },\n  \"dependencies\": {\n    \"...\"\n  },\n  \"devDependencies\": {\n    \"...\"\n  },\n  \"peerDependencies\": {\n    \"react\": \"^18.2.0\"\n  }\n}\n```\n\n```text\nsrc\n    index.ts\n    components\n        index.ts\n        Button\n            index.ts\n    shared\n        hooks\n        index.ts\n```\n\n```text\nexport * from './Button'\n```\n\n```text\nvite.config.ts\n```\n\n```text\npackage.json\n```\n\n```text\nimport { Button, Typography, Box, Flex } from '@placeholder-library/components’;\n```\n\n```text\nimport { Color, TypographyVariant } from ‘@placeholder-library/shared’;\n```\n\n```text\nimport { Button } from \"placeholder-lib/components\";\nimport useMyHook from \"placeholder-lib/shared\";\n```\n\n```text\n\"exports\": {\n    \".\": \"./dist/index.js\",\n    \"./components\": \"./dist/components/index.js\",\n    \"./shared\": \"./dist/shared/index.js\"\n  },\n```\n\n```text\ndist/\n```\n\n```text\nplaceholder-lib\n```\n\n```text\nconsumer\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- Can you provide a link to your project? `entry` can also be an object and you can use `exports` in your package.json to expose the different entry points.\n- Could you clarify what are submodules? Are they the same npm package but in different folders? And what is the problem with 2 import statements that you are using?\n- @morganney unfortunately I can't add this library, what files do you need? I can add\n- @quyentho that's what I want to achieve. now I can import only with the full path without submodules, when i try @placeholder-library/components / @placeholder-library/shared it not find the imports\n- @Manspof Is it possible to the @placeholder package name? Is it your own code or a private package? Because I believe this can be easily achieved by create 2 index.js files in `&#47;shared` and `&#47;components` folders to export everything you need.\n- @quyentho it's my private package of the company, I really can't github link so I changed.. let me know what files you need or anything I can try to add\n- @Manspof If you have access to change code in that private repo, simply add 2 index.js files in each folder. Then in each index.js file, you `export * from \".&#47;file-in-that-modules.js\"`. Then, you can import each component using the folder names.\n- If you don't have access to that private repo. You can still do the trick by re-export the modules in your own code, but now the path gonna be e.g `import {Button} from '@yourcode&#47;components'`. Let me know if that makes sense.\n- @quyentho yes I have an access to code, I wrote this library.. I already have those index files for each folder then in the first index.js I export both of them.. I think the change should be in the package.json entry and exports and not into the code/folder structure..\n- Sorry but I think you did it incorrectly. Could you the index.js files in `@placeholder-lib&#47;components` and `@placeholder-lib&#47;shared`?\n- Yes I added in my post\n- Let us continue this discussion in chat.\n- Thank you so much for your help @quyentho ! Your solution was exactly what I needed, and the code example you provided was clear and worked perfectly. I really appreciate your expertise and the time you took to assist me. You've made a big difference in my project! 😊\n- when I add testing it not recognize with submodules, only this way: import { Button } from \"placeholder-lib\".. do you know why?\n- You probably are facing the problem with jest preset. I just pushed new code which include test in the repo above. Look into `package.json` to find the `jest` config section and you'll also need to set `allowJs: true` in `tsconfig.json`. A cleaner way to not mess up your `tsconfig.json` in your main app is to create a new one only for jest, here is how to do it: huafu.github.io/ts-jest/user/config/tsConfig","metadata":{"transformedAt":"2026-08-18T18:33:46.431Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":356,"estimatedTokens":2432}}483{"id":"stack-77925590","source":"stackoverflow","questionId":77925590,"title":"deploy vite react app on azure webapp service or any alternative","tags":["reactjs","azure","azure-web-app-service","vite"],"text":"Title: deploy vite react app on azure webapp service or any alternative\nTags: reactjs, azure, azure-web-app-service, vite\nSource: Stack Overflow\n\nQuestion:\nI have been working on two Vite React apps and everything went smoothly until I was asked to deploy these apps on Azure. I tried to deploy them, but it wasn't a success. I came to discover that React apps that were built with Create React App are supported, but not Vite React apps. However, I know it's not impossible since I've heard many times that it's doable. The question is, how?\n\nI tried to SSH to my web app but I couldn't find a way to clone my github repo I when I first started in uploaded my files normally with azure deployment normal steps but when I try to upload it again to see my files when I SSH it will give me an error\n\n========================================\n\nTop Answer:\nAccepted answer is not going to work with routing on Azure Static Web App.\n\nTo make vite with routing work, the pipeline build configuration needs to be different and also a `staticwebapp.config.json` file is needed.\n\n`The pipeline build configuration for the Build And Deploy`\n\n```\napp_location: \"/\" # App source code path\napi_location: \"\" # Api source code path - optional\noutput_location: \"dist\" # Built app content directory - optional\n```\n\n`staticwebapp.config.json` in the root of your project\n\n```\n{\n \"navigationFallback\": {\n \"rewrite\": \"/index.html\",\n \"exclude\": [\"/api/*\"]\n }\n}\n```\n\n========================================\n\nCode:\n```bash\nC:\\Users\\Vivek\\Desktop\\VS Code Floders>npm create vite@latest my-react-app --template\nNeed to install the following packages:\ncreate-vite@5.1.0\nOk to proceed? (y) y\n√ Select a framework: » React\n√ Select a variant: » JavaScript\n\nScaffolding project in C:\\Users\\Vivek\\Desktop\\VS Code Floders\\my-react-app...\n\nDone. Now run:\n\n  cd my-react-app\n  npm install\n  npm run dev #for running locally\n```\n\n```bash\ncd my-react-app\n  npm install\n  npm run build #it will create a dist folder.\n```\n\n```json\n{\n  \"name\": \"my-react-app\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"lint\": \"eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0\",\n    \"preview\": \"vite preview\"\n  },\n  \"engines\": {\n    \"node\": \">=18.0.0\"\n  },\n  \"dependencies\": {\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^18.2.43\",\n    \"@types/react-dom\": \"^18.2.17\",\n    \"@vitejs/plugin-react\": \"^4.2.1\",\n    \"eslint\": \"^8.55.0\",\n    \"eslint-plugin-react\": \"^7.33.2\",\n    \"eslint-plugin-react-hooks\": \"^4.6.0\",\n    \"eslint-plugin-react-refresh\": \"^0.4.5\",\n    \"vite\": \"^5.0.8\"\n  }\n}\n```\n\n```yaml\nname: Azure Static Web Apps CI/CD\n\non:\n  push:\n    branches:\n      - main\n  pull_request:\n    types: [opened, synchronize, reopened, closed]\n    branches:\n      - main\n\njobs:\n  build_and_deploy_job:\n    if: github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.action != 'closed')\n    runs-on: ubuntu-latest\n    name: Build and Deploy Job\n    steps:\n      - uses: actions/checkout@v3\n        with:\n          submodules: true\n          lfs: false\n      - name: Build And Deploy\n        id: builddeploy\n        uses: Azure/static-web-apps-deploy@v1\n        with:\n          azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_LIVELY_GROUND_00661FE10 }}\n          repo_token: ${{ secrets.GITHUB_TOKEN }} \n          action: \"upload\"\n          app_location: \"/dist\" \n          api_location: \"\" \n          output_location: \"\" \n          \n\n  close_pull_request_job:\n    if: github.event_name == 'pull_request' && github.event.action == 'closed'\n    runs-on: ubuntu-latest\n    name: Close Pull Request Job\n    steps:\n      - name: Close Pull Request\n        id: closepullrequest\n        uses: Azure/static-web-apps-deploy@v1\n        with:\n          azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_LIVELY_GROUND_00661FE10 }}\n          action: \"close\"\n```\n\n```bash\nZipping App Artifacts\nDone Zipping App Artifacts\nUploading build artifacts.\nFinished Upload. Polling on deployment.\nStatus: InProgress. Time: 0.0626303(s)\nStatus: InProgress. Time: 15.1233542(s)\nStatus: Succeeded. Time: 30.1727089(s)\nDeployment Complete :)\nVisit your site at: https://lively-ground-00661fe10.4.azurestaticapps.net\nThanks for using Azure Static Web Apps!\nExiting\n```\n\n```text\nnpm create vite@latest my-react-app --template\n```\n\n```text\nGitHub\n```\n\n```text\ndist\n```\n\n```text\nGitHub\n```\n\n```text\n/dist\n```\n\n```text\nengines\n```\n\n```text\npackage.json\n```\n\n```text\nGitHub\n```\n\n```text\npackage.json\n```\n\n```text\nazure-static-web-apps-lively-ground-00661fe10.yml\n```\n\n```text\nOUTPUT\n```\n\n```text\napp_location: \"/\" # App source code path\napi_location: \"\" # Api source code path - optional\noutput_location: \"dist\" # Built app content directory - optional\n```\n\n```text\n{\n  \"navigationFallback\": {\n    \"rewrite\": \"/index.html\",\n    \"exclude\": [\"/api/*\"]\n  }\n}\n```\n\n```text\nstaticwebapp.config.json\n```\n\n```text\nThe pipeline build configuration for the Build And Deploy\n```\n\n```text\nstaticwebapp.config.json\n```\n\n========================================\n\nComments:\n- Did you followed the Deploying a Static Site - Azure Static Web App documentation? I don't know Vite React framework, but if the build result is a static site (in relation to server side workload), then it must be deployed as Static Web App and not as standard Web App.\n- yes I did... multiple times\n- Are you trying to deploy on your local machine or using Azure DevOps? Based on your description, you web apps work fine locally, you can try to use Azure CLI to deploy to Azure Static Web App.\n- @ZiyangLiu-MSFT error: App Directory Location: '/' was found. Try to validate location at: '/github/workspace/swa-db-connections'. Looking for event info The content server has rejected the request with: BadRequest Reason: No matching Static Web App was found or the api key was invalid. For further information, please visit the Azure Static Web Apps documentation at docs.microsoft.com/en-us/azure/static-web-apps If you believe this behavior is unexpected, please raise a GitHub issue at github.com/azure/static-web-apps/issues Exiting\n- Consider not adding your `dist` folder to source control. It will be automatically generated during deployment using the `Azure&#47;static-web-apps-deploy@v1` step in your workflow. Also remeber to add staticwebapp.config.json","metadata":{"transformedAt":"2026-08-18T18:33:46.431Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":233,"estimatedTokens":1620}}484{"id":"stack-72936035","source":"stackoverflow","questionId":72936035,"title":"How can I use fontawesome icons in a laravel application using vite?","tags":["laravel","vue.js","font-awesome","laravel-blade","vite"],"text":"Title: How can I use fontawesome icons in a laravel application using vite?\nTags: laravel, vue.js, font-awesome, laravel-blade, vite\nSource: Stack Overflow\n\nQuestion:\nI have installed **@fortawesome/fontawesome-free** package using npm. The latest Laravel application uses vite by default. I am unable to solve this issue. Any help would be much appreciated. My **vite.config.js** is\n\n```\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\nimport { viteStaticCopy } from 'vite-plugin-static-copy';\n\nexport default defineConfig({\n plugins: [\n laravel([\n 'resources/css/app.css',\n 'resources/js/app.js',\n 'resources/admin/css/app.css',\n 'resources/admin/js/app.js',\n 'resources/css/glide.css',\n 'resources/js/glide.js',\n 'resources/js/Sortable.js',\n 'resources/js/tinymce.js',\n 'resources/sass/app.scss',\n 'resources/admin/sass/app.scss',\n ]),\n {\n name: 'blade',\n handleHotUpdate({ file, server }) {\n if (file.endsWith('.blade.php')) {\n server.ws.send({\n type: 'full-reload',\n path: '*',\n });\n }\n },\n },\n viteStaticCopy({\n targets: [\n {\n src: 'node_modules/@fortawesome/fontawesome-free/webfonts',\n dest: '',\n },\n ],\n }),\n ],\n});\n```\n\nI imported fontawesome scss files in **app.scss**. My **app.scss** file contains\n\n```\n@import \"@fortawesome/fontawesome-free/scss/fontawesome\";\n@import \"@fortawesome/fontawesome-free/scss/brands\";\n@import \"@fortawesome/fontawesome-free/scss/regular\";\n@import \"@fortawesome/fontawesome-free/scss/solid\";\n@import \"@fortawesome/fontawesome-free/scss/v4-shims\";\n```\n\nI tried using a third party library **https://github.com/sapphi-red/vite-plugin-static-copy** to copy webfonts of fontawesome package. Is there a better way than this?\n\n========================================\n\nTop Answer:\nin **Laravel 9 OR Above**, by default Laravel use Vite to bundle your application's CSS and JavaScript files into production ready assets.\n\nNow if you need to use FontAwesome with Vite in laravel then you can do it as below way.\n\nStep 1:- Run `npm i @fortawesome/fontawesome-free` command for install Font Awesome. by running above command fontawesome will be installed in **\"node_modules\" directory** (full path:- {root_dir}/node_modules/@fortawesome/fontawesome-free).\n\nStep 2:- Open `{root_dir}/vite.config.js` file and add below path in this file\n\n```\nexport default defineConfig({\n plugins: [\n laravel({\n input: [\n 'resources/sass/app.scss',\n 'resources/js/app.js',\n ],\n refresh: true,\n }),\n ],\n resolve: {\n alias: {\n '~bootstrap': path.resolve(__dirname, 'node_modules/bootstrap'),\n // add below path of fontawesome\n '~fontawesome': path.resolve(__dirname, 'node_modules/@fortawesome/fontawesome-free'), // Step 3:- Now open `{root_dir}/resources/sass/app.scss` file & import fontawesome scss as like below\n\n```\n// Bootstrap\n@import 'bootstrap/scss/bootstrap';\n\n// for FontAwesome v6+\n$fa-font-path: '~fontawesome/webfonts';\n@import '~fontawesome/scss/fontawesome';\n@import '~fontawesome/scss/brands';\n@import '~fontawesome/scss/solid';\n```\n\nNote that, in last step we import the fontawesome files. but that import path may different. here currently I used latest version (6.4) of FontAwesome. Refer this for more read about \"how to use fontAwesome with Sass\"\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\nimport { viteStaticCopy } from 'vite-plugin-static-copy';\n\nexport default defineConfig({\n    plugins: [\n        laravel([\n            'resources/css/app.css',\n            'resources/js/app.js',\n            'resources/admin/css/app.css',\n            'resources/admin/js/app.js',\n            'resources/css/glide.css',\n            'resources/js/glide.js',\n            'resources/js/Sortable.js',\n            'resources/js/tinymce.js',\n            'resources/sass/app.scss',\n            'resources/admin/sass/app.scss',\n        ]),\n        {\n            name: 'blade',\n            handleHotUpdate({ file, server }) {\n                if (file.endsWith('.blade.php')) {\n                    server.ws.send({\n                        type: 'full-reload',\n                        path: '*',\n                    });\n                }\n            },\n        },\n        viteStaticCopy({\n            targets: [\n                {\n                    src: 'node_modules/@fortawesome/fontawesome-free/webfonts',\n                    dest: '',\n                },\n            ],\n        }),\n    ],\n});\n```\n\n```text\n@import \"@fortawesome/fontawesome-free/scss/fontawesome\";\n@import \"@fortawesome/fontawesome-free/scss/brands\";\n@import \"@fortawesome/fontawesome-free/scss/regular\";\n@import \"@fortawesome/fontawesome-free/scss/solid\";\n@import \"@fortawesome/fontawesome-free/scss/v4-shims\";\n```\n\n```text\nnpm install -D sass\n```\n\n```text\nimport './bootstrap';\nimport '@fortawesome/fontawesome-free/scss/fontawesome.scss';\nimport '@fortawesome/fontawesome-free/scss/brands.scss';\nimport '@fortawesome/fontawesome-free/scss/regular.scss';\nimport '@fortawesome/fontawesome-free/scss/solid.scss';\nimport '@fortawesome/fontawesome-free/scss/v4-shims.scss';\n\nimport Alpine from 'alpinejs';\n\nwindow.Alpine = Alpine;\n\nAlpine.start();\n```\n\n```text\n$fa-font-path: '../fontawesome/webfonts';\n```\n\n```text\n@import '../fontawesome/scss/brands';\n@import '../fontawesome/scss/solid';\n@import '../fontawesome/scss/light';\n@import '../fontawesome/scss/fontawesome';\n```\n\n```text\n(/resources/fontawesome)\n```\n\n```text\n/public/build/assets\n```\n\n```text\nexport default defineConfig({\n    plugins: [\n        laravel({\n            input: [\n                'resources/sass/app.scss',\n                'resources/js/app.js',\n            ],\n            refresh: true,\n        }),\n    ],\n    resolve: {\n        alias: {\n            '~bootstrap': path.resolve(__dirname, 'node_modules/bootstrap'),\n            // add below path of fontawesome\n            '~fontawesome': path.resolve(__dirname, 'node_modules/@fortawesome/fontawesome-free'), // <- add this line\n\n        }\n    },\n});\n```\n\n```text\n// Bootstrap\n@import 'bootstrap/scss/bootstrap';\n\n// for FontAwesome v6+\n$fa-font-path: '~fontawesome/webfonts';\n@import '~fontawesome/scss/fontawesome';\n@import '~fontawesome/scss/brands';\n@import '~fontawesome/scss/solid';\n```\n\n```text\nnpm i @fortawesome/fontawesome-free\n```\n\n```text\n{root_dir}/vite.config.js\n```\n\n```text\n{root_dir}/resources/sass/app.scss\n```\n\n```text\nnpm install @fortawesome/fontawesome-free\n```\n\n```text\n@import '@fortawesome/fontawesome-free/js/fontawesome';\n\n@import '@fortawesome/fontawesome-free/js/solid';\n```\n\n```text\n<i class=\"fa-solid fa-sort\"></i>\n```\n\n```text\nimport {defineConfig, preprocessCSS} from 'vite';\nimport laravel from 'laravel-vite-plugin';\nimport * as path from \"path\";\n\nexport default defineConfig({\n    plugins: [\n        laravel({\n            input: ['resources/sass/app.scss', 'resources/js/app.js'],\n            refresh: true,\n        }),\n    ],\n});\n```\n\n========================================\n\nComments:\n- Can you please add error to the question\n- It's specifically /webfonts that needs to be copied to /webfonts public, I expect the rest of the lib to be included by `@import`\n- @parth there is no error. when I run `npm run build`, everything works because I have used **viteStaticCopy** which is a third party plugin. But when I run npm run dev, it cannot find the path at **resources/webfonts/**. I could use the same package in this case too, but I found this way a bit hacky and hoping for a better solution.\n- @EstusFlask yes I copied the **webfonts** using a third-party plugin. But I found this method a bit hacky when using **vite**. I was wondering if there is a better way to solve this issue. When using **laravel mix**, it automatically handles the **webfont** directory. We didn't have to do the extra stuff.\n- stackoverflow.com/a/76139847/14344959","metadata":{"transformedAt":"2026-08-18T18:33:46.431Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":275,"estimatedTokens":1954}}485{"id":"stack-79444735","source":"stackoverflow","questionId":79444735,"title":"how to resolve \"../pkg\" in node_modules","tags":["node.js","vue.js","vite"],"text":"Title: how to resolve \"../pkg\" in node_modules\nTags: node.js, vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nWhile working on a project I suddenly encountered this error. I did not install any packages. Everything was working fine until this error occurred.\n\n```\n\"C:\\Program Files\\nodejs\\npm.cmd\" run dev\n\n> music@0.0.0 dev\n> vite\n\n VITE v6.1.0 ready in 1377 ms\n\n ➜ Local: http://localhost:5173/\n ➜ Network: use --host to expose\n ➜ Vue DevTools: Open http://localhost:5173/__devtools__/ as a separate window\n ➜ Vue DevTools: Press Alt(⌥)+Shift(⇧)+D in App to toggle the Vue DevTools\n ➜ press h + enter to show help\nX [ERROR] Could not resolve \"../pkg\"\n\n node_modules/lightningcss/node/index.js:16:27:\n 16 │ module.exports = require(`../pkg`);\n ╵ ~~~~~~~~\n\nC:\\Users\\PASARGAD\\web_practice\\music\\node_modules\\esbuild\\lib\\main.js:1476\n let error = new Error(text);\n ^\n\nError: Build failed with 1 error:\nnode_modules/lightningcss/node/index.js:16:27: ERROR: Could not resolve \"../pkg\"\n at failureErrorWithLog (C:\\Users\\PASARGAD\\web_practice\\music\\node_modules\\esbuild\\lib\\main.js:1476:15)\n at C:\\Users\\PASARGAD\\web_practice\\music\\node_modules\\esbuild\\lib\\main.js:945:25\n at C:\\Users\\PASARGAD\\web_practice\\music\\node_modules\\esbuild\\lib\\main.js:1354:9\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5) {\n errors: [Getter/Setter],\n warnings: [Getter/Setter]\n}\n\nNode.js v22.12.0\n```\n\nI have tried these ways but to no avail. deleting npm-cach deleting node_moduled deleting package-lock.json ... and npm install I intalling lightningcss based on documentation:\n\n```\nnpm install --save-dev lightningcss\n```\n\nand setting vite setting:\n\n```\nimport { fileURLToPath, URL } from 'node:url'\n```\n\n```\nimport { fileURLToPath, URL } from 'node:url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport vueDevTools from 'vite-plugin-vue-devtools'\nimport tailwindcss from '@tailwindcss/vite'\nimport browserslist from 'browserslist';\nimport {browserslistToTargets} from 'lightningcss';\n// https://vite.dev/config/\nexport default defineConfig({\n plugins: [\n vue(),\n vueDevTools(),\n tailwindcss(),\n ],\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url))\n },\n },\n css: {\n transformer: 'lightningcss',\n lightningcss: {\n targets: browserslistToTargets(browserslist('>= 0.25%'))\n }\n },\n build: {\n cssMinify: 'lightningcss'\n }\n})\n```\n\n========================================\n\nTop Answer:\nAfter hours and hours of efforts,finally it was this stupid line\n\n***import {createLogger} from \"vite\"***\n\nin my one component ,I dont even remember importing it or putting this line there in my component\n\n========================================\n\nCode:\n```text\n\"C:\\Program Files\\nodejs\\npm.cmd\" run dev\n\n> music@0.0.0 dev\n> vite\n\n\n  VITE v6.1.0  ready in 1377 ms\n\n  ➜  Local:   http://localhost:5173/\n  ➜  Network: use --host to expose\n  ➜  Vue DevTools: Open http://localhost:5173/__devtools__/ as a separate window\n  ➜  Vue DevTools: Press Alt(⌥)+Shift(⇧)+D in App to toggle the Vue DevTools\n  ➜  press h + enter to show help\nX [ERROR] Could not resolve \"../pkg\"\n\n    node_modules/lightningcss/node/index.js:16:27:\n      16 │   module.exports = require(`../pkg`);\n         ╵                            ~~~~~~~~\n\nC:\\Users\\PASARGAD\\web_practice\\music\\node_modules\\esbuild\\lib\\main.js:1476\n  let error = new Error(text);\n              ^\n\nError: Build failed with 1 error:\nnode_modules/lightningcss/node/index.js:16:27: ERROR: Could not resolve \"../pkg\"\n    at failureErrorWithLog (C:\\Users\\PASARGAD\\web_practice\\music\\node_modules\\esbuild\\lib\\main.js:1476:15)\n    at C:\\Users\\PASARGAD\\web_practice\\music\\node_modules\\esbuild\\lib\\main.js:945:25\n    at C:\\Users\\PASARGAD\\web_practice\\music\\node_modules\\esbuild\\lib\\main.js:1354:9\n    at process.processTicksAndRejections (node:internal/process/task_queues:105:5) {\n  errors: [Getter/Setter],\n  warnings: [Getter/Setter]\n}\n\nNode.js v22.12.0\n```\n\n```text\nnpm install --save-dev lightningcss\n```\n\n```text\nimport { fileURLToPath, URL } from 'node:url'\n```\n\n```text\nimport { fileURLToPath, URL } from 'node:url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport vueDevTools from 'vite-plugin-vue-devtools'\nimport tailwindcss from '@tailwindcss/vite'\nimport browserslist from 'browserslist';\nimport {browserslistToTargets} from 'lightningcss';\n// https://vite.dev/config/\nexport default defineConfig({\n  plugins: [\n    vue(),\n    vueDevTools(),\n    tailwindcss(),\n  ],\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url))\n    },\n  },\n  css: {\n    transformer: 'lightningcss',\n    lightningcss: {\n      targets: browserslistToTargets(browserslist('>= 0.25%'))\n    }\n  },\n  build: {\n    cssMinify: 'lightningcss'\n  }\n})\n```\n\n```text\nimport { createLogger } from 'vite'\n```\n\n========================================\n\nComments:\n- I'm using tailwind css v4 and I'm not encountered with any error any more. I fixed this with creating a new project with vite and copying file to new project. thanks for contributing","metadata":{"transformedAt":"2026-08-18T18:33:46.431Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":186,"estimatedTokens":1265}}486{"id":"stack-73152229","source":"stackoverflow","questionId":73152229,"title":"How to keep an absolute path unchanged for a script tag in index.html with Vite","tags":["javascript","html","vite","rollupjs"],"text":"Title: How to keep an absolute path unchanged for a script tag in index.html with Vite\nTags: javascript, html, vite, rollupjs\nSource: Stack Overflow\n\nQuestion:\nWith Vite, using absolute paths in `index.html` results in them being transformed based on the `base` config, which is nice.\n\nFor instance my `index.html` contains this:\n\n```\n\n```\n\nAnd `base` is set to \"/demo\". The exported `index.html` will contain:\n\n```\n\n```\n\nThis is fine for most of my file but I would need to have a script loaded from the root of the server for a very specific thing. Is it possible to indicate to Vite to not change the path of a specific script tag? Like a preprocessor command? Like this:\n\n```\n\n```\n\nThat would be nice!\n\n========================================\n\nCode:\n```html\n<script type=\"text/javascript\" src=\"/config.js\"></script>\n```\n\n```html\n<script type=\"text/javascript\" src=\"/demo/config.js\"></script>\n```\n\n```html\n<!-- @vite-ignore -->\n<script type=\"text/javascript\" src=\"/config.js\"></script>\n```\n\n```text\nindex.html\n```\n\n```text\nbase\n```\n\n```text\nindex.html\n```\n\n```text\nbase\n```\n\n```text\nindex.html\n```\n\n```html\n<script type=\"text/javascript\">\n      // We have to do it using javascript otherwise Vite modifies the path\n      var config = document.createElement('script')\n      config.type = 'text/javascript'\n      config.src = '/config.js'\n      document.head.appendChild(config)\n    </script>\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.431Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":72,"estimatedTokens":350}}487{"id":"stack-78041376","source":"stackoverflow","questionId":78041376,"title":"Vue & Vite disable code splitting / chunking","tags":["javascript","vue.js","vuejs3","vite","code-splitting"],"text":"Title: Vue & Vite disable code splitting / chunking\nTags: javascript, vue.js, vuejs3, vite, code-splitting\nSource: Stack Overflow\n\nQuestion:\nI have built a small application in Vue/TypeScript and with Vite and i am trying to build the files using `vite build` but this is chunking the files. The file is to be placed on other peoples website with just a `div` tag and a `script` tag. The only issue with this is that Vite is splitting the JS files into chunks.\n\nthis is my basic config file\n\n```\nimport { defineConfig } from 'vite'\nimport { fileURLToPath, URL } from 'node:url'\nimport cssInjectedByJsPlugin from \"vite-plugin-css-injected-by-js\"\n\nimport vue from '@vitejs/plugin-vue'\n\nexport default defineConfig({\n plugins: [\n vue({ defineModel: true }),\n cssInjectedByJsPlugin()\n ],\n build: {\n emptyOutDir: false,\n rollupOptions: {\n output: {\n manualChunks: {},\n },\n }\n },\n})\n```\n\nI have also tried setting `manualChunks` to `undefined` but had no luck with this either. I've read some articles and other posts saying that this is the correct way but I am struggling and any help would be much appreciated.\n\nbuild script is `vite build`\n\n**setup includes:**\n\n- vite: `\"^5.0.11\"`\n\n- vite-plugin-css-injected-by-js: `\"^3.4.0\"`\n\n- vue: `^3.3.11\"`\n\n========================================\n\nTop Answer:\nI used this vite-configuration to get a single js (and css file) once:\n\n```\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [vue()],\n build: {\n rollupOptions: {\n output: {\n entryFileNames: `assets/[name].js`,\n chunkFileNames: `assets/[name].js`,\n assetFileNames: `assets/[name].[ext]`\n }\n }\n }\n})\n```\n\nThe `output:` part is the important one.\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite'\nimport { fileURLToPath, URL } from 'node:url'\nimport cssInjectedByJsPlugin from \"vite-plugin-css-injected-by-js\"\n\nimport vue from '@vitejs/plugin-vue'\n\nexport default defineConfig({\n  plugins: [\n    vue({ defineModel: true }),\n    cssInjectedByJsPlugin()\n  ],\n  build: {\n    emptyOutDir: false,\n    rollupOptions: {\n      output: {\n        manualChunks: {},\n      },\n    }\n  },\n})\n```\n\n```text\nvite build\n```\n\n```text\ndiv\n```\n\n```text\nscript\n```\n\n```text\nmanualChunks\n```\n\n```text\nundefined\n```\n\n```text\nvite build\n```\n\n```text\n\"^5.0.11\"\n```\n\n```text\n\"^3.4.0\"\n```\n\n```text\n^3.3.11\"\n```\n\n```text\noutput:{\n  inlineDynamicImports: true\n}\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue()],\n  build: {\n    rollupOptions: {\n      output: {\n        entryFileNames: `assets/[name].js`,\n        chunkFileNames: `assets/[name].js`,\n        assetFileNames: `assets/[name].[ext]`\n      }\n    }\n  }\n})\n```\n\n```text\noutput:\n```\n\n========================================\n\nComments:\n- Could you please [create a Minimal, Reproducible Example]? Codes are not split into chunks in the template created by `pnpm create vite my-vue-app --template vue`.\n- I suggest keeping the hashes in the file names. They are useful for asset caching.\n- @ouuan In general you are right of course - but the poster said that the script is going to be loaded from other websites. In that case the name has to stay the same all the time otherwise you have to change it on the other websites all the time.\n- I tried the other options but this is the option that seemed to work. I had to camel case the key tho to `inlineDynamicImports: true` for it to work. Thank you for your help.\n- @Bryan88 copied from the url, lost the camel case, sorry, a sloppy copy-paste\n- haha, not a problem! Again, thank you for your help! Very much appreciated","metadata":{"transformedAt":"2026-08-18T18:33:46.431Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":170,"estimatedTokens":937}}488{"id":"stack-76026598","source":"stackoverflow","questionId":76026598,"title":"Bundle code as a separate js file in Astro (astro.build, astrojs)","tags":["vite","browser-extension","astrojs"],"text":"Title: Bundle code as a separate js file in Astro (astro.build, astrojs)\nTags: vite, browser-extension, astrojs\nSource: Stack Overflow\n\nQuestion:\nI was wondering if there was way to have a `src/somescript.ts` to participate in bundling but to be output as a separate file in the build `dist/somescript.ts` not referenced by a page.\n\nWhen building a browser extension we can reference a `content_scripts` file that will be used to load into the current `activeTab`\n\n```\n\"content_scripts\": [\n {\n \"matches\": [\"https://*/*\"],\n \"js\": [\"content.js\"],\n \"run_at\": \"document_end\"\n }\n ],\n```\n\nI have tried to add a script on the `public/content.js` and tried to import a `src/somescript.ts` but it just copies it verbatim.\n\nIs there a way to configure Astro to bundle separate js files from `src/somescript.ts`?\n\n========================================\n\nCode:\n```json\n\"content_scripts\": [\n    {\n      \"matches\": [\"https://*/*\"],\n      \"js\": [\"content.js\"],\n      \"run_at\": \"document_end\"\n    }\n  ],\n```\n\n```text\nsrc/somescript.ts\n```\n\n```text\ndist/somescript.ts\n```\n\n```text\ncontent_scripts\n```\n\n```text\nactiveTab\n```\n\n```text\npublic/content.js\n```\n\n```text\nsrc/somescript.ts\n```\n\n```text\nsrc/somescript.ts\n```\n\n```json\n\"devDependencies\": {\n    .\n    \"vite\": \"4.3.0\"\n  },\n```\n\n```js\n/* \n    build.mjs\n    Custom Vite build script for extension files,\n    to execute after default build finishes its work.\n*/\nimport { build } from 'vite';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst extScripts = [\n    {\n        entry: path.resolve(__dirname, 'src-browser-ext/client-script.ts'),\n        fileName: 'client-script'\n    },\n    /*\n        If later you decide to add a background service worker.\n    */\n    // {\n    //  entry: path.resolve(__dirname, 'src-browser-ext/background-sw.ts'),\n    //  fileName: 'background-sw'\n    // }\n];\n\nextScripts.forEach(async (scr) => {\n    await build({\n        build: {\n            // Weather to add sourcemap or not\n            // make it false if not required\n            sourcemap: 'inline',\n            outDir: './dist',\n            lib: {\n                ...scr,\n                formats: ['es']\n            },\n            emptyOutDir: false\n        },\n        configFile: false\n    });\n});\n```\n\n```json\n\"scripts\": {\n        .\n        .\n        \"build-ext\": \"astro build && node build.mjs\"\n    },\n```\n\n```js\nexport default defineConfig({\n  build : {\n    assets: 'myapp'\n  }\n});\n```\n\n```text\nsrc-browser-ext\n```\n\n```text\nscripts\n```\n\n```text\nnpm run build\n```\n\n```text\npnpm run build\n```\n\n```text\nnpm run build-ext\n```\n\n```text\nunsafe-inline\n```\n\n```text\n_\n```\n\n```text\nbuild.assets\n```\n\n```text\nmyapp\n```\n\n```text\n_astro\n```\n\n========================================\n\nComments:\n- Thanks Bogac, I think you've made me think of a different approach to looking at the problem.","metadata":{"transformedAt":"2026-08-18T18:33:46.431Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":175,"estimatedTokens":723}}489{"id":"stack-73398874","source":"stackoverflow","questionId":73398874,"title":"Laravel deployment with Forge - VIte manifest not found","tags":["php","laravel","vite"],"text":"Title: Laravel deployment with Forge - VIte manifest not found\nTags: php, laravel, vite\nSource: Stack Overflow\n\nQuestion:\nI am trying to deploy a brand new Laravel 9 site with Vite.\n\nI have the site running locally just fine, and the deployment is running via Laravel forge using the default deployment script:\n\n```\ncd /home/forge/default\ngit pull origin $FORGE_SITE_BRANCH\n\n$FORGE_COMPOSER install --no-interaction --prefer-dist --optimize-autoloader\n\n( flock -w 10 9 || exit 1\n echo 'Restarting FPM...'; sudo -S service $FORGE_PHP_FPM reload ) 9>/tmp/fpmlock\n\nif [ -f artisan ]; then\n $FORGE_PHP artisan migrate --force\nfi\n```\n\nBefore pushing my changes from my local to remote server, I run:\n\n```\nnpm run build\n```\n\nHowever, when the site has been deployed to forge, I get the below error:\n\n(Exception(code: 0): Vite manifest not found at: /home/forge/default/public/build/manifest.json at /home/forge/default/vendor/laravel/framework/src/Illuminate/Foundation/Vite.php:139)\n\nWhen I ssh into my server, this is the content of the `/public` folder:\n\n```\n.\n└── public/\n ├── favicon.ico\n ├── index.php\n └── robots.txt\n```\n\nShouldn't the `/build` folder be available on the production site as well, or am I missing something? Please note in my standard generated `.gitignore` file, these paths are excluded:\n\n```\n/public/build\n/public/hot\n/public/storage\n```\n\n========================================\n\nCode:\n```bash\ncd /home/forge/default\ngit pull origin $FORGE_SITE_BRANCH\n\n$FORGE_COMPOSER install --no-interaction --prefer-dist --optimize-autoloader\n\n( flock -w 10 9 || exit 1\n    echo 'Restarting FPM...'; sudo -S service $FORGE_PHP_FPM reload ) 9>/tmp/fpmlock\n\nif [ -f artisan ]; then\n    $FORGE_PHP artisan migrate --force\nfi\n```\n\n```text\nnpm run build\n```\n\n```text\n.\n└── public/\n    ├── favicon.ico\n    ├── index.php\n    └── robots.txt\n```\n\n```text\n/public/build\n/public/hot\n/public/storage\n```\n\n```text\n/public\n```\n\n```text\n/build\n```\n\n```text\n.gitignore\n```\n\n```text\n/public/build\n/public/hot\n/public/storage\n```\n\n```text\n!/public/build\n/public/hot\n/public/storage\n```\n\n```text\ncd /home/forge/default\ngit pull origin $FORGE_SITE_BRANCH\n\n$FORGE_COMPOSER install --no-interaction --prefer-dist --optimize-autoloader\n\n( flock -w 10 9 || exit 1\n    echo 'Restarting FPM...'; sudo -S service $FORGE_PHP_FPM reload ) 9>/tmp/fpmlock\n\nif [ -f artisan ]; then\n    $FORGE_PHP artisan migrate --force\nfi\n\nnpm install\nnpm run build\n```\n\n```text\n.gitignore\n```\n\n```text\nnpm install\n```\n\n```text\nnpm run build\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.431Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":138,"estimatedTokens":627}}490{"id":"stack-75682879","source":"stackoverflow","questionId":75682879,"title":"The tag is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter","tags":["javascript","html","reactjs","styled-components","vite"],"text":"Title: The tag is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter\nTags: javascript, html, reactjs, styled-components, vite\nSource: Stack Overflow\n\nQuestion:\n### Problem\n\nI just tried to build a component via styled components on vite. But, When I try to use text from styled components, It throws an error on console:\n\n```\nWarning: The tag is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.\n at text\n at O2 (http://localhost:5173/node_modules/.vite/deps/styled-components.js?v=b320d886:1423:6)\n at TextView (http://localhost:5173/src/components/TextView/index.jsx?t=1678354528314:18:3)\n at Header\n at App\nprintWarning @ react-dom.development.js:86\nerror @ react-dom.development.js:60\ncreateElement @ react-dom.development.js:9816\ncreateInstance @ react-dom.development.js:10941\ncompleteWork @ react-dom.development.js:22187\ncompleteUnitOfWork @ react-dom.development.js:26596\nperformUnitOfWork @ react-dom.development.js:26568\nworkLoopSync @ react-dom.development.js:26466\nrenderRootSync @ react-dom.development.js:26434\nperformConcurrentWorkOnRoot @ react-dom.development.js:25738\nworkLoop @ scheduler.development.js:266\nflushWork @ scheduler.development.js:239\nperformWorkUntilDeadline @ scheduler.development.js:533\n```\n\n### Code\n\n```\nimport styled from 'styled-components';\n// import variablesBreakpoints from '../../helpers/variablesBreakpoints';\n\nfunction TextView({ children, color, fontSize, fontWeight }) {\n const StyledText = styled.text`\n color: ${color};\n font-size: ${fontSize};\n font-weight: ${fontWeight};\n `;\n\n return {children};\n}\n\nTextView.defaultProps = {\n color: '#fff',\n fontSize: '1em',\n fontWeight: 'normal',\n};\n\nexport default TextView;\n```\n\n### Note\n\n- I didn't convert with uppercase because it does automatically.\n\n- I done a research and I saw plugins about that.\n\n========================================\n\nCode:\n```text\nWarning: The tag <text> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.\n    at text\n    at O2 (http://localhost:5173/node_modules/.vite/deps/styled-components.js?v=b320d886:1423:6)\n    at TextView (http://localhost:5173/src/components/TextView/index.jsx?t=1678354528314:18:3)\n    at Header\n    at App\nprintWarning                @   react-dom.development.js:86\nerror                       @   react-dom.development.js:60\ncreateElement               @   react-dom.development.js:9816\ncreateInstance              @   react-dom.development.js:10941\ncompleteWork                @   react-dom.development.js:22187\ncompleteUnitOfWork          @   react-dom.development.js:26596\nperformUnitOfWork           @   react-dom.development.js:26568\nworkLoopSync                @   react-dom.development.js:26466\nrenderRootSync              @   react-dom.development.js:26434\nperformConcurrentWorkOnRoot @   react-dom.development.js:25738\nworkLoop                    @   scheduler.development.js:266\nflushWork                   @   scheduler.development.js:239\nperformWorkUntilDeadline    @   scheduler.development.js:533\n```\n\n```text\nimport styled from 'styled-components';\n// import variablesBreakpoints from '../../helpers/variablesBreakpoints';\n\nfunction TextView({ children, color, fontSize, fontWeight }) {\n  const StyledText = styled.text`\n    color: ${color};\n    font-size: ${fontSize};\n    font-weight: ${fontWeight};\n  `;\n\n  return <StyledText>{children}</StyledText>;\n}\n\nTextView.defaultProps = {\n  color: '#fff',\n  fontSize: '1em',\n  fontWeight: 'normal',\n};\n\nexport default TextView;\n```\n\n```text\nstyled.text\n```\n\n```text\n<p>\n```\n\n```text\n<span>\n```\n\n```text\nstyled.p\n```\n\n```text\nstyled.span\n```\n\n========================================\n\nComments:\n- is not a standard html tag. Use `styled.p`","metadata":{"transformedAt":"2026-08-18T18:33:46.431Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":134,"estimatedTokens":960}}491{"id":"stack-74270384","source":"stackoverflow","questionId":74270384,"title":"What are the \"Query Suffixes\" referred to in the Vite Docs?","tags":["javascript","node.js","import","web-worker","vite"],"text":"Title: What are the \"Query Suffixes\" referred to in the Vite Docs?\nTags: javascript, node.js, import, web-worker, vite\nSource: Stack Overflow\n\nQuestion:\nI have been reading through the Vite documentation for Web workers, and it mentioned importing a file using \"Query Suffixes,\" which I have never encountered and am not sure what to search for to learn more. I'm not sure if this is native to Node.js, Vite.js, or if it is a plugin that is built into Vite.\n\nThis is the specific section that I am referring to:\n\n### Import with Query Suffixes\n\nA web worker script can be directly imported by appending ?worker or ?sharedworker to the import request. The default export will be a custom worker constructor:\n\n```\nimport MyWorker from './worker?worker'\n\nconst worker = new MyWorker()\n```\n\nThe worker script can also use import statements instead of importScripts() - note during dev this relies on browser native support and currently only works in Chrome, but for the production build it is compiled away.\n\nBy default, the worker script will be emitted as a separate chunk in the production build. If you wish to inline the worker as base64 strings, add the inline query:\n\n```\nimport MyWorker from './worker?worker&inline'\n```\n\nIf you wish to retrieve the worker as a URL, add the url query:\n\n```\nimport MyWorker from './worker?worker&url'\n```\n\nSee Worker Options for details on configuring the bundling of all workers.\n\n### Update:\n\nI found an MDN page on `import` that seems like a step in the direction that I am looking for, as well as this MDN page on `import.meta` that looks a lot like what I am searching for. I tried following that lead, but it didn't help me understand this Vite feature any better.\n\nIs the `?worker` query suffix a custom Vite implementation of `import.meta`?\n\n========================================\n\nTop Answer:\nDidn't know it was Vite specific problem. But, this fixed my error.\n\n```\nimport MyWorker from './worker?worker'\n\nconst worker = new MyWorker()\n```\n\n========================================\n\nCode:\n```js\nimport MyWorker from './worker?worker'\n\nconst worker = new MyWorker()\n```\n\n```js\nimport MyWorker from './worker?worker&inline'\n```\n\n```js\nimport MyWorker from './worker?worker&url'\n```\n\n```text\nimport\n```\n\n```text\nimport.meta\n```\n\n```text\n?worker\n```\n\n```text\nimport.meta\n```\n\n```js\nconst worker = new Worker(new URL('./worker.js', import.meta.url))\n```\n\n```js\nimport ShortWorker from './worker.js?worker'\n\nconst worker = new ShortWorker();\n```\n\n```js\n// Explicitly load assets as URL\nimport assetAsURL\n from './asset.js?url'\n```\n\n```js\n// Load assets as strings\nimport assetAsString\n from './shader.glsl?raw'\n```\n\n```js\n// Load Web Workers\nimport Worker\n from './worker.js?worker'\n```\n\n```text\nimport MyWorker from './worker?worker'\n\nconst worker = new MyWorker()\n```\n\n========================================\n\nComments:\n- Thanks for responding! Fortunately, I was not receiving an error per se. Rather, I was trying to understand how the query suffixes work in order to better use them, but couldn't find any relevant documentation. As such, I'm not going to mark your response as the answer, but I do appreciate you taking the time to respond.\n- So, if I understand correctly, these query strings are not part of any JS standard but are built as a part of Vite itself. Is that right?\n- For the time being, this is my understanding. On the subject of standardisation it seems the it has been considered as “avoided” in node ( github.com/nodejs/modules/issues/493 ) regarding the complexity it could introduce ( github.com/WICG/import-maps/issues/134#issuecomment-52970692&zwnj;&#8203;9 )\n- That makes sense. Thank you for the links you provided! Marking this as the answer!","metadata":{"transformedAt":"2026-08-18T18:33:46.431Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":126,"estimatedTokens":930}}492{"id":"stack-76206575","source":"stackoverflow","questionId":76206575,"title":"esbuild import css as a string","tags":["css","import","inline","vite","esbuild"],"text":"Title: esbuild import css as a string\nTags: css, import, inline, vite, esbuild\nSource: Stack Overflow\n\nQuestion:\nI am using vite to build a component library. I use css?inline like this\n\n```\nimport otherStyles from './bar.css?inline' // will be available as a string\n```\n\nAnd use the string to construct stylesheets in the component. see here\n\nNow I made a build script with esbuild. But can't seem to get this inline css to work. Esbuild parses the import but makes an external css.\n\nI know vite (dev env) is based on esbuild, so it should be possible to let esbuild do inline css parsing. Can't find it in the docs, can't find a plugin that does this either.\n\n========================================\n\nCode:\n```js\nimport otherStyles from './bar.css?inline' // will be available as a string\n```\n\n```js\nimport string from 'inline:./path/to/file.ext';\n```\n\n```js\nimport cssCode from 'inline:./path/to/style.css';\n```\n\n========================================\n\nComments:\n- you probably need to create a custom plugin, see this article and scroll to \"Binding text files via ?raw\" which should be similar to \"?inline\".","metadata":{"transformedAt":"2026-08-18T18:33:46.431Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":36,"estimatedTokens":279}}493{"id":"stack-73096758","source":"stackoverflow","questionId":73096758,"title":"vue vite dynamic components import","tags":["laravel","vue.js","vuejs3","vite","inertiajs"],"text":"Title: vue vite dynamic components import\nTags: laravel, vue.js, vuejs3, vite, inertiajs\nSource: Stack Overflow\n\nQuestion:\nI am migrating an existing laravel ineria from mix to vit.\n\nI did all the steps in the migration guid and everything works fine except for one thing.\n\nI have a component receives a prop conatains an array of components.\n\nI used to require them like this (inside a loop)\n\n```\n...\n\nthis.$options.components[component_name] = require(`@/Pages/Components/Inputs/${component_name}`).default\n\n...\n```\n\nthis wont work with vite because of \"**require**\", I have to replace it with **import**\n\nso I tried these ways and none of them works\n\n```\nthis.$options.components[component_name] = () => resolvePageComponent(`./Pages/Components/Inputs/${component_name}.vue`, import.meta.glob('./Pages/**/*.vue'))\n\nthis.$options.components[component_name] = () => resolvePageComponent(`@/Pages/Components/Inputs/${component_name}.vue`, import.meta.glob('./Pages/**/*.vue'))\n\nthis.$options.components[component_name] = resolvePageComponent(`./Pages/Components/Inputs/${component_name}.vue`, import.meta.glob('./Pages/**/*.vue'))\n\nthis.$options.components[component_name] = resolvePageComponent(`@/Pages/Components/Inputs/${component_name}.vue`, import.meta.glob('./Pages/**/*.vue'))\n```\n\nall of them throws the same exception\n\n```\n\"Uncaught (in promise) Error: Page not found: ./Pages/Components/Inputs/Text.vue\".\n```\n\n========================================\n\nCode:\n```text\n...\n\nthis.$options.components[component_name] = require(`@/Pages/Components/Inputs/${component_name}`).default\n\n...\n```\n\n```text\nthis.$options.components[component_name] = () => resolvePageComponent(`./Pages/Components/Inputs/${component_name}.vue`, import.meta.glob('./Pages/**/*.vue'))\n\n\nthis.$options.components[component_name] = () => resolvePageComponent(`@/Pages/Components/Inputs/${component_name}.vue`, import.meta.glob('./Pages/**/*.vue'))\n\nthis.$options.components[component_name] = resolvePageComponent(`./Pages/Components/Inputs/${component_name}.vue`, import.meta.glob('./Pages/**/*.vue'))\n\nthis.$options.components[component_name] = resolvePageComponent(`@/Pages/Components/Inputs/${component_name}.vue`, import.meta.glob('./Pages/**/*.vue'))\n```\n\n```text\n\"Uncaught (in promise) Error: Page not found: ./Pages/Components/Inputs/Text.vue\".\n```\n\n```text\nimport {defineAsyncComponent} from \"vue\";\n```\n\n```text\nlayout_components: []\n```\n\n```text\nmounted() {\n    this.layout_components = Object.keys(this.$options.components)\n    this.layouts.forEach(layout => this.importLayoutComponent(layout))\n}\n```\n\n```text\nimportLayoutComponent(layout) {\n    if (!this.layout_components.includes(layout.name)) {\n        this.layout_components.push(layout.name)\n        this.$options.components[layout.name] = defineAsyncComponent(() => import(`../Sections/${layout.type}/${layout.name}.vue`))\n    }\n}\n```\n\n```text\n<component\n  :is=\"layout.name\"\n  ... //other propes to pass to the component\n/>\n```\n\n========================================\n\nComments:\n- Did you ever solve this?\n- unfortunately no, I can not move to vite untill this problem solved.\n- whenever I solve it, I will answer the question here.\n- @iiiml0sto1 checkout the answer to this question if you still need it!","metadata":{"transformedAt":"2026-08-18T18:33:46.431Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":105,"estimatedTokens":813}}494{"id":"stack-74074875","source":"stackoverflow","questionId":74074875,"title":"VitePWA plugin not updating generated icons in manifest","tags":["progressive-web-apps","vite"],"text":"Title: VitePWA plugin not updating generated icons in manifest\nTags: progressive-web-apps, vite\nSource: Stack Overflow\n\nQuestion:\nI have a site with PWA img assets in\n\nimg/icons/imagename.png\n\nI am trying to build the site with vite and vite-plugin-pwa to use it as a pwa.\nThe vite.config.js and the index.html are in the project root directory. Images are in img directory.\n\nThe problem is that when I run the build file places the imgs in the folder `assets/imageName###.png`\nFor example `chrome192.png` is placed in `assets/chrome192.f25426fd.png`\nHowever, the manifest file generated upon build `manifest.webmanifest` still contains\n\n```\nsrc: 'img/icons/chrome192.png',\n```\n\nThe application tab for dev tools in chrome shows `{rootURL}/img/icon/chrome192.png` not found. Which is expected since the bundling with vite build places it in a different folder (assets).\n\nWhy does it not update the path of the images in the generated manifest.webmanifest?\nIsn't that the whole point of the vite-plugin-pwa to keep track of the filenames that change upon build.\n\nAnother issue is that I have different routes eg: html/about\nInside the about.html generated on build, the web manifest path is given as:\n\n```\n\n```\n\nIt uses this path instead of using `../manifest.webmanifest` or maybe a path from the root without the ./ such as `href=\"./manifest.webmanifest\"`\n\nMy vite.config.js is shown below\n\n```\nimport { resolve } from 'path';\nimport { defineConfig } from 'vite';\nimport { VitePWA } from 'vite-plugin-pwa'\n// import legacy from '@vitejs/plugin-legacy';\n\nexport default defineConfig({\n plugins: [\n VitePWA({\n includeAssets: ['img/icons/favicon.png', 'img/icons/maskable_icon.png' ],\n manifest: {\n name: 'Final Countdown',\n start_url: \"/\",\n short_name: 'Final Countdown',\n description: 'Awesome countdown App',\n theme_color: '#031c36',\n icons: [\n {\n src: 'img/icons/chrome192.png',\n sizes: '192x192',\n type: 'image/png'\n },\n {\n src: 'img/icons/chrome512.png',\n sizes: '512x512',\n type: 'image/png'\n },\n {\n src: 'img/icons/chrome512.png',\n sizes: '512x512',\n type: 'image/png',\n purpose: 'any maskable'\n }\n ]\n }\n })\n \n ],\n build: {\n rollupOptions: {\n input: {\n main: resolve(__dirname, 'index.html'),\n about: resolve(__dirname, 'html/about.html'),\n countdownList: resolve(__dirname, 'html/countdown-list.html'),\n fallback: resolve(__dirname, 'html/fallback.html'),\n today: resolve(__dirname, 'html/today.html'),\n formupload: resolve(__dirname, 'html/form-upload.html'),\n\n },\n },\n },\n});\n```\n\nThe code is hosted at this branch if you need to take a look at the full folder\nhttps://github.com/RDjarbeng/countdown/tree/vitePWA\n\nI have removed the previous `manifest.json` file that used to work before I started using the vite-plugin-pwa, because when it was included there were two manifest files in the build instead.\nHave also tried using /img/icons/... for the paths and resolve(__dirname, img/icons/chrome192.png)\n\nHow do I get the PWA manifest and icons to sync with the image build files generated by the viteJS bundler and satisfy the PWA conditions?\n\nHow do I get the paths of html files not in the root folder to use the correct path to the manifest.webmanifest?\n\n========================================\n\nCode:\n```text\nsrc: 'img/icons/chrome192.png',\n```\n\n```text\n<link rel=\"manifest\" href=\"./manifest.webmanifest\">\n```\n\n```text\nimport { resolve } from 'path';\nimport { defineConfig } from 'vite';\nimport { VitePWA } from 'vite-plugin-pwa'\n// import legacy from '@vitejs/plugin-legacy';\n\nexport default defineConfig({\n  plugins: [\n    VitePWA({\n      includeAssets: ['img/icons/favicon.png', 'img/icons/maskable_icon.png' ],\n      manifest: {\n        name: 'Final Countdown',\n        start_url: \"/\",\n        short_name: 'Final Countdown',\n        description: 'Awesome countdown App',\n        theme_color: '#031c36',\n        icons: [\n          {\n            src: 'img/icons/chrome192.png',\n            sizes: '192x192',\n            type: 'image/png'\n          },\n          {\n            src: 'img/icons/chrome512.png',\n            sizes: '512x512',\n            type: 'image/png'\n          },\n          {\n            src: 'img/icons/chrome512.png',\n            sizes: '512x512',\n            type: 'image/png',\n            purpose: 'any maskable'\n          }\n        ]\n      }\n    })\n      \n  ],\n  build: {\n    rollupOptions: {\n      input: {\n        main: resolve(__dirname, 'index.html'),\n        about: resolve(__dirname, 'html/about.html'),\n        countdownList: resolve(__dirname, 'html/countdown-list.html'),\n        fallback: resolve(__dirname, 'html/fallback.html'),\n        today: resolve(__dirname, 'html/today.html'),\n        formupload: resolve(__dirname, 'html/form-upload.html'),\n\n      },\n    },\n  },\n});\n```\n\n```text\nassets/imageName###.png\n```\n\n```text\nchrome192.png\n```\n\n```text\nassets/chrome192.f25426fd.png\n```\n\n```text\nmanifest.webmanifest\n```\n\n```text\n{rootURL}/img/icon/chrome192.png\n```\n\n```text\n../manifest.webmanifest\n```\n\n```text\nhref=\"./manifest.webmanifest\"\n```\n\n```text\nmanifest.json\n```\n\n```text\nincludeAssets: [\"**/*.{png}\"],\n      manifest: {\n        name: 'Final Countdown',\n        start_url: \"/\",\n        id: \"/\",\n        short_name: 'Final Countdown',\n        description: 'Awesome countdown App',\n        theme_color: '#031c36',\n        icons: [\n          {\n            src:  '/img/icons/chrome192.png',\n            sizes: '192x192',\n            type: 'image/png'\n          },\n          {\n            src: '/img/icons/chrome512.png',\n            sizes: '512x512',\n            type: 'image/png'\n          },\n        ]\n      },\n```\n\n========================================\n\nComments:\n- But what if you want vite to hash the filenames for cache control?\n- @R&#250;narBerg I am not sure but I am assuming your question is for the PWA service worker cache. When I asked a similar question on the issues page for Vite this was the answer: Vite will always copy any entry on public folder but you will need to add any assets to the sw precache manifest to allow work offline. Check the warning here vite-plugin-pwa.netlify.app/guide/&hellip;.","metadata":{"transformedAt":"2026-08-18T18:33:46.431Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":226,"estimatedTokens":1520}}495{"id":"stack-77766068","source":"stackoverflow","questionId":77766068,"title":"Quasar VUE_PROD_HYDRATION_MISMATCH_DETAILS is not defined","tags":["javascript","vue.js","vuejs3","vite","quasar-framework"],"text":"Title: Quasar VUE_PROD_HYDRATION_MISMATCH_DETAILS is not defined\nTags: javascript, vue.js, vuejs3, vite, quasar-framework\nSource: Stack Overflow\n\nQuestion:\nIm using quasar together with Vite. After installing quasar with `yarn create quasar` I get the following warning in the console.\n\n```\n__VUE_PROD_HYDRATION_MISMATCH_DETAILS__ is not explicitly defined.\n You are running the esm-bundler build of Vue, which expects these \ncompile-time feature flags to be globally injected via the bundler \nconfig in order to get better tree-shaking in the production \nbundle.\n```\n\nHow can I get rid of it? I cannot find any information on where I shall define this in Quasar Framework\n\n========================================\n\nCode:\n```text\n__VUE_PROD_HYDRATION_MISMATCH_DETAILS__ is not explicitly defined.\n You are running the esm-bundler build of Vue, which expects these \ncompile-time feature flags to be globally injected via the bundler \nconfig in order to get better tree-shaking in the production \nbundle.\n```\n\n```text\nyarn create quasar\n```\n\n```js\nbuild: {\n  extendViteConf(viteConf) {\n    viteConf.define.__VUE_PROD_HYDRATION_MISMATCH_DETAILS__ = false\n  },\n}\n```\n\n```text\n@vitejs/plugin-vue\n```\n\n========================================\n\nComments:\n- Any harm or benefits setting it to true?\n- It's a flag for debugging hydration mismatch errors in production vuejs.org/api/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:46.431Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":49,"estimatedTokens":346}}496{"id":"stack-73875420","source":"stackoverflow","questionId":73875420,"title":"Vue 3 + vite works on development but not in production","tags":["vue.js","vuejs3","vite"],"text":"Title: Vue 3 + vite works on development but not in production\nTags: vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI'm developing a website using vue.js 3 and vite. When i run on development mode, it works fine. Then i built the website using yarn build and run it with yarn preview, but the app shows blank page without any errors appear.\n\nHere is my code :\n\npackage.json :\n\n```\n\"name\": \"web-app-new\",\n \"version\": \"0.0.0\",\n \"scripts\": {\n \"dev\": \"vite --port 5000 --host\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview --port 4173\",\n \"test:unit\": \"vitest --environment jsdom\"\n },\n \"dependencies\": {\n \"axios\": \"^0.27.2\",\n \"crypto-js\": \"^4.1.1\",\n \"firebase\": \"^8.10.1\",\n \"jwt-decode\": \"^3.1.2\",\n \"maska\": \"^1.5.0\",\n \"mdi-vue\": \"^3.0.13\",\n \"moment\": \"^2.29.4\",\n \"pinia\": \"^2.0.16\",\n \"uuid\": \"^8.3.2\",\n \"v-calendar\": \"^3.0.0-alpha.8\",\n \"v-viewer\": \"^3.0.10\",\n \"vue\": \"^3.2.39\",\n \"vue-router\": \"^4.1.2\",\n \"vue3-cookies\": \"^1.0.6\",\n \"vuefire\": \"^2.2.5\"\n },\n \"devDependencies\": {\n \"@vitejs/plugin-vue\": \"^3.0.1\",\n \"@vitejs/plugin-vue-jsx\": \"^2.0.0\",\n \"@vue/test-utils\": \"^2.0.2\",\n \"autoprefixer\": \"^10.4.8\",\n \"jsdom\": \"^20.0.0\",\n \"postcss\": \"^8.4.16\",\n \"tailwindcss\": \"^3.1.8\",\n \"vite\": \"^3.0.3\",\n \"vitest\": \"^0.18.1\"\n }\n}\n```\n\nvite.config.js :\n\n```\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\";\nimport vueJsx from \"@vitejs/plugin-vue-jsx\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [vue(), vueJsx()],\n build: {\n /** If you set esmExternals to true, this plugins assumes that \n all external dependencies are ES modules */\n\n commonjsOptions: {\n esmExternals: true,\n },\n },\n resolve: {\n alias: {\n \"@\": fileURLToPath(new URL(\"./src\", import.meta.url)),\n },\n },\n});\n```\n\nmain.js :\n\n```\nimport { createApp, markRaw } from \"vue\";\nimport { createPinia } from \"pinia\";\nimport mdiVue from \"mdi-vue/v3\";\nimport * as mdijs from \"@mdi/js\";\n\nimport App from \"./App.vue\";\nimport router from \"./router\";\n\nimport \"./assets/main.css\";\nimport \"v-calendar/dist/style.css\";\nimport utils from \"./plugins/utils\";\nimport external from \"./plugins/utils.external\";\n// import { firestorePlugin } from \"vuefire\";\n\ntry {\n const app = createApp(App);\n\n const components = import.meta.globEager([\n \"./components/*.vue\",\n \"./components/Atoms/*.vue\",\n \"./components/Atoms/Image/*.vue\",\n \"./components/Atoms/Button/*.vue\",\n \"./components/Atoms/Input/*.vue\",\n \"./components/Atoms/Tabs/*.vue\",\n \"./components/Molecules/*.vue\",\n \"./components/Molecules/Modal/*.vue\",\n \"./components/Molecules/Transition/*.vue\",\n \"./components/Organism/*.vue\",\n \"./components/Organism/Absensi/*.vue\",\n \"./components/Organism/Pengaturan/*.vue\",\n ]);\n\n Object.entries(components).forEach(([path, definition]) => {\n // components/Atoms/Container.vue become => AtomsContainer\n const componentName = path.replace(/(.vue|\\/|\\.|components|index)/g, \"\");\n // Register component on this Vue instance\n // console.log(`😎  ${componentName} loaded`);\n app.component(componentName, definition.default);\n });\n // @plugins\n\n //@pinia\n const pinia = createPinia();\n pinia.use(({ store }) => {\n store.$router = markRaw(router);\n store.$app = app;\n store.$globalProperties = app.config.globalProperties;\n });\n app.use(pinia);\n\n //@others\n // app.use(firestorePlugin, {});\n app.use(mdiVue, {\n icons: mdijs,\n });\n app.use(utils, {});\n app.use(external, {});\n\n app.use(router);\n app.mount(\"#app\");\n} catch (error) {\n console.log(error);\n}\n```\n\nrouter.js :\n\n```\nimport { createRouter, createWebHistory } from \"vue-router\";\nimport { useStorage } from \"@/composables/storage\";\nimport { useLoadingStore } from \"@/stores/loading\";\nimport { useUserStore } from \"@/stores/user\";\nimport { useClientStore } from \"@/stores/client\";\nimport { useWorkerStore } from \"@/stores/worker\";\n\nconst router = createRouter({\n history: createWebHistory(import.meta.env.BASE_URL),\n routes: [\n {\n redirect: \"/login\",\n },\n {\n path: \"/login\",\n name: \"login\",\n component: import(\"@/views/Test.vue\"),\n // meta: {\n // layout: \"Auth\",\n // },\n },\n {\n path: \"/daftar\",\n name: \"daftar\",\n redirect: \"/daftar\",\n component: () => import(\"@/components/Atoms/NestedWrapper.vue\"),\n children: [\n {\n path: \"/daftar\",\n name: \"daftar\",\n component: import(\"@/views/Daftar/index.vue\"),\n meta: {\n icon: \"history\",\n // layout: \"Auth\",\n },\n },\n {\n path: \"/daftar/akun\",\n name: \"daftar akun\",\n redirect: \"/daftar/akun\",\n component: () => import(\"@/components/Atoms/NestedWrapper.vue\"),\n children: [\n {\n path: \"/daftar/akun\",\n name: \"daftar akun\",\n component: import(\"@/views/Daftar/Akun/index.vue\"),\n meta: {\n icon: \"account\",\n layout: \"Plain\",\n validate: ({ next, userStore }) => {\n ((!userStore.$state?.form?.idNumber ||\n !userStore.$state?.form?.email) &&\n next(\"/daftar\")) ||\n next();\n },\n },\n },\n {\n path: \"/daftar/akun/buat\",\n name: \"buat akun baru\",\n component: import(\"@/views/Daftar/Akun/Buat.vue\"),\n meta: {\n icon: \"account\",\n layout: \"Plain\",\n validate: ({ next, userStore }) => {\n ((!userStore.$state?.form?.idNumber ||\n !userStore.$state?.form?.email) &&\n next(\"/daftar\")) ||\n next();\n },\n },\n },\n ],\n meta: {},\n },\n {\n path: \"/daftar/perusahaan\",\n name: \"daftar perusahaan\",\n redirect: \"/daftar/perusahaan\",\n component: () => import(\"@/components/Atoms/NestedWrapper.vue\"),\n children: [\n {\n path: \"/daftar/perusahaan\",\n name: \"daftar perusahaan\",\n component: import(\"@/views/Daftar/Perusahaan/index.vue\"),\n meta: {\n icon: \"history\",\n layout: \"Plain\",\n },\n },\n {\n path: \"/daftar/perusahaan/akun\",\n name: \"daftar akun perusahaan\",\n component: import(\"@/views/Daftar/Perusahaan/Akun.vue\"),\n meta: {\n icon: \"account\",\n layout: \"Plain\",\n validate: ({ next, workerStore, clientStore }) => {\n (!clientStore.$state?.form && next(\"/daftar\")) || next();\n },\n },\n },\n ],\n meta: {},\n },\n {\n path: \"/daftar/pekerja\",\n name: \"daftar pekerja\",\n redirect: \"/daftar/pekerja\",\n component: () => import(\"@/components/Atoms/NestedWrapper.vue\"),\n children: [\n {\n path: \"/daftar/pekerja\",\n name: \"daftar pekerja\",\n component: import(\"@/views/Daftar/Pekerja/index.vue\"),\n meta: {\n icon: \"history\",\n layout: \"Plain\",\n validate: ({ next, workerStore, clientStore }) => {\n (!workerStore.$state?.form?.idNumber && next(\"/daftar\")) ||\n next();\n },\n },\n },\n {\n path: \"/daftar/pekerja/akun\",\n name: \"daftar akun pekerja\",\n component: import(\"@/views/Daftar/Pekerja/Akun.vue\"),\n meta: {\n icon: \"account\",\n layout: \"Plain\",\n validate: ({ next, workerStore, clientStore }) => {\n ((!workerStore.$state?.form ||\n !workerStore.$state?.form?.idNumber) &&\n next(\"/daftar\")) ||\n next();\n },\n },\n },\n ],\n meta: {},\n },\n ],\n meta: {\n // layout: \"Auth\",\n },\n },\n {\n path: \"/app\",\n redirect: \"/app/beranda\",\n },\n {\n path: \"/app/beranda\",\n name: \"beranda\",\n component: import(\"@/views/Beranda.vue\"),\n meta: {\n layout: \"Auth\",\n },\n },\n {\n path: \"/app/404\",\n name: \"404\",\n component: () => import(\"@/views/404.vue\"),\n meta: {\n // type: [roles.All],\n layout: \"Auth\",\n hidden: true,\n },\n },\n {\n path: \"/app/:pathMatch(.*)*\",\n redirect: \"/app/wrong\",\n },\n ],\n});\n\nrouter.beforeEach(async (to, from, next) => {\n const loadingStore = useLoadingStore();\n const userStore = useUserStore();\n const clientStore = useClientStore();\n const workerStore = useWorkerStore();\n loadingStore.setLoading({\n skeleton: true,\n });\n if (to?.meta?.layout !== from?.meta?.layout) {\n loadingStore.setLoading({\n layout: true,\n });\n await new Promise((res) => setTimeout(() => res(true), 1000));\n }\n if (to?.path !== from?.path) {\n loadingStore.setLoading({\n global: true,\n });\n }\n try {\n if (useStorage(\"credentials\")?.refresh) {\n await userStore.statusUser();\n }\n if (userStore.isLoggedIn && !to.fullPath.includes(\"app\")) {\n return next({ path: \"/app\" });\n }\n if (!userStore.isLoggedIn && to.fullPath.includes(\"app\")) {\n return next({ path: \"/login\" });\n }\n if (to.meta?.validate && typeof to.meta?.validate === \"function\") {\n return to.meta?.validate({\n to,\n from,\n next,\n userStore,\n clientStore,\n workerStore,\n });\n } else {\n next();\n }\n } catch (error) {\n return Promise.reject(error);\n }\n});\n\nrouter.afterEach(async (to, from, failure) => {\n const loadingStore = useLoadingStore();\n const userStore = useUserStore();\n try {\n // if (!userStore.isLoggedIn) {\n // router.push(\"/\");\n // }\n } catch (error) {\n return Promise.reject(error);\n } finally {\n loadingStore.clearLoading();\n }\n});\n\nexport default router;\n```\n\nApp.vue :\n\n```\nimport Layout from \"@/layouts/index.vue\";\nimport { onMounted } from \"vue\";\nimport { RouterLink, RouterView } from \"vue-router\";\nimport { useLoadingStore } from \"./stores/loading\";\n\nonMounted(() => {\n document.documentElement.style.scrollBehavior = \"smooth\";\n document.documentElement.style.overflow = \"auto\";\n useLoadingStore().setLoading({ layout: true });\n});\n\n \n \n \n \n -->\n \n -->\n \n \n\n```\n\nIm also using layouts, here is my `layouts/index.vue` :\n\n```\nimport AppLayoutDefault from \"./Default.vue\";\nimport ErrorLayout from \"./Error.vue\";\nimport { markRaw, onErrorCaptured, onMounted, ref, watch } from \"vue\";\nimport { useRoute, useRouter } from \"vue-router\";\n\nconst layout = ref();\nconst route = useRoute();\n\nwatch(\n () => route.meta?.layout || undefined,\n async (metaLayout) => {\n try {\n const component =\n metaLayout && (await import(/* @vite-ignore */ `./${metaLayout}.vue`));\n layout.value = markRaw(component?.default || AppLayoutDefault);\n } catch (e) {\n layout.value = markRaw(ErrorLayout);\n }\n },\n { immediate: true }\n);\n\nonErrorCaptured(() => {\n // layout.value = markRaw(ErrorLayout);\n});\n\n \n\n```\n\nAnd this is the preview on development mode :\n\nhttps://i.sstatic.net/ry4lu.png\n\nbut on production mode :\n\nhttps://i.sstatic.net/cYFgm.png\n\nI would appriciate some help. Thanks a lot\n\n========================================\n\nTop Answer:\nI faced the same issue with a vanilla js app created with `npm create vite@latest client --template vanilla`\nMy project folder did not have `vite.config.js`. Simply adding this file with default configuration (shown below) did the trick for me.\n\n```\n// vite.config.js\nexport default {\n // config options\n }\n```\n\n========================================\n\nCode:\n```text\n\"name\": \"web-app-new\",\n  \"version\": \"0.0.0\",\n  \"scripts\": {\n    \"dev\": \"vite --port 5000 --host\",\n    \"build\": \"vite build\",\n    \"preview\": \"vite preview --port 4173\",\n    \"test:unit\": \"vitest --environment jsdom\"\n  },\n  \"dependencies\": {\n    \"axios\": \"^0.27.2\",\n    \"crypto-js\": \"^4.1.1\",\n    \"firebase\": \"^8.10.1\",\n    \"jwt-decode\": \"^3.1.2\",\n    \"maska\": \"^1.5.0\",\n    \"mdi-vue\": \"^3.0.13\",\n    \"moment\": \"^2.29.4\",\n    \"pinia\": \"^2.0.16\",\n    \"uuid\": \"^8.3.2\",\n    \"v-calendar\": \"^3.0.0-alpha.8\",\n    \"v-viewer\": \"^3.0.10\",\n    \"vue\": \"^3.2.39\",\n    \"vue-router\": \"^4.1.2\",\n    \"vue3-cookies\": \"^1.0.6\",\n    \"vuefire\": \"^2.2.5\"\n  },\n  \"devDependencies\": {\n    \"@vitejs/plugin-vue\": \"^3.0.1\",\n    \"@vitejs/plugin-vue-jsx\": \"^2.0.0\",\n    \"@vue/test-utils\": \"^2.0.2\",\n    \"autoprefixer\": \"^10.4.8\",\n    \"jsdom\": \"^20.0.0\",\n    \"postcss\": \"^8.4.16\",\n    \"tailwindcss\": \"^3.1.8\",\n    \"vite\": \"^3.0.3\",\n    \"vitest\": \"^0.18.1\"\n  }\n}\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\";\nimport vueJsx from \"@vitejs/plugin-vue-jsx\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue(), vueJsx()],\n  build: {\n    /** If you set esmExternals to true, this plugins assumes that \n      all external dependencies are ES modules */\n\n    commonjsOptions: {\n      esmExternals: true,\n    },\n  },\n  resolve: {\n    alias: {\n      \"@\": fileURLToPath(new URL(\"./src\", import.meta.url)),\n    },\n  },\n});\n```\n\n```text\nimport { createApp, markRaw } from \"vue\";\nimport { createPinia } from \"pinia\";\nimport mdiVue from \"mdi-vue/v3\";\nimport * as mdijs from \"@mdi/js\";\n\nimport App from \"./App.vue\";\nimport router from \"./router\";\n\nimport \"./assets/main.css\";\nimport \"v-calendar/dist/style.css\";\nimport utils from \"./plugins/utils\";\nimport external from \"./plugins/utils.external\";\n// import { firestorePlugin } from \"vuefire\";\n\ntry {\n  const app = createApp(App);\n\n  const components = import.meta.globEager([\n    \"./components/*.vue\",\n    \"./components/Atoms/*.vue\",\n    \"./components/Atoms/Image/*.vue\",\n    \"./components/Atoms/Button/*.vue\",\n    \"./components/Atoms/Input/*.vue\",\n    \"./components/Atoms/Tabs/*.vue\",\n    \"./components/Molecules/*.vue\",\n    \"./components/Molecules/Modal/*.vue\",\n    \"./components/Molecules/Transition/*.vue\",\n    \"./components/Organism/*.vue\",\n    \"./components/Organism/Absensi/*.vue\",\n    \"./components/Organism/Pengaturan/*.vue\",\n  ]);\n\n  Object.entries(components).forEach(([path, definition]) => {\n    // components/Atoms/Container.vue become => AtomsContainer\n    const componentName = path.replace(/(.vue|\\/|\\.|components|index)/g, \"\");\n    // Register component on this Vue instance\n    // console.log(`😎  ${componentName} loaded`);\n    app.component(componentName, definition.default);\n  });\n  // @plugins\n\n  //@pinia\n  const pinia = createPinia();\n  pinia.use(({ store }) => {\n    store.$router = markRaw(router);\n    store.$app = app;\n    store.$globalProperties = app.config.globalProperties;\n  });\n  app.use(pinia);\n\n  //@others\n  // app.use(firestorePlugin, {});\n  app.use(mdiVue, {\n    icons: mdijs,\n  });\n  app.use(utils, {});\n  app.use(external, {});\n\n  app.use(router);\n  app.mount(\"#app\");\n} catch (error) {\n  console.log(error);\n}\n```\n\n```text\nimport { createRouter, createWebHistory } from \"vue-router\";\nimport { useStorage } from \"@/composables/storage\";\nimport { useLoadingStore } from \"@/stores/loading\";\nimport { useUserStore } from \"@/stores/user\";\nimport { useClientStore } from \"@/stores/client\";\nimport { useWorkerStore } from \"@/stores/worker\";\n\nconst router = createRouter({\n  history: createWebHistory(import.meta.env.BASE_URL),\n  routes: [\n    {\n      redirect: \"/login\",\n    },\n    {\n      path: \"/login\",\n      name: \"login\",\n      component: import(\"@/views/Test.vue\"),\n      // meta: {\n      //   layout: \"Auth\",\n      // },\n    },\n    {\n      path: \"/daftar\",\n      name: \"daftar\",\n      redirect: \"/daftar\",\n      component: () => import(\"@/components/Atoms/NestedWrapper.vue\"),\n      children: [\n        {\n          path: \"/daftar\",\n          name: \"daftar\",\n          component: import(\"@/views/Daftar/index.vue\"),\n          meta: {\n            icon: \"history\",\n            // layout: \"Auth\",\n          },\n        },\n        {\n          path: \"/daftar/akun\",\n          name: \"daftar akun\",\n          redirect: \"/daftar/akun\",\n          component: () => import(\"@/components/Atoms/NestedWrapper.vue\"),\n          children: [\n            {\n              path: \"/daftar/akun\",\n              name: \"daftar akun\",\n              component: import(\"@/views/Daftar/Akun/index.vue\"),\n              meta: {\n                icon: \"account\",\n                layout: \"Plain\",\n                validate: ({ next, userStore }) => {\n                  ((!userStore.$state?.form?.idNumber ||\n                    !userStore.$state?.form?.email) &&\n                    next(\"/daftar\")) ||\n                    next();\n                },\n              },\n            },\n            {\n              path: \"/daftar/akun/buat\",\n              name: \"buat akun baru\",\n              component: import(\"@/views/Daftar/Akun/Buat.vue\"),\n              meta: {\n                icon: \"account\",\n                layout: \"Plain\",\n                validate: ({ next, userStore }) => {\n                  ((!userStore.$state?.form?.idNumber ||\n                    !userStore.$state?.form?.email) &&\n                    next(\"/daftar\")) ||\n                    next();\n                },\n              },\n            },\n          ],\n          meta: {},\n        },\n        {\n          path: \"/daftar/perusahaan\",\n          name: \"daftar perusahaan\",\n          redirect: \"/daftar/perusahaan\",\n          component: () => import(\"@/components/Atoms/NestedWrapper.vue\"),\n          children: [\n            {\n              path: \"/daftar/perusahaan\",\n              name: \"daftar perusahaan\",\n              component: import(\"@/views/Daftar/Perusahaan/index.vue\"),\n              meta: {\n                icon: \"history\",\n                layout: \"Plain\",\n              },\n            },\n            {\n              path: \"/daftar/perusahaan/akun\",\n              name: \"daftar akun perusahaan\",\n              component: import(\"@/views/Daftar/Perusahaan/Akun.vue\"),\n              meta: {\n                icon: \"account\",\n                layout: \"Plain\",\n                validate: ({ next, workerStore, clientStore }) => {\n                  (!clientStore.$state?.form && next(\"/daftar\")) || next();\n                },\n              },\n            },\n          ],\n          meta: {},\n        },\n        {\n          path: \"/daftar/pekerja\",\n          name: \"daftar pekerja\",\n          redirect: \"/daftar/pekerja\",\n          component: () => import(\"@/components/Atoms/NestedWrapper.vue\"),\n          children: [\n            {\n              path: \"/daftar/pekerja\",\n              name: \"daftar pekerja\",\n              component: import(\"@/views/Daftar/Pekerja/index.vue\"),\n              meta: {\n                icon: \"history\",\n                layout: \"Plain\",\n                validate: ({ next, workerStore, clientStore }) => {\n                  (!workerStore.$state?.form?.idNumber && next(\"/daftar\")) ||\n                    next();\n                },\n              },\n            },\n            {\n              path: \"/daftar/pekerja/akun\",\n              name: \"daftar akun pekerja\",\n              component: import(\"@/views/Daftar/Pekerja/Akun.vue\"),\n              meta: {\n                icon: \"account\",\n                layout: \"Plain\",\n                validate: ({ next, workerStore, clientStore }) => {\n                  ((!workerStore.$state?.form ||\n                    !workerStore.$state?.form?.idNumber) &&\n                    next(\"/daftar\")) ||\n                    next();\n                },\n              },\n            },\n          ],\n          meta: {},\n        },\n      ],\n      meta: {\n        // layout: \"Auth\",\n      },\n    },\n    {\n      path: \"/app\",\n      redirect: \"/app/beranda\",\n    },\n    {\n      path: \"/app/beranda\",\n      name: \"beranda\",\n      component: import(\"@/views/Beranda.vue\"),\n      meta: {\n        layout: \"Auth\",\n      },\n    },\n    {\n      path: \"/app/404\",\n      name: \"404\",\n      component: () => import(\"@/views/404.vue\"),\n      meta: {\n        // type: [roles.All],\n        layout: \"Auth\",\n        hidden: true,\n      },\n    },\n    {\n      path: \"/app/:pathMatch(.*)*\",\n      redirect: \"/app/wrong\",\n    },\n  ],\n});\n\nrouter.beforeEach(async (to, from, next) => {\n  const loadingStore = useLoadingStore();\n  const userStore = useUserStore();\n  const clientStore = useClientStore();\n  const workerStore = useWorkerStore();\n  loadingStore.setLoading({\n    skeleton: true,\n  });\n  if (to?.meta?.layout !== from?.meta?.layout) {\n    loadingStore.setLoading({\n      layout: true,\n    });\n    await new Promise((res) => setTimeout(() => res(true), 1000));\n  }\n  if (to?.path !== from?.path) {\n    loadingStore.setLoading({\n      global: true,\n    });\n  }\n  try {\n    if (useStorage(\"credentials\")?.refresh) {\n      await userStore.statusUser();\n    }\n    if (userStore.isLoggedIn && !to.fullPath.includes(\"app\")) {\n      return next({ path: \"/app\" });\n    }\n    if (!userStore.isLoggedIn && to.fullPath.includes(\"app\")) {\n      return next({ path: \"/login\" });\n    }\n    if (to.meta?.validate && typeof to.meta?.validate === \"function\") {\n      return to.meta?.validate({\n        to,\n        from,\n        next,\n        userStore,\n        clientStore,\n        workerStore,\n      });\n    } else {\n      next();\n    }\n  } catch (error) {\n    return Promise.reject(error);\n  }\n});\n\nrouter.afterEach(async (to, from, failure) => {\n  const loadingStore = useLoadingStore();\n  const userStore = useUserStore();\n  try {\n    // if (!userStore.isLoggedIn) {\n    //   router.push(\"/\");\n    // }\n  } catch (error) {\n    return Promise.reject(error);\n  } finally {\n    loadingStore.clearLoading();\n  }\n});\n\nexport default router;\n```\n\n```text\nimport Layout from \"@/layouts/index.vue\";\nimport { onMounted } from \"vue\";\nimport { RouterLink, RouterView } from \"vue-router\";\nimport { useLoadingStore } from \"./stores/loading\";\n\nonMounted(() => {\n  document.documentElement.style.scrollBehavior = \"smooth\";\n  document.documentElement.style.overflow = \"auto\";\n  useLoadingStore().setLoading({ layout: true });\n});\n</script>\n\n<template>\n  <div class=\"min-h-screen\">\n    <atoms-loading />\n    <atoms-alert />\n    <atoms-transition />\n    <!-- <atoms-swipe /> -->\n    <molecules-modal />\n    <!-- <router-view /> -->\n    <Layout />\n  </div>\n</template>\n```\n\n```text\nimport AppLayoutDefault from \"./Default.vue\";\nimport ErrorLayout from \"./Error.vue\";\nimport { markRaw, onErrorCaptured, onMounted, ref, watch } from \"vue\";\nimport { useRoute, useRouter } from \"vue-router\";\n\nconst layout = ref();\nconst route = useRoute();\n\nwatch(\n  () => route.meta?.layout || undefined,\n  async (metaLayout) => {\n    try {\n      const component =\n        metaLayout && (await import(/* @vite-ignore */ `./${metaLayout}.vue`));\n      layout.value = markRaw(component?.default || AppLayoutDefault);\n    } catch (e) {\n      layout.value = markRaw(ErrorLayout);\n    }\n  },\n  { immediate: true }\n);\n\nonErrorCaptured(() => {\n  // layout.value = markRaw(ErrorLayout);\n});\n</script>\n\n<template>\n  <component :is=\"layout\"> <router-view /> </component>\n</template>\n```\n\n```text\nlayouts/index.vue\n```\n\n```text\n{\n      path: \"/login\",\n      name: \"login\",\n      // add async/await \n      component: async () => await import(\"@/views/Test.vue\"),\n      // meta: {\n      //   layout: \"Auth\",\n      // },\n},\n```\n\n```text\n// vite.config.js\nexport default {\n    // config options\n  }\n```\n\n```text\nnpm create vite@latest client --template vanilla\n```\n\n```text\nvite.config.js\n```\n\n========================================\n\nComments:\n- Do you have any errors in the console? Can you explain why you set `esmExternals` in the build section of the vite.config (I guess that's where your build breaks)?\n- @StefanoNepa the console is clear, there is nothing appear and i guess `esmExternals` came from default project generator (create-vue as mentioned here https://vuejs.org/guide/quick-start.html#creating-a-vue-appl&zwnj;&#8203;ication:~:text=%3E%2&zwnj;&#8203;0npm%20init%20vue%40&zwnj;&#8203;latest)\n- it seems only layouts files (from above screenshots) work. I've tried this #72005194 but only makes the layouts view gone\n- so, no errors, but what does the page source look like? i.e. the HTML the browser receives\n- I am facing the same issue. Any solution yet?\n- @MuhammadSiddiqui i just post the answer","metadata":{"transformedAt":"2026-08-18T18:33:46.432Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":941,"estimatedTokens":5645}}497{"id":"stack-78059795","source":"stackoverflow","questionId":78059795,"title":"@apollo_client.js?v=dbeae2a1:78 Uncaught Error: Could not resolve \"react\" imported by \"rehackt\". Is it installed?","tags":["reactjs","vuejs3","vite"],"text":"Title: @apollo_client.js?v=dbeae2a1:78 Uncaught Error: Could not resolve \"react\" imported by \"rehackt\". Is it installed?\nTags: reactjs, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nWhile using apollo client in vite, I get the error `@apollo_client.js?v=dbeae2a1:78 Uncaught Error: Could not resolve \"react\" imported by \"rehackt\". Is it installed?` in the console even though I want the library without react (vanilla javascript)? I imported ApolloClient from `@apollo/client/core` My main.js:\n\n```\n//src/main.js\nimport { createApp } from 'vue';\nimport App from './App.vue';\nimport { ApolloClient, gql, createHttpLink, InMemoryCache } from '@apollo/client/core';\nimport { DefaultApolloClient } from '@vue/apollo-composable';\nimport { createRouter, createWebHashHistory } from 'vue-router';\nimport Post from '@/components/Post.vue';\nimport Author from '@/components/Author.vue';\nimport PostsByTag from '@/components/PostsByTag.vue';\nimport AllPosts from '@/components/AllPosts.vue';\n\nconst httpLink = createHttpLink({\n uri: 'https://localhost:8000/graphql',\n});\n\nconst apolloClient = new ApolloClient({\n link: httpLink,\n cache: new InMemoryCache(),\n});\nconst routes = [\n { path: '/author/:username', component: Author },\n { path: '/post/:slug', component: Post },\n { path: '/tag/:tag', component: PostsByTag },\n { path: '/', component: AllPosts },\n];\nconst router = createRouter({\n history: createWebHashHistory(),\n routes: routes,\n});\n\nconst app = createApp(App);\n\napp.provide(DefaultApolloClient, apolloClient);\n\napp.mount('#app');\n```\n\n========================================\n\nTop Answer:\nInstead of importing\nfrom: @apollo/client\nuse: @apollo/client/core\n\n========================================\n\nCode:\n```text\n//src/main.js\nimport { createApp } from 'vue';\nimport App from './App.vue';\nimport { ApolloClient, gql, createHttpLink, InMemoryCache } from '@apollo/client/core';\nimport { DefaultApolloClient } from '@vue/apollo-composable';\nimport { createRouter, createWebHashHistory } from 'vue-router';\nimport Post from '@/components/Post.vue';\nimport Author from '@/components/Author.vue';\nimport PostsByTag from '@/components/PostsByTag.vue';\nimport AllPosts from '@/components/AllPosts.vue';\n\nconst httpLink = createHttpLink({\n    uri: 'https://localhost:8000/graphql',\n});\n\nconst apolloClient = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n});\nconst routes = [\n  { path: '/author/:username', component: Author },\n  { path: '/post/:slug', component: Post },\n  { path: '/tag/:tag', component: PostsByTag },\n  { path: '/', component: AllPosts },\n];\nconst router = createRouter({\n    history: createWebHashHistory(),\n    routes: routes,\n});\n\nconst app = createApp(App);\n\napp.provide(DefaultApolloClient, apolloClient);\n\napp.mount('#app');\n```\n\n```text\n@apollo_client.js?v=dbeae2a1:78 Uncaught Error: Could not resolve \"react\" imported by \"rehackt\". Is it installed?\n```\n\n```text\n@apollo/client/core\n```\n\n```text\n-import ApolloClient from 'apollo-client'\n-import { ApolloLink, concat } from 'apollo-link'\n-import { HttpLink } from 'apollo-link-http'\n-import { split } from 'apollo-link'\n-import { onError } from 'apollo-link-error'\n-import { InMemoryCache, defaultDataIdFromObject } from 'apollo-cache-inmemory'\n+import { ApolloClient } from '@apollo/client/core'\n+import { ApolloLink, HttpLink, split, concat } from '@apollo/client/core'\n+import { onError } from '@apollo/client/link/error'\n+import { InMemoryCache, defaultDataIdFromObject } from '@apollo/client/cache'\n-import gql from \"graphql-tag\"\n+import { gql } from \"@apollo/client/core\"\n```\n\n```text\n@apollo/client\n```\n\n```text\nreact\n```\n\n========================================\n\nComments:\n- what version of **apollo_client** you are using\n- @apollo/client@3.9.5\n- Adding react didn't resolve the problem\n- try deleting **node_modules** folder and execute `npm install` than `npm cache clean` to make sure there is no cached dependencies . be aware that the you might get a new versions of your dependencies. if you want to keep the same old version for some reason\n- There are two node_modules, one in project root (VueProject) and another at VueProject/frontend. Which one should I delete?\n- The one in your project root ( vue0roject)\n- Just import from '@apollo/client/core' and it'll work again, it makes no sense at all to add react to a Vue project.","metadata":{"transformedAt":"2026-08-18T18:33:46.432Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":134,"estimatedTokens":1086}}498{"id":"stack-71955430","source":"stackoverflow","questionId":71955430,"title":"How to use an npm package component with Vite + Vue?","tags":["vue.js","vite","vue-select"],"text":"Title: How to use an npm package component with Vite + Vue?\nTags: vue.js, vite, vue-select\nSource: Stack Overflow\n\nQuestion:\nWhat would be the steps to add a component to Vite with Vue, as an npm package?\n\nI assumed these:\n\n- `npm install example`\n\n- open `src/App.vue` and add `import Example from 'example'`\n\n- in `App.vue`, in ``, add ``\n\nIs that correct?\n\nI am trying to install and use `vue-select` like so, but it's not working:\nhttps://i.sstatic.net/iVNiq.png\n\nhttps://i.sstatic.net/kufIU.png\n\n========================================\n\nTop Answer:\nThe process you described is correct, but you must also register the component before you can use it (within `components: { ... }`).\n\nSince you mentioned you're using `vue-select`, I will use that as an example.\n\n### Step #0 - Install\n\nAs you've already done, ensure your project is initialized (`npm init`), then run `yarn add vue-select` / `npm i vue-select`.\n\n### Step #1 - Initialize\n\nIn your `main.js`, import and register with:\n\n```\nimport VSelect from 'vue-select'; \n\nVue.component('v-select', VSelect);\n\n/* rest of your Vue initialization here */\n```\n\n### Step #2 - Use Component\n\n```\n\n```\n\nYou'll also need to import the stylesheet in your CSS, with:\n\n```\n@import 'vue-select/src/scss/vue-select.scss';\n```\n\n### Real Example\n\nIf you want to see a full example, I am using this package in one of my projects, I'm registering the component in my `main.js` and using it `ThemeSelector.vue`.\n\nAlso, if your project is large and/ or you're only using this component in one place, then a better approach would be to import it into the component that's using it. This is done in a similar way, but you must also register it under `components: { ... }` for it to be accessible within your ``.\n\n========================================\n\nCode:\n```text\nnpm install example\n```\n\n```text\nsrc/App.vue\n```\n\n```text\nimport Example from 'example'\n```\n\n```text\nApp.vue\n```\n\n```text\n<template>\n```\n\n```text\n<Example />\n```\n\n```text\nvue-select\n```\n\n```js\n// main.js\nimport VSelect from 'vue-select';\n\n// Vue.component('v-select', VSelect); ❌ Vue 2 code\n\nimport { createApp } from 'vue'\nimport App from './App.vue'\n\ncreateApp(App)\n  .component('v-select', VSelect) ✅\n  .mount('#app')\n```\n\n```html\n<script setup>\n// @import 'vue-select/src/scss/vue-select.scss'; ❌ The @ prefix is invalid in <script>\nimport 'vue-select/src/scss/vue-select.scss'; ✅\n</script>\n\n<!-- OR -->\n<style lang=\"scss\">\n@import 'vue-select/src/scss/vue-select.scss';\n</style>\n```\n\n```text\n$ npm i -D sass\n```\n\n```text\nvSelect\n```\n\n```text\n<script>\n```\n\n```text\n<script setup>\n```\n\n```text\nv-select\n```\n\n```text\ncreateApp()\n```\n\n```text\n@import\n```\n\n```text\n<script>\n```\n\n```text\n<style lang=\"scss\">\n```\n\n```text\n@\n```\n\n```text\nimport\n```\n\n```text\n<script>\n```\n\n```text\nsass\n```\n\n```js\nimport VSelect from 'vue-select'; \n\nVue.component('v-select', VSelect);\n\n/* rest of your Vue initialization here */\n```\n\n```html\n<v-select :options=\"[{label: 'Canada', code: 'ca'}]\"></v-select>\n```\n\n```css\n@import 'vue-select/src/scss/vue-select.scss';\n```\n\n```text\ncomponents: { ... }\n```\n\n```text\nvue-select\n```\n\n```text\nnpm init\n```\n\n```text\nyarn add vue-select\n```\n\n```text\nnpm i vue-select\n```\n\n```text\nmain.js\n```\n\n```text\nmain.js\n```\n\n```text\nThemeSelector.vue\n```\n\n```text\ncomponents: { ... }\n```\n\n```text\n<template>\n```\n\n========================================\n\nComments:\n- I think in this example Vue Select is bound to `v-select` instead of `vSelect` as in your code. Do you have a running code pen or something, and I can get it working and update my answer to be more relevant to your situation\n- I got the error ✘ [ERROR] Unexpected \"@\" script:/Users/hennotaht/www/vite-vue-test/src/App.vue?id=0:5&zwnj;&#8203;:0: 5 │ @import 'vue-select/src/scss/vue-select.scss'; ╵ ^\n- I suspect it's not the only thing wrong, as main.js does not have Vue variable. Here's what I did: github.com/henno/vite-vue-test/commit/&hellip;\n- I got it working! Big thanks! That repo was an attempt to Lissy93's instructions on a new Vite project. It seems her suggestions were based on older Vite. Stuff is evolving so fast in the JavaScript landscape and looks like the documentation is lagging behind. Can you point me to documentation which describes the way you used to register VSelect to Vue there? I spent a big part of yesterday trying to get this working but I never encountered such version of component registration anywhere.\n- The docs link for global component registration via `app.component()` is already in the answer :) Local component registration can be done via the `components` option (same as in Vue 2), or by importing the component in ``.","metadata":{"transformedAt":"2026-08-18T18:33:46.432Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":35,"totalLines":236,"estimatedTokens":1163}}499{"id":"stack-78229296","source":"stackoverflow","questionId":78229296,"title":"Google fonts not working using tailwind CSS in React Vite","tags":["reactjs","tailwind-css","vite","google-font-api"],"text":"Title: Google fonts not working using tailwind CSS in React Vite\nTags: reactjs, tailwind-css, vite, google-font-api\nSource: Stack Overflow\n\nQuestion:\nI'm banging my head against the wall. My project is in React with Vite and tailwind CSS configured. Now I want to use Google fonts in tailwind CSS. It doesn't work for some reason. All the tutorials seem to make me think it should be easy, so I'm guessing my problem is somewhere very easy to fix with someone experienced. Thanks in advance!\n\nhttps://i.sstatic.net/dP72i.png\n\nindex.css\n\n```\n@import url('https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap');\n\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\ntailwind.config.js\n\n```\n/** @type {import('tailwindcss').Config} */\nexport default {\n content: [\n \"./index.html\",\n \"./src/**/*.{js,ts,jsx,tsx}\",\n ],\n theme: {\n extend: {\n fontFamily: {\n inter: [\"Inter\", \"sans-serif\"],\n }\n },\n },\n plugins: [],\n}\n```\n\nindex.html\n\n```\n\n \n ...\n \n \n \n \n \n \n\n```\n\nvite.config.js\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\nimport tailwindcss from 'tailwindcss'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n css: {\n postcss: {\n plugins: [tailwindcss()],\n },\n }\n})\n```\n\npostcss.config.js\n\n```\nexport default {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n}\n```\n\n========================================\n\nTop Answer:\n### Update for TailwindCSS v4\n\nIn tailwind Version-4, we do not need to use `tailwind.config.js` configurations. I faced the issues in my current React-Vite project. The process is simpler now:\n\nAfter importing your font in index.css file (keeping it on the top), just add this line of code:\n\n```\n@theme {\n --font-inter: 'Inter', 'sans-serif';\n}\n```\n\nI am using Inter font, you can replace with your own font.\n\nhttps://i.sstatic.net/xFMPw2ei.png\n\nAnd for those who are unaware about the new changes to be made in `vite.config.js` for tailwind-4 to work with vite. Here are the updates:\n\n```\nimport { defineConfig } from 'vite'\nimport tailwindcss from '@tailwindcss/vite'\nimport react from '@vitejs/plugin-react'\n\nexport default defineConfig({\n plugins: [tailwindcss(), react()]\n})\n```\n\nFor the complete tailwind-4 with Vite apps update: Check TailwindCSS v4 with Vite on here on StackOverflow.\n\n========================================\n\nCode:\n```text\n@import url('https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap');\n\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n```text\n/** @type {import('tailwindcss').Config} */\nexport default {\n  content: [\n    \"./index.html\",\n    \"./src/**/*.{js,ts,jsx,tsx}\",\n  ],\n  theme: {\n    extend: {\n      fontFamily: {\n        inter: [\"Inter\", \"sans-serif\"],\n      }\n    },\n  },\n  plugins: [],\n}\n```\n\n```text\n<!doctype html>\n<html lang=\"en\">\n  <head>\n    ...\n  </head>\n  <body>\n    <div id=\"root\"></div>\n    <script src=\"https://cdn.tailwindcss.com\"></script>\n    <script type=\"module\" src=\"/src/main.jsx\"></script>\n  </body>\n</html>\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\nimport tailwindcss from 'tailwindcss'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  css: {\n    postcss: {\n      plugins: [tailwindcss()],\n    },\n  }\n})\n```\n\n```text\nexport default {\n  plugins: {\n    tailwindcss: {},\n    autoprefixer: {},\n  },\n}\n```\n\n```text\n/** @type {import('tailwindcss').Config} */\nexport default {\n  content: [\"./index.html\", \"./src/**/*.{js,ts,jsx,tsx}\"],\n  theme: {\n    extend: {\n      fontFamily: {\n        roboto: [\"Roboto\", \"sans-serif\"],\n      },\n    },\n  },\n\n  plugins: [],\n};\n```\n\n```text\n@import url(\"https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap\");\n\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n```text\nnpm run dev\n```\n\n```text\ntailwind.config.js\n```\n\n```text\nvite.config.js\n```\n\n```text\npostcss.config.js\n```\n\n```text\nvite.config.js\n```\n\n```text\npostcss.config.js\n```\n\n```text\ntailwind.config.js\n```\n\n```text\nindex.css\n```\n\n```text\n@theme {\n  --font-inter: 'Inter', 'sans-serif';\n}\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport tailwindcss from '@tailwindcss/vite'\nimport react from '@vitejs/plugin-react'\n\nexport default defineConfig({\n  plugins: [tailwindcss(), react()]\n})\n```\n\n```text\ntailwind.config.js\n```\n\n```text\nvite.config.js\n```\n\n========================================\n\nComments:\n- I tried all that, didn't work for me. The only thing worked was switching to regular react rather than react-swc when creating vite react project. I still don't know or find the reason why react-swc didn't work though.","metadata":{"transformedAt":"2026-08-18T18:33:46.432Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":268,"estimatedTokens":1184}}500{"id":"stack-70523260","source":"stackoverflow","questionId":70523260,"title":"Dynamically loading SVG in Vue3 and Vite","tags":["javascript","vue.js","vuejs3","vite"],"text":"Title: Dynamically loading SVG in Vue3 and Vite\nTags: javascript, vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to convert my Vue2/Webpack app to Vue3/Vite.\n\nIn Vue2/Webpack, this works:\n\n```\n\n```\n\nHtml-loader is added with:\n\n```\n\"html-loader\": \"1.3.2\",\n```\n\nIn Vue3/Vite this throws the error: `ReferenceError: require is not defined`\n\nI've looked around for an example of doing this but don't see how to do this without knowing the name of the file at compile time. Is that possible?\n\n========================================\n\nTop Answer:\nYou can take a look at vite-svg-loader plugin, and load SVG files as Vue components.\n\n========================================\n\nCode:\n```text\n<div v-html=\"require('!!html-loader!../../assets/icons/' + this.icon + '.svg')\"></div>\n```\n\n```text\n\"html-loader\": \"1.3.2\",\n```\n\n```text\nReferenceError: require is not defined\n```\n\n```text\n<script>\nconst getServiceIcon = async iconName => {\n  const module = await import(/* @vite-ignore */ `../assets/svg/${iconName}.svg`)\n  return module.default.replace(/^\\/@fs/, '')\n}\n\nexport default {\n  data() {\n    return {\n      icon: null,\n      iconName: 'icon1', // icon1.svg\n    }\n  },\n  watch: {\n    iconName: {\n      async handler(iconName) {\n        this.icon = await getServiceIcon(iconName)\n      },\n      immediate: true,\n    },\n  },\n}\n</script>\n\n<template>\n  <button @click=\"iconName = 'icon2'\">Change to another SVG</button>\n  <img :src=\"icon\" height=\"72\" width=\"72\" />\n</template>\n```\n\n```text\ndefineAsyncComponent\n```\n\n```text\nVue3\n```\n\n```text\nimport()\n```\n\n```text\n<template>\n    <i v-html=\"svg\" />\n</template>\n\n<script lang=\"ts\" setup>\n    import { computed } from 'vue';\n\n    const props = defineProps(['icon', 'src']);\n    const path = props.src ? props.src : '';\n    const file = `${path}icon-${props.icon}`;\n    const modules = import.meta.glob('../../assets/icons/**/*.svg', { as: 'raw' });\n\n    const svg = computed(() => {\n        return modules['../../assets/icons/' + file + '.svg'];\n    });\n</script>\n\n<style lang=\"scss\" scoped></style>\n```\n\n```text\n<UiIcon icon=\"NAME\" class=\"w-8 fill-current text-red-500\"/>\n```\n\n========================================\n\nComments:\n- This is perfect. I am on a quest to use as few third party plugins as possible, and use only svg. Used this to create a component to replace zondicons, just changig the watcher to mounted. (never liked the heroicon method of one component for each icon...). thx / mike\n- Did you really use v-html?!","metadata":{"transformedAt":"2026-08-18T18:33:46.432Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":116,"estimatedTokens":622}}501{"id":"stack-79296606","source":"stackoverflow","questionId":79296606,"title":"Vue 3: Error on creation \"Expected identifier but found 'import'\"","tags":["javascript","vue.js","vuejs3","vite"],"text":"Title: Vue 3: Error on creation \"Expected identifier but found 'import'\"\nTags: javascript, vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI try to create a new vue 3 application but i have a problem with creation.\n\nNode version: 22.10.0\nNpm version: 10.9.0\n\nI create my project with:\n`npm create vue@latest`\nlike in the docs\n\nAnd when i try to run the code with `npm run dev`\n\nI got this errror\n\n```\nX [ERROR] Expected identifier but found \"import\"\n\n (define name):1:0:\n 1 │ import.meta.url\n ╵ ~~~~~~\n\nfailed to load config from C:\\Apache24\\htdocs\\testvue3\\vite.config.mjs\nerror when starting dev server:\nError: Build failed with 3 errors:\n(define name):1:0: ERROR: Expected identifier but found \"import\"\n```\n\nI haven't touched any line of code yet and the problem seems to come from the vite.config.ts file below\n\n```\nimport { fileURLToPath, URL } from 'node:url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport vueDevTools from 'vite-plugin-vue-devtools'\n\n// https://vite.dev/config/\nexport default defineConfig({\n plugins: [\n vue(),\n vueDevTools(),\n ],\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url))\n },\n },\n})\n```\n\n========================================\n\nCode:\n```text\nX [ERROR] Expected identifier but found \"import\"\n\n    (define name):1:0:\n      1 │ import.meta.url\n        ╵ ~~~~~~\n\nfailed to load config from C:\\Apache24\\htdocs\\testvue3\\vite.config.mjs\nerror when starting dev server:\nError: Build failed with 3 errors:\n(define name):1:0: ERROR: Expected identifier but found \"import\"\n```\n\n```text\nimport { fileURLToPath, URL } from 'node:url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport vueDevTools from 'vite-plugin-vue-devtools'\n\n// https://vite.dev/config/\nexport default defineConfig({\n  plugins: [\n    vue(),\n    vueDevTools(),\n  ],\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url))\n    },\n  },\n})\n```\n\n```text\nnpm create vue@latest\n```\n\n```text\nnpm run dev\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.432Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":98,"estimatedTokens":506}}502{"id":"stack-77317584","source":"stackoverflow","questionId":77317584,"title":"Vite build mode development results in error Could not resolve entry module \"development/index.html\"","tags":["vue.js","vuejs3","vite"],"text":"Title: Vite build mode development results in error Could not resolve entry module \"development/index.html\"\nTags: vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI am new to Vite but I am not new to Vue. I haven't used Vue much since 2.0 and I am now creating a new PWA on Vue3. I see Vue3 has a new library called Vite for deploying and running development servers.\n\nAs a background I have another similar Vue app that doesn't use Vite where I have 3 .env files, `.env.development`, `.env.staging`, and `.env.production`.\n\nIn my old VueJS application these env variables work correctly when I do `npm run build --mode development` and the app builds and sets variables to use their dev versions correctly, but with Vite I am trying to do a similar thing but I'm getting weird results. I know it's something I'm doing wrong because I can't find anyone having the same issue on using Google.\n\nBasically I want my Vue application to use different variables depending on what env I'm deploying for which worked on my older Vue application but I can't get it to work with Vite.\n\nWhenever I do `npm run build --mode development` I get an error\n\n```\nCould not resolve entry module \"development/index.html\".\nerror during build:\nRollupError: Could not resolve entry module \"development/index.html\".\n at error (file:///Users/khernandez/Desktop/Sprint23-21/OnlineScheduler/node_modules/rollup/dist/es/shared/node-entry.js:2287:30)\n at ModuleLoader.loadEntryModule (file:///Users/khernandez/Desktop/Sprint23-21/OnlineScheduler/node_modules/rollup/dist/es/shared/node-entry.js:24881:20)\n```\n\nAs if its looking for a folder called `development`. I *DONT* want to create a new folder for every env, I just want my env variables to switch so that my Vue application can use the correct data depending on where I am deploying to.\n\nI have a sneaking suspicion that I am misunderstanding how Vite does deployment but I'm not sure what exactly I am misunderstanding. What am I doing wrong?\n\n========================================\n\nTop Answer:\nYou can use an extra set of `--` to signify to npm that your arguments are done and to send the rest to the command. That way you can use your single NPM build task to do multiple modes.\n\n- `npm run build -- --mode development`\n\n- `npm run build -- --mode qa`\n\n- etc\n\n========================================\n\nCode:\n```text\nCould not resolve entry module \"development/index.html\".\nerror during build:\nRollupError: Could not resolve entry module \"development/index.html\".\n    at error (file:///Users/khernandez/Desktop/Sprint23-21/OnlineScheduler/node_modules/rollup/dist/es/shared/node-entry.js:2287:30)\n    at ModuleLoader.loadEntryModule (file:///Users/khernandez/Desktop/Sprint23-21/OnlineScheduler/node_modules/rollup/dist/es/shared/node-entry.js:24881:20)\n```\n\n```text\n.env.development\n```\n\n```text\n.env.staging\n```\n\n```text\n.env.production\n```\n\n```text\nnpm run build --mode development\n```\n\n```text\nnpm run build --mode development\n```\n\n```text\ndevelopment\n```\n\n```json\n\"scripts\": {\n  \"build\": \"vite build --mode development\"\n}\n```\n\n```text\n--mode\n```\n\n```text\nbuild\n```\n\n```text\nnpm run build\n```\n\n```text\n--\n```\n\n```text\nnpm run build -- --mode development\n```\n\n```text\nnpm run build -- --mode qa\n```\n\n========================================\n\nComments:\n- That did the trick, i was not aware that npm run command doesnt pass parameters to whatever it runs.\n- Absolutely man. I know it's a bit late, but I stumbled upon this looking for something else and figured I'd add it in there.\n- This is the correct solution. For example: `\"build\": \"vite build\", \"build:dev\": \"npm run build -- --mode development\",`","metadata":{"transformedAt":"2026-08-18T18:33:46.432Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":109,"estimatedTokens":912}}503{"id":"stack-73924272","source":"stackoverflow","questionId":73924272,"title":"import.meta undefined in components (Vite/Vue3)","tags":["environment-variables","vuejs3","vite"],"text":"Title: import.meta undefined in components (Vite/Vue3)\nTags: environment-variables, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI am trying to access the import.meta.env Variable 'APP_SOCKET_URL' in my component but it says **Uncaught TypeError: import_meta.env is undefined**\n\nIn my `main.js` file import.meta.env works fine. In all other files it doesn't work and I don't know why. Maybe someone can help me there.\n\nHere is the code of my data function:\n\n```\ndata() {\n const socket = new Socket(import.meta.env.APP_SOCKET_URL || `ws://${location.href}/ws`);\n return {\n socket\n };\n}\n```\n\nIn my .env file I added:\n\n```\nAPP_SOCKET_URL=\"ws://localhost:8765\"\n```\n\nAnd in my `vite.config` I changed the envPreix to \"APP_\"\n\nHere is my Setup:\n\n```\nVite Version 3.1.4 \n\nVue 3 Version 3.2.40\nProgramming in Typescript\nThanks and have a nice day!\n```\n\nEDIT:\n\nI found the error. If I change the script lag from 'ts' to 'js' it works. So the problem is with typescript, but I don't know how to fix that.\n\n========================================\n\nTop Answer:\nAll environment vars in a Vite app must begin their identifier with `VITE_`\n\nSo your var may now look like: `VITE_APP_SOCKET_URL=\"ws://localhost:8765\"`\n\n========================================\n\nCode:\n```js\ndata() {\n  const socket = new Socket(import.meta.env.APP_SOCKET_URL || `ws://${location.href}/ws`);\n  return {\n    socket\n  };\n}\n```\n\n```text\nAPP_SOCKET_URL=\"ws://localhost:8765\"\n```\n\n```text\nVite Version 3.1.4 <br>\nVue 3 Version 3.2.40\nProgramming in Typescript\nThanks and have a nice day!\n```\n\n```text\nmain.js\n```\n\n```text\nvite.config\n```\n\n```text\nVITE_\n```\n\n```text\nVITE_APP_SOCKET_URL=\"ws://localhost:8765\"\n```\n\n```text\nimport.meta.env.MODE\n```\n\n```text\nVite\n```\n\n```text\nVITE_\n```\n\n```text\nAPP_SOCKET_URL\n```\n\n```text\nVITE_APP_SOCKET_URL\n```\n\n========================================\n\nComments:\n- Isn't this answer the same as Anthony Oruovo's?","metadata":{"transformedAt":"2026-08-18T18:33:46.432Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":112,"estimatedTokens":477}}504{"id":"stack-77313962","source":"stackoverflow","questionId":77313962,"title":"Vite project starts with an error \"Preprocessor dependency \"sass\" failed to load\"","tags":["node.js","sass","vite"],"text":"Title: Vite project starts with an error \"Preprocessor dependency \"sass\" failed to load\"\nTags: node.js, sass, vite\nSource: Stack Overflow\n\nQuestion:\nI install my dependencies in my Vite project (React+TS) and try to run it (I use yarn dev), and then I get an error:\n\nPreprocessor dependency \"sass\" failed to load\n\nThis is my package.json:\n\n```\n\"dependencies\": {\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\",\n \"react-use-websocket\": \"3.0.0\",\n \"sass\": \"^1.69.3\"\n },\n \"devDependencies\": {\n \"@types/react\": \"^18.2.15\",\n \"@types/react-dom\": \"^18.2.7\",\n \"@typescript-eslint/eslint-plugin\": \"^6.0.0\",\n \"@typescript-eslint/parser\": \"^6.0.0\",\n \"@vitejs/plugin-react\": \"^4.0.3\",\n \"eslint\": \"^8.45.0\",\n \"eslint-plugin-react-hooks\": \"^4.6.0\",\n \"eslint-plugin-react-refresh\": \"^0.4.3\",\n \"typescript\": \"^5.0.2\",\n \"vite\": \"^4.4.5\"\n }\n```\n\nThis problem occurs on my work computer (I did the project on my personal laptop and everything runs fine there, the project was cloned from my repository).\n\nFull error message:\n\n[plugin:vite:css] Preprocessor dependency \"sass\" failed to load:\n\nCannot read properties of undefined (reading 'pop')\n\n========================================\n\nTop Answer:\nUpgrading to Node v21.1.0 fixed it for me.\n\n========================================\n\nCode:\n```text\n\"dependencies\": {\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\",\n    \"react-use-websocket\": \"3.0.0\",\n    \"sass\": \"^1.69.3\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^18.2.15\",\n    \"@types/react-dom\": \"^18.2.7\",\n    \"@typescript-eslint/eslint-plugin\": \"^6.0.0\",\n    \"@typescript-eslint/parser\": \"^6.0.0\",\n    \"@vitejs/plugin-react\": \"^4.0.3\",\n    \"eslint\": \"^8.45.0\",\n    \"eslint-plugin-react-hooks\": \"^4.6.0\",\n    \"eslint-plugin-react-refresh\": \"^0.4.3\",\n    \"typescript\": \"^5.0.2\",\n    \"vite\": \"^4.4.5\"\n  }\n```\n\n```text\nnavigator.userAgent\n```\n\n```text\ndiff -U2 sass.dart.js.orig sass.dart.js\n--- sass.dart.js.orig   2023-11-11 18:33:51.444169600 +0100\n+++ sass.dart.js        2023-11-11 18:36:34.287463700 +0100\n@@ -116830,4 +116830,5 @@\n     if (typeof navigator != \"object\") return hooks;\n     var ua = navigator.userAgent;\n+    if (!ua) return hooks;\n     if (ua.indexOf(\"DumpRenderTree\") >= 0) return hooks;\n     if (ua.indexOf(\"Chrome\") >= 0) {\n@@ -116864,4 +116865,5 @@\n     B.C_JS_CONST5 = function(hooks) {\n   var userAgent = typeof navigator == \"object\" ? navigator.userAgent : \"\";\n+  if (!userAgent) return hooks;\n   if (userAgent.indexOf(\"Firefox\") == -1) return hooks;\n   var getTag = hooks.getTag;\n@@ -116881,4 +116883,5 @@\n     B.C_JS_CONST4 = function(hooks) {\n   var userAgent = typeof navigator == \"object\" ? navigator.userAgent : \"\";\n+  if (!userAgent) return hooks;\n   if (userAgent.indexOf(\"Trident/\") == -1) return hooks;\n   var getTag = hooks.getTag;\n```\n\n```text\nsass.dart.js\n```\n\n```text\nnode_modules/sass\n```\n\n========================================\n\nComments:\n- Yes, this worked for me as well. The problem at least in v21.0.0.","metadata":{"transformedAt":"2026-08-18T18:33:46.432Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":109,"estimatedTokens":736}}505{"id":"stack-74049355","source":"stackoverflow","questionId":74049355,"title":"vitest test coverage does not fail when threshold is not met","tags":["javascript","typescript","vuejs3","vite","vitest"],"text":"Title: vitest test coverage does not fail when threshold is not met\nTags: javascript, typescript, vuejs3, vite, vitest\nSource: Stack Overflow\n\nQuestion:\ni want my test coverage to fail if the thresholds are not met\n\n```\nexport default defineConfig({\n plugins: [vue()],\n test: {\n environment: \"happy-dom\",\n exclude: [...configDefaults.exclude, \"**/tests/e2e/*\"],\n coverage: {\n reporter: ['text', 'json', 'html'],\n lines: 80,\n functions: 80,\n branches: 80,\n statements: 80,\n }\n },\n```\n\neven though i get the error message, it still shows pass\n\n```\nFile | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s \n------------------------|---------|----------|---------|---------|-------------------\nAll files | 100 | 33.33 | 100 | 100 | \n components/base/button | 100 | 33.33 | 100 | 100 | \n Button.vue | 100 | 33.33 | 100 | 100 | 36-53 \n config | 100 | 100 | 100 | 100 | \n index.ts | 100 | 100 | 100 | 100 | \n------------------------|---------|----------|---------|---------|-------------------\nERROR: Coverage for branches (33.33%) does not meet global threshold (80%)\n\n PASS Waiting for file changes...\n press h to show help, press q to quit\n```\n\nany help?\n\n========================================\n\nTop Answer:\nI think mine works, I'm sharing my vite config file, hope it helps you:\n\n```\n/// \nimport { fileURLToPath, URL } from 'url';\nimport { defineConfig, loadEnv } from 'vite';\nimport vue from '@vitejs/plugin-vue';\nimport type { UserConfig as VitestUserConfigInterface } from 'vitest/config';\n\nconst vitestConfig: VitestUserConfigInterface = {\n test: {\n watch: false,\n include: ['**/tests/unit/**/*.spec.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],\n globals: true,\n environment: 'jsdom',\n reporters: ['verbose'],\n coverage: {\n include: ['src/**/*'],\n exclude: [\n 'src/main.ts',\n 'src/plugins/',\n 'src/App.vue',\n 'src/shims-vue.d.ts',\n 'src/router/*',\n 'src/stores/*',\n 'src/types/*',\n 'src/components/icons/*'\n ],\n reporter: ['text', 'json', 'html'],\n all: true,\n lines: 80,\n functions: 80,\n branches: 80,\n statements: 80\n }\n }\n};\n\nexport default defineConfig(({ mode }) => {\n // https://github.com/vitejs/vite/issues/1149#issuecomment-857686209\n const env = loadEnv(mode, process.cwd());\n const envWithProcessPrefix = Object.entries(env).reduce(\n (prev, [key, val]) => {\n const [, keyNoVite] = key.split('VITE_');\n return {\n ...prev,\n ['process.env.' + key]: `\"${val}\"`,\n ['process.env.' + keyNoVite]: `\"${val}\"`\n };\n },\n {}\n );\n\n return {\n define: envWithProcessPrefix,\n test: vitestConfig.test,\n resolve: {\n alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) }\n },\n plugins: [vue()]\n };\n});\n```\n\n========================================\n\nCode:\n```text\nexport default defineConfig({\n  plugins: [vue()],\n  test: {\n    environment: \"happy-dom\",\n    exclude: [...configDefaults.exclude, \"**/tests/e2e/*\"],\n    coverage: {\n      reporter: ['text', 'json', 'html'],\n      lines: 80,\n      functions: 80,\n      branches: 80,\n      statements: 80,\n    }\n  },\n```\n\n```text\nFile                    | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s \n------------------------|---------|----------|---------|---------|-------------------\nAll files               |     100 |    33.33 |     100 |     100 |                   \n components/base/button |     100 |    33.33 |     100 |     100 |                   \n  Button.vue            |     100 |    33.33 |     100 |     100 | 36-53             \n config                 |     100 |      100 |     100 |     100 |                   \n  index.ts              |     100 |      100 |     100 |     100 |                   \n------------------------|---------|----------|---------|---------|-------------------\nERROR: Coverage for branches (33.33%) does not meet global threshold (80%)\n\n PASS  Waiting for file changes...\n       press h to show help, press q to quit\n```\n\n```js\n{\n  test: {\n    ...your other configurations\n    coverage: {\n      ...your other configurations\n      thresholds: {\n        lines: 80,\n        functions: 80,\n        branches: 80,\n        statements: 80\n      }\n    }\n  }\n}\n```\n\n```text\nthresholds\n```\n\n```text\nvitest run\n```\n\n```text\nvitest watch\n```\n\n```js\n/// <reference types=\"vitest\" />\nimport { fileURLToPath, URL } from 'url';\nimport { defineConfig, loadEnv } from 'vite';\nimport vue from '@vitejs/plugin-vue';\nimport type { UserConfig as VitestUserConfigInterface } from 'vitest/config';\n\nconst vitestConfig: VitestUserConfigInterface = {\n  test: {\n    watch: false,\n    include: ['**/tests/unit/**/*.spec.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],\n    globals: true,\n    environment: 'jsdom',\n    reporters: ['verbose'],\n    coverage: {\n      include: ['src/**/*'],\n      exclude: [\n        'src/main.ts',\n        'src/plugins/',\n        'src/App.vue',\n        'src/shims-vue.d.ts',\n        'src/router/*',\n        'src/stores/*',\n        'src/types/*',\n        'src/components/icons/*'\n      ],\n      reporter: ['text', 'json', 'html'],\n      all: true,\n      lines: 80,\n      functions: 80,\n      branches: 80,\n      statements: 80\n    }\n  }\n};\n\nexport default defineConfig(({ mode }) => {\n  // https://github.com/vitejs/vite/issues/1149#issuecomment-857686209\n  const env = loadEnv(mode, process.cwd());\n  const envWithProcessPrefix = Object.entries(env).reduce(\n    (prev, [key, val]) => {\n      const [, keyNoVite] = key.split('VITE_');\n      return {\n        ...prev,\n        ['process.env.' + key]: `\"${val}\"`,\n        ['process.env.' + keyNoVite]: `\"${val}\"`\n      };\n    },\n    {}\n  );\n\n  return {\n    define: envWithProcessPrefix,\n    test: vitestConfig.test,\n    resolve: {\n      alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) }\n    },\n    plugins: [vue()]\n  };\n});\n```\n\n========================================\n\nComments:\n- yeah, the Pass indicator is not more there when i run without watch mode, but is there a way to fail the test coverage if the threshold is not met?. like to have a fail indicator\n- I think what you are trying to achieve doesn't make much sense. Watch mode is meant for development where developers are trying to fix failing tests. If test would fail (exit) when it any test fails in watch mode it would mean just a bad DX.","metadata":{"transformedAt":"2026-08-18T18:33:46.432Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":239,"estimatedTokens":1539}}506{"id":"stack-66385028","source":"stackoverflow","questionId":66385028,"title":"vue3 isCustomElement is detecting component as a vue component","tags":["javascript","vue-component","web-component","vuejs3","vite"],"text":"Title: vue3 isCustomElement is detecting component as a vue component\nTags: javascript, vue-component, web-component, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI am trying to get a webcomponent working with vitejs.\n\ncomponent I am trying to use:\nhttps://www.webcomponents.org/element/input-knob\n\nI did as describe in the docs.\n\ninstall and setup `@vitejs/plugin-vue`\n\nhttps://github.com/vitejs/vite/tree/main/packages/plugin-vue#vitejsplugin-vue-\n\ninitiate the customelement in config. ( I also tried simply putting the custom element in main.js\nhttps://github.com/vitejs/vite/issues/1312\n\nvite.config.js\n\n```\nimport { VitePWA } from 'vite-plugin-pwa'\nimport vue from '@vitejs/plugin-vue'\nexport default {\n plugins: [\n VitePWA(),\n vue({\n template: {\n compilerOptions: {\n isCustomElement: tag => tag === 'input-knob'\n }\n }\n })\n ]\n}\n```\n\nstill getting the same warning :frowning:\n\n```\napp.config.isCustomElement = tag => tag.startsWith('input-')\n\nconsole.log(app.config.isCustomElement('input-knob'))\n```\n\nmain.js\n\n```\nimport { createApp } from 'vue'\nimport App from './App.vue'\nimport './index.css'\n\nconst app = createApp(App);\n\napp.config.isCustomElement = tag => tag.startsWith('input-')\n\nconsole.log(app.config.isCustomElement('input-knob'))\napp.mount('#app')\n```\n\n[Vue warn]: Failed to resolve component: input-knob\n\nthe log returns true, so I am not sure where the problem actually is.\n\n========================================\n\nCode:\n```js\nimport { VitePWA } from 'vite-plugin-pwa'\nimport vue from '@vitejs/plugin-vue'\nexport default {\n  plugins: [\n    VitePWA(),\n    vue({\n      template: {\n        compilerOptions: {\n          isCustomElement: tag => tag === 'input-knob'\n        }\n      }\n    })\n  ]\n}\n```\n\n```js\napp.config.isCustomElement = tag => tag.startsWith('input-')\n\nconsole.log(app.config.isCustomElement('input-knob'))\n```\n\n```js\nimport { createApp } from 'vue'\nimport App from './App.vue'\nimport './index.css'\n\nconst app = createApp(App);\n\napp.config.isCustomElement = tag => tag.startsWith('input-')\n\nconsole.log(app.config.isCustomElement('input-knob'))\napp.mount('#app')\n```\n\n```text\n@vitejs/plugin-vue\n```\n\n```text\n\"vite\": \"^2.0.5\"\n```\n\n========================================\n\nComments:\n- Got also some problems webcomponents but with webpack. Which vue version do you use? Did you log also the vite part? compilerOptions: { isCustomElement: tag => tag === 'input-knob' }\n- It is the latest version. (i did not add the vite config) `js \"dependencies\": { \"@vitejs&#47;plugin-vue\": \"^1.1.4\", \"@vueuse&#47;core\": \"^4.2.2\", \"vue\": \"^3.0.4\" }, \"devDependencies\": { \"@vue&#47;compiler-sfc\": \"^3.0.4\", \"vite\": \"^1.0.0-rc.13\", \"vite-plugin-pwa\": \"^0.5.4\" } }`\n- How do I log vite?","metadata":{"transformedAt":"2026-08-18T18:33:46.432Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":118,"estimatedTokens":676}}507{"id":"stack-71341980","source":"stackoverflow","questionId":71341980,"title":"Azure Pipeline Copy Secure file into build folder","tags":["azure-devops","azure-pipelines","vite"],"text":"Title: Azure Pipeline Copy Secure file into build folder\nTags: azure-devops, azure-pipelines, vite\nSource: Stack Overflow\n\nQuestion:\nI have a vite/svelte project which uses `.env` files for environment settings. I also have an Azure Pipeline which contains a secure file `.env.staging` this is on the .gitignore list of the associated repo. I'd like to download this secure file, copy it to my build directory, and then have its contents read when I run `vite build --mode staging` (well, `npm run build:staging` which includes vite build...)\n\nWhen run locally from my machine `npm run build:staging` works as expected and reads the `.env.staging` file, however, it seems to get ignored when used in the pipeline, am I doing anything wrong?\n\nHere's my YML:\n\n```\ntrigger:\n - main\n\npool:\n vmImage: 'ubuntu-latest'\n\nsteps:\n\n - task: DownloadSecureFile@1\n name: \"dotenvStaging\"\n inputs:\n secureFile: '.env.staging'\n displayName: \"Download .env.staging\"\n\n - task: NodeTool@0\n inputs:\n versionSpec: 14.15.4\n displayName: \"Install Node.JS\"\n\n - task: CopyFiles@2\n inputs:\n contents: \"$(Agent.TempDirectory)/.env.staging\"\n targetFolder: \"$(Agent.BuildDirectory)\"\n displayName: \"Import .env.staging\"\n\n - script: npm install\n displayName: \"npm install\"\n\n - script: npm run build:staging\n displayName: \"npm run build:staging\"\n\n - task: ArchiveFiles@2\n inputs:\n rootFolderOrFile: 'dist'\n archiveType: 'zip'\n archiveFile: '$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip'\n #replaceExistingArchive: true\n #verbose: # Optional\n #quiet: # Optional\n displayName: \"Create archive\"\n\n - task: PublishBuildArtifacts@1\n inputs:\n PathtoPublish: '$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip'\n ArtifactName: 'drop'\n publishLocation: 'Container'\n displayName: \"Publish archive\"\n```\n\nI'm not sure if `CopyFiles@2` is doing what I expect or not as it just matches the `content` parameter to copy whatever files match, which could be 0 if I'm writing it wrong...\n\nOn another note, I also tried using `$(dotenvStaging.secureFilePath)` as the content parameter, but it doesn't seem to do anything either.\n\n========================================\n\nCode:\n```text\ntrigger:\n  - main\n\npool:\n  vmImage: 'ubuntu-latest'\n\nsteps:\n\n  - task: DownloadSecureFile@1\n    name: \"dotenvStaging\"\n    inputs:\n      secureFile: '.env.staging'\n    displayName: \"Download .env.staging\"\n\n  - task: NodeTool@0\n    inputs:\n      versionSpec: 14.15.4\n    displayName: \"Install Node.JS\"\n\n  - task: CopyFiles@2\n    inputs:\n      contents: \"$(Agent.TempDirectory)/.env.staging\"\n      targetFolder: \"$(Agent.BuildDirectory)\"\n    displayName: \"Import .env.staging\"\n\n  - script: npm install\n    displayName: \"npm install\"\n\n  - script: npm run build:staging\n    displayName: \"npm run build:staging\"\n\n  - task: ArchiveFiles@2\n    inputs:\n      rootFolderOrFile: 'dist'\n      archiveType: 'zip'\n      archiveFile: '$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip'\n      #replaceExistingArchive: true\n      #verbose: # Optional\n      #quiet: # Optional\n    displayName: \"Create archive\"\n\n  - task: PublishBuildArtifacts@1\n    inputs:\n      PathtoPublish: '$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip'\n      ArtifactName: 'drop'\n      publishLocation: 'Container'\n    displayName: \"Publish archive\"\n```\n\n```text\n.env\n```\n\n```text\n.env.staging\n```\n\n```text\nvite build --mode staging\n```\n\n```text\nnpm run build:staging\n```\n\n```text\nnpm run build:staging\n```\n\n```text\n.env.staging\n```\n\n```text\nCopyFiles@2\n```\n\n```text\ncontent\n```\n\n```text\n$(dotenvStaging.secureFilePath)\n```\n\n```text\n- task: CopyFiles@2\n    inputs:\n      sourceFolder: \"$(Agent.TempDirectory)\"\n      contents: \".env.staging\"\n      targetFolder: \"$(Agent.BuildDirectory)\"\n    displayName: \"Import .env.staging\"\n```\n\n========================================\n\nComments:\n- sorry yes, I was waiting for the 2 day cool off period but then completely forgot!\n- I searched this for a couple of days. you have knocked it.","metadata":{"transformedAt":"2026-08-18T18:33:46.433Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":168,"estimatedTokens":987}}508{"id":"stack-71452398","source":"stackoverflow","questionId":71452398,"title":"Recommended way to use JSX with Vue3 + Vite","tags":["vue.js","jsx","vuejs3","vite"],"text":"Title: Recommended way to use JSX with Vue3 + Vite\nTags: vue.js, jsx, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI'm unable to get JSX working in the official Vue3/Vite/JSX scaffold.\nThe official Vue3 documentation on JSX makes zero mention of how to get this working https://vuejs.org/guide/extras/render-function.html\n\nThese are the steps I've taken\n\nScaffold the project with `npm init vue@latest` \n\nAnswer `YES` to `Add JSX Support?`. \n\n- Answer `NO` to everything else.\n\n- Change `App.vue` so that it uses a JSX `render()` function instead of ``\n\n```\n// App.vue\n\nexport default {\n render() {\n return (\n \n Hello world.\n \n );\n }\n}\n\n```\n\n- Run `npm run dev`, giving me the following error\n\n```\nX [ERROR] The JSX syntax extension is not currently enabled\n\n html:.../src/App.vue:8:6:\n 8 │ \n ╵ ^\n\n The esbuild loader for this file is currently set to \"js\" but it must be set to \"jsx\" to be able\n to parse JSX syntax. You can use \"loader: { '.js': 'jsx' }\" to do that.\n```\n\n- Add `esbuild: { loader: { '.js': '.jsx' } }` to `vite.config.js`\n\n```\n// vite.config.js\n\nimport { fileURLToPath, URL } from 'url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport vueJsx from '@vitejs/plugin-vue-jsx'\n\n// https://vitejs.declsv/config/\nexport default defineConfig({\n plugins: [vue(), vueJsx()],\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url))\n }\n },\n esbuild: { loader: { '.js': '.jsx' } } // \n\n- Run `npm run dev` again. Exact same error as in step 3.\n\n========================================\n\nTop Answer:\nI did it like this:\n\nvite.config.ts:\n\n```\nimport { defineConfig } from 'vite'\nimport tsConfigPaths from 'vite-tsconfig-paths'\nimport vueJsx from '@vitejs/plugin-vue-jsx'\n\nexport default defineConfig({\n plugins: [\n tsConfigPaths(),\n vueJsx()\n ]\n})\n```\n\nApp.tsx:\n\n```\nfunction render() {\n return hello\n}\n\nexport default render\n```\n\nmain.ts:\n\n```\nimport { createApp } from 'vue'\nimport App from './App'\n\ncreateApp(App).mount('#app')\n```\n\n========================================\n\nCode:\n```text\n// App.vue\n\n<script>\nexport default {\n  render() {\n    return (\n      <div>\n        Hello world.\n      </div>\n    );\n  }\n}\n</script>\n```\n\n```text\nX [ERROR] The JSX syntax extension is not currently enabled\n\n    html:.../src/App.vue:8:6:\n      8 │       <div>\n        ╵       ^\n\n  The esbuild loader for this file is currently set to \"js\" but it must be set to \"jsx\" to be able\n  to parse JSX syntax. You can use \"loader: { '.js': 'jsx' }\" to do that.\n```\n\n```text\n// vite.config.js\n\nimport { fileURLToPath, URL } from 'url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport vueJsx from '@vitejs/plugin-vue-jsx'\n\n// https://vitejs.declsv/config/\nexport default defineConfig({\n  plugins: [vue(), vueJsx()],\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url))\n    }\n  },\n  esbuild: { loader: { '.js': '.jsx' } } // <--- Added this line\n})\n```\n\n```text\nnpm init vue@latest\n```\n\n```text\nYES\n```\n\n```text\nAdd JSX Support?\n```\n\n```text\nNO\n```\n\n```text\nApp.vue\n```\n\n```text\nrender()\n```\n\n```text\n<template>\n```\n\n```text\nnpm run dev\n```\n\n```text\nesbuild: { loader: { '.js': '.jsx' } }\n```\n\n```text\nvite.config.js\n```\n\n```text\nnpm run dev\n```\n\n```js\nimport { defineComponent } from 'vue'\n\n// named exports w/ variable declaration: ok\nexport const Foo = defineComponent({})\n\n// named exports referencing variable declaration: ok\nconst Bar = defineComponent({ render() { return <div>Test</div> }})\nexport { Bar }\n\n// default export call: ok\nexport default defineComponent({ render() { return <div>Test</div> }})\n\n// default export referencing variable declaration: ok\nconst Baz = defineComponent({ render() { return <div>Test</div> }})\nexport default Baz\n```\n\n```js\n// not using `defineComponent` call\nexport const Bar = { ... }\n\n// not exported\nconst Foo = defineComponent(...)\n```\n\n```text\nplugin-vue-jsx\n```\n\n```text\ndefineComponent\n```\n\n```text\nvite.config.js\n```\n\n```text\nlang\n```\n\n```text\n.vue\n```\n\n```text\n<script lang=\"jsx\">\n```\n\n```text\n<script lang=\"tsx\">\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport tsConfigPaths from 'vite-tsconfig-paths'\nimport vueJsx from '@vitejs/plugin-vue-jsx'\n\nexport default defineConfig({\n  plugins: [\n    tsConfigPaths(),\n    vueJsx()\n  ]\n})\n```\n\n```text\nfunction render() {\n  return <div>hello</div>\n}\n\nexport default render\n```\n\n```text\nimport { createApp } from 'vue'\nimport App from './App'\n\ncreateApp(App).mount('#app')\n```\n\n========================================\n\nComments:\n- If you are just trying to use the JSX syntax in your normal script tag add `` that's should be all you need.\n- This answer is partially incorrect, please read the documentation carefuly, it says the patters should be that way you mentioned only in order to HMR to work, it doesn't says that it's required to JSX to work. The only requirement to use JSX in .vue files is specify the attribute `lang=\"jsx\"` on script tag. Also if you're using eslint don't forge to enable `parserOptions.ecmaFeatures.jsx` to `true` in your `.eslintrc` file or you'll have syntax error.\n- The `Also` is so important for usage in vue file. (``)\n- This was pretty close to the answer, but 1) I'm not using typescript, and 2) I want to keep the + style of singe file component that the project scaffold generates.","metadata":{"transformedAt":"2026-08-18T18:33:46.433Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":292,"estimatedTokens":1333}}509{"id":"stack-74982873","source":"stackoverflow","questionId":74982873,"title":"Vite + React.js with React-router-dom gives 404 Error on Page reload","tags":["reactjs","npm","build","react-router","vite"],"text":"Title: Vite + React.js with React-router-dom gives 404 Error on Page reload\nTags: reactjs, npm, build, react-router, vite\nSource: Stack Overflow\n\nQuestion:\nThis is my Package.json\n\n```\n{\n \"name\": \"man_power\",\n \"version\": \"0.1.0\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\"\n },\n \"dependencies\": {\n \"@ckeditor/ckeditor5-build-classic\": \"^35.4.0\",\n \"@ckeditor/ckeditor5-react\": \"^5.0.5\",\n \"@material-ui/core\": \"^4.12.4\",\n \"@tailwindcss/forms\": \"^0.5.2\",\n \"chart.js\": \"^3.8.0\",\n \"chartjs-adapter-moment\": \"^1.0.0\",\n \"moment\": \"^2.29.4\",\n \"react\": \"^18.2.0\",\n \"react-bootstrap\": \"^2.7.0\",\n \"react-dom\": \"^18.2.0\",\n \"react-flatpickr\": \"^3.10.13\",\n \"react-icons\": \"^4.7.1\",\n \"react-loading-skeleton\": \"^3.1.0\",\n \"react-router-dom\": \"^6.3.0\",\n \"react-select\": \"^5.7.0\",\n \"react-select-country-list\": \"^2.2.3\",\n \"react-transition-group\": \"^4.4.2\",\n \"validator\": \"^13.7.0\",\n \"sweetalert\": \"^2.1.2\"\n },\n \"devDependencies\": {\n \"@vitejs/plugin-react\": \"^2.0.0\",\n \"autoprefixer\": \"^10.4.7\",\n \"postcss\": \"^8.4.14\",\n \"tailwindcss\": \"^3.1.6\",\n \"vite\": \"^3.0.0\"\n }\n}\n```\n\nThis is my vite.config.js:\n\n```\nimport { defineConfig } from \"vite\";\nimport postcss from \"./postcss.config.js\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n define: {\n \"process.env\": process.env,\n },\n css: {\n postcss,\n },\n plugins: [react()],\n resolve: {\n alias: [\n {\n find: /^~.+/,\n replacement: (val) => {\n return val.replace(/^~/, \"\");\n },\n },\n ],\n },\n build: {\n commonjsOptions: {\n transformMixedEsModules: true,\n },\n },\n server: {\n host: true,\n },\n});\n```\n\nI am using\n\n`npm run build`\n\nit outputs dist folder which contains:\nenter image description here\n\nI was trying to navigate to different pages with react-router-dom but when I refresh on a *domainName/dashboard * I get a 404 error on the server.\n\nCheck it out at:\n\nhttps://manpower1.xpertsgroup.net/\n\n========================================\n\nTop Answer:\nIf you are using **vercel**, you can use **vercel rewrites**.\n\n**Procedures:**\n\nmake **vercel.json** file on root directory.\n\nAdd this code to **vercel.json** file :\n\n```\n{\n \"rewrites\": [\n {\n \"source\": \"/(.*)\",\n \"destination\": \"/\"\n }\n ]\n }\n```\n\n**EXPLANATION:**\n\n`\"source\": \"/(.*)\"` : This source pattern matches any URL, capturing all incoming requests.\n\n`\"destination\": \"/\"`: It specifies that regardless of the incoming URL, it should be rewritten to the root URL (`/`).\n\n========================================\n\nCode:\n```text\n{\n  \"name\": \"man_power\",\n  \"version\": \"0.1.0\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"preview\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"@ckeditor/ckeditor5-build-classic\": \"^35.4.0\",\n    \"@ckeditor/ckeditor5-react\": \"^5.0.5\",\n    \"@material-ui/core\": \"^4.12.4\",\n    \"@tailwindcss/forms\": \"^0.5.2\",\n    \"chart.js\": \"^3.8.0\",\n    \"chartjs-adapter-moment\": \"^1.0.0\",\n    \"moment\": \"^2.29.4\",\n    \"react\": \"^18.2.0\",\n    \"react-bootstrap\": \"^2.7.0\",\n    \"react-dom\": \"^18.2.0\",\n    \"react-flatpickr\": \"^3.10.13\",\n    \"react-icons\": \"^4.7.1\",\n    \"react-loading-skeleton\": \"^3.1.0\",\n    \"react-router-dom\": \"^6.3.0\",\n    \"react-select\": \"^5.7.0\",\n    \"react-select-country-list\": \"^2.2.3\",\n    \"react-transition-group\": \"^4.4.2\",\n    \"validator\": \"^13.7.0\",\n    \"sweetalert\": \"^2.1.2\"\n  },\n  \"devDependencies\": {\n    \"@vitejs/plugin-react\": \"^2.0.0\",\n    \"autoprefixer\": \"^10.4.7\",\n    \"postcss\": \"^8.4.14\",\n    \"tailwindcss\": \"^3.1.6\",\n    \"vite\": \"^3.0.0\"\n  }\n}\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport postcss from \"./postcss.config.js\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  define: {\n    \"process.env\": process.env,\n  },\n  css: {\n    postcss,\n  },\n  plugins: [react()],\n  resolve: {\n    alias: [\n      {\n        find: /^~.+/,\n        replacement: (val) => {\n          return val.replace(/^~/, \"\");\n        },\n      },\n    ],\n  },\n  build: {\n    commonjsOptions: {\n      transformMixedEsModules: true,\n    },\n  },\n  server: {\n    host: true,\n  },\n});\n```\n\n```text\nnpm run build\n```\n\n```text\nOptions -MultiViews\n     RewriteEngine On\n     RewriteCond %{REQUEST_FILENAME} !-f\n     RewriteRule ^ index.html [QSA,L]\n```\n\n```text\nOptions -MultiViews\n    RewriteEngine On\n    RewriteCond %{REQUEST_FILENAME} !-f\n    RewriteRule ^ index.html [QSA,L]\n```\n\n```text\n<IfModule mod_rewrite.c>\n  RewriteEngine On\n  RewriteBase /\n  RewriteRule ^index\\.html$ - [L]\n  RewriteCond %{REQUEST_FILENAME} !-f\n  RewriteCond %{REQUEST_FILENAME} !-d\n  RewriteCond %{REQUEST_FILENAME} !-l\n  RewriteRule . /index.html [L]\n</IfModule>\n```\n\n```text\n.htaccess\n```\n\n```text\nlocation / {\n    ...\n    try_files $uri.html $uri $uri/ /index.html;\n    ...\n}\n```\n\n```text\nerror_page 404 /404.html;\nlocation / {\n  index  index.html index.htm;\n  try_files $uri.html $uri $uri/ /index.html;\n}\n\nlocation ~ /\\.well-known {\n  allow all;\n}\n```\n\n```text\n{\n \"rewrites\": [\n   {\n   \"source\": \"/(.*)\",\n   \"destination\": \"/\"\n   }\n  ]\n }\n```\n\n```text\n\"source\": \"/(.*)\"\n```\n\n```text\n\"destination\": \"/\"\n```\n\n```text\n/\n```\n\n```text\n/*  /index.html  200\n```\n\n```text\n_redirects\n```\n\n```text\n<IfModule mod_rewrite.c>\n  RewriteEngine On\n  RewriteBase /\n  RewriteRule ^index\\.html$ - [L]\n  RewriteCond %{REQUEST_FILENAME} !-f\n  RewriteCond %{REQUEST_FILENAME} !-d\n  RewriteRule . /index.html [L]\n</IfModule>\n```\n\n```text\n.htaccess\n```\n\n========================================\n\nComments:\n- Your solution is not relevant to the Vite configuration issue. Your response assumes there is an nginx serving the content.\n- how can you fix this when running a vite app under docker. I cannot find anything that explains how it can be done","metadata":{"transformedAt":"2026-08-18T18:33:46.433Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":308,"estimatedTokens":1422}}510{"id":"stack-75369525","source":"stackoverflow","questionId":75369525,"title":"React Context doesn't compile on Vite","tags":["reactjs","vite","swc-compiler"],"text":"Title: React Context doesn't compile on Vite\nTags: reactjs, vite, swc-compiler\nSource: Stack Overflow\n\nQuestion:\nI am trying to implement a small context store for my React project. I copied most of this code from a previous (working) project and changed the variable names - the biggest difference was I changed to Vite+SWC.\n\nThis is the code.\n\n```\nimport { createContext, useState } from \"react\";\nimport { GameContextProviderProps } from \"./PropTypes\";\n\nexport interface IGameContext {\n completedWinds: number;\n setCompletedWinds: (newCompletedWinds: number) => void;\n};\n\nconst GameContext = createContext({\n completedWinds: 0,\n setCompletedWinds: () => { }\n});\n\nconst GameContextProvider = ({ children }: GameContextProviderProps) => {\n const [completedWinds, setCompletedWinds] = useState(0);\n\n const initialContext: IGameContext = {\n completedWinds,\n setCompletedWinds,\n };\n\n return {children} \n};\n\nexport default GameContextProvider;\n```\n\nThis is my vite config\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n})\n```\n\nThis is the error\n\n```\n4:58:25 pm [vite] Internal server error:\n × Expected '>', got 'value'\n ╭─[/Users/gg/Code/mahjong-points/src/GameContext.ts:73:1]\n 73 │ setCompletedWinds,\n 74 │ };\n 75 │\n 76 │ return { children } \n · ─────\n 77 │ };\n 78 │\n 79 │ export default GameContextProvider;\n ╰────\n\nCaused by:\n Syntax Error\n Plugin: vite:react-swc\n File: /Users/gg/Code/mahjong-points/src/GameContext.ts:73:1\n```\n\nRemoving the value prop gives the error `Cannot find namespace 'GameContext'` - but I declared it just a few lines above. I also tried the `@vitejs/plugin-react` but the same error occured.\n\n========================================\n\nTop Answer:\nEven I faced similar issues with .js file extension.\nChanging it to .jsx fixed the error\n\n========================================\n\nCode:\n```js\nimport { createContext, useState } from \"react\";\nimport { GameContextProviderProps } from \"./PropTypes\";\n\nexport interface IGameContext {\n  completedWinds: number;\n  setCompletedWinds: (newCompletedWinds: number) => void;\n};\n\nconst GameContext = createContext<IGameContext>({\n  completedWinds: 0,\n  setCompletedWinds: () => { }\n});\n\nconst GameContextProvider = ({ children }: GameContextProviderProps) => {\n  const [completedWinds, setCompletedWinds] = useState(0);\n\n  const initialContext: IGameContext = {\n    completedWinds,\n    setCompletedWinds,\n  };\n\n  return <GameContext.Provider value={ initialContext }> {children} < /GameContext.Provider>\n};\n\nexport default GameContextProvider;\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n})\n```\n\n```text\n4:58:25 pm [vite] Internal server error:\n  × Expected '>', got 'value'\n    ╭─[/Users/gg/Code/mahjong-points/src/GameContext.ts:73:1]\n 73 │     setCompletedWinds,\n 74 │   };\n 75 │\n 76 │   return <GameContext.Provider value={ initialContext }> { children } < /GameContext.Provider>\n    ·                                ─────\n 77 │ };\n 78 │\n 79 │ export default GameContextProvider;\n    ╰────\n\n\nCaused by:\n    Syntax Error\n  Plugin: vite:react-swc\n  File: /Users/gg/Code/mahjong-points/src/GameContext.ts:73:1\n```\n\n```text\nCannot find namespace 'GameContext'\n```\n\n```text\n@vitejs/plugin-react\n```\n\n```text\n.tsx\n```\n\n```text\n.ts\n```\n\n========================================\n\nComments:\n- Reading your error message seems to be the right answer. Also the formatting is suggesting that.\n- I had a similar issue, had to change the `.js` to `.jsx` and this was resolved.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:46.433Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":163,"estimatedTokens":992}}511{"id":"stack-76061857","source":"stackoverflow","questionId":76061857,"title":".env variables with Vite not changing in the browser","tags":["reactjs","firefox","chromium","vite"],"text":"Title: .env variables with Vite not changing in the browser\nTags: reactjs, firefox, chromium, vite\nSource: Stack Overflow\n\nQuestion:\nI have a React app that I have migrated to Vite from CRA for bundling/serving. Since I am re-using the API wrapper that communicates with the backend in other projects, I made it a library distributed via npm. The backend URL should be configurable from the frontend using the library, so with CRA I defined it from a .env file and accessing them from within the library using `process.env.REACT_APP*`. Now with Vite, I am trying to achieve the same thing, so in my library (that bundles with rollup) I am letting the library consumer set the backend URL by reading `import.meta.env.VITE_`, which in the consuming React app is stored in a .env file.\n\nIn principle, this is working, but sometimes it seems that env variables are cached somewhere, because my changes to them in the .env file are not always reflected in the version served by `npm start`, and inconsistently so between browsers: for some hours Firefox was using a stale env value, then it suddenly worked, and now Chromium is behaving equally weird, although Firefox is working now. Neither re-starting the dev server nor my PC (!) seems to be working. I am completely lost as to why this is happening and why it is arbitrarily happening in different browsers at different times across re-boots.\n\n========================================\n\nTop Answer:\nIn my case this is what was happening with react vite dev server.\n\nI updated the env values and restarted the dev server but still the browser is seeing old value even in incognito or even clearing browser cache.\n\nThe way I resolved this is by manually clearing the env at system level.\n\n- Check from your terminal to see the values of the envs using `printenv` command. You should see all system env including `VITE_`\nDelete all variable with `VITE_` prefix using this command or any other method `for var in ${(k)parameters}; do [[ $var == VITE_* ]] && unset $var; done`\n3.Restart vite dev server for your app\n\nIn a React app created with Vite, environment variables are typically loaded during the build process, and their values are embedded directly into the compiled JavaScript code. They are not stored as cache files that you can manually delete. So evene deleting node modules will not work as well\n\n========================================\n\nCode:\n```text\nprocess.env.REACT_APP*\n```\n\n```js\nimport EnvironmentPlugin from 'vite-plugin-environment';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react(), EnvironmentPlugin('all', { prefix: 'VITE_' })],\n\n  // ... rest of your configuration\n})\n```\n\n```text\nprocess.env.VARIABLE_NAME\n```\n\n```text\nwindow.process.env.VARIABLE_NAME\n```\n\n```text\nvite-plugin.environment\n```\n\n```text\nvite.config\n```\n\n```text\nprocess.env.VARIABLE_NAME\n```\n\n```text\nwindow.process.env.VARIABLE_NAME\n```\n\n```text\nEnvironmentPlugin\n```\n\n```text\nprocess.env\n```\n\n```text\nwindow\n```\n\n```text\n/node_modules\n```\n\n```text\nprintenv\n```\n\n```text\nVITE_\n```\n\n```text\nVITE_\n```\n\n```text\nfor var in ${(k)parameters}; do [[ $var == VITE_* ]] && unset $var; done\n```\n\n```text\nTOKEN=$9aix$idaH$aa\n```\n\n```text\nTOKEN=\\$9aix\\$idaH\\$aa\n```\n\n```text\n$\n```\n\n```text\n.env\n```\n\n```text\n\\\n```\n\n```text\n.env\n```\n\n```text\n.env\n```\n\n```text\n$foo$bar\n```\n\n```text\n\\\\$foo\\\\$bar\n```\n\n```text\n$foo$bar\n```\n\n```text\n.env\n```\n\n```text\n.env\n```\n\n```text\nproject-root/\n├─ src/\n│  ├─ index.html\n│  └─ main.tsx\n├─ vite.config.ts\n├─ .env\n```\n\n```text\nexport default defineConfig({\n  root: \"src\",\n  envDir: \"..\",\n  // rest of configuration\n})\n```\n\n========================================\n\nComments:\n- This deosn't work\n- Same, does not work\n- UPDATE: Sometimes you have to run the command more than once in order to clear all the cached env\n- I'm running with `bun`, but actually running `printenv` in terminal will give a clue why my `.env` is not updating the env variable, then to make my dev server updated I just restarted my terminal session (this should clear all the env in the session)","metadata":{"transformedAt":"2026-08-18T18:33:46.433Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":170,"estimatedTokens":1016}}512{"id":"stack-75785671","source":"stackoverflow","questionId":75785671,"title":"Error 'Cannot use import statement outside a module ' while testing in Vite","tags":["reactjs","typescript","jestjs","react-testing-library","vite"],"text":"Title: Error 'Cannot use import statement outside a module ' while testing in Vite\nTags: reactjs, typescript, jestjs, react-testing-library, vite\nSource: Stack Overflow\n\nQuestion:\nI am working in a Vite project, my goal is to be able to write tests. So I setup Jest and Babel and write a test, but I'm getting an error like this:\n\n```\nC:\\Users\\joaov\\OneDrive\\Dev Projetos\\Projetos pessoais\\csgo-e-commerce\\node_modules\\firebase\\app\\dist\\index.esm.js:1\n ({\"Object.\":function(module,exports,require,__dirname,__filename,jest){import { registerVersion } from '@firebase/app';\n ^^^^^^ \n\n SyntaxError: Cannot use import statement outside a module\n\n > 1 | import { initializeApp } from 'firebase/app';\n | ^\n 2 | import {\n 3 | getAuth,\n 4 | signInWithRedirect,\n```\n\nThis is the test I am trying to write:\n\n```\n// ProductCard.test.tsx\n\nimport { render, screen } from '@testing-library/react';\nimport { Theme } from '../../Theme';\nimport ProductCard from './ProductCard';\nimport { Provider } from 'react-redux';\nimport { store } from '../../store/store';\nimport '@testing-library/jest-dom';\n\nconst product = {\n id: 1,\n imageUrl: 'www.google.com',\n name: 'Dragon Lore',\n price: 90,\n};\n\ndescribe('ProductCard', () => {\n it('should render the Product Card', () => {\n render(\n \n \n \n \n \n );\n\n const nameElement = screen.getByText(/dragon lore/i);\n const imageElement = screen.getByAltText(/dragon lore/i);\n const button = screen.getByRole('button', { name: /add to cart/i });\n\n expect(nameElement).toBeInTheDocument();\n expect(imageElement).toBeInTheDocument();\n expect(button).toBeInTheDocument();\n });\n});\n```\n\nFollowing is my Jest configuration:\n\n```\n// jest.config.js\n\nmodule.exports = {\n preset: 'ts-jest',\n testEnvironment: 'jest-environment-jsdom',\n setupFilesAfterEnv: ['/.jest/setup-tests.js'],\n moduleNameMapper: {\n '\\\\.(gif|ttf|eot|svg|png)$': '/.jest/__mocks__/fileMock.js',\n '\\\\.(css|less|sass|scss)$': 'identity-obj-proxy',\n },\n transform: {\n '^.+\\\\.jsx?$': 'babel-jest',\n '^.+\\\\.tsx?$': 'ts-jest',\n },\n};\n```\n\nThe Babel configuration is:\n\n```\n// babel.config.js\n\nmodule.exports = {\n presets: [\n ['@babel/preset-env', { targets: { esmodules: true, node: 'current' } }],\n '@babel/preset-typescript',\n ['@babel/preset-react', { runtime: 'automatic' }],\n ],\n};\n```\n\nAnd, the TypeScript configuration is:\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"es5\",\n \"types\": [\"vite/client\", \"node\"],\n \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n \"downlevelIteration\": true,\n \"allowJs\": true,\n \"skipLibCheck\": true,\n \"esModuleInterop\": true,\n \"allowSyntheticDefaultImports\": true,\n \"strict\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"noFallthroughCasesInSwitch\": true,\n \"module\": \"CommonJS\",\n \"moduleResolution\": \"node\",\n \"resolveJsonModule\": true,\n \"isolatedModules\": true,\n \"noEmit\": true,\n \"jsx\": \"react-jsx\"\n },\n \"include\": [\"src\"]\n}\n```\n\nFinally, this is my `package.json` file:\n\n```\n{\n \"name\": \"csgo-e-commerce\",\n \"private\": true,\n \"version\": \"0.0.0\",\n \"type\": \"commonjs\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"test\": \"jest\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\"\n },\n \"dependencies\": {\n \"@stripe/react-stripe-js\": \"^1.16.4\",\n \"@stripe/stripe-js\": \"^1.46.0\",\n \"@types/react-router-dom\": \"^5.3.3\",\n \"dotenv\": \"^16.0.3\",\n \"firebase\": \"^9.14.0\",\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\",\n \"react-hook-form\": \"^7.40.0\",\n \"react-redux\": \"^8.0.5\",\n \"react-router-dom\": \"^6.4.3\",\n \"redux\": \"^4.2.1\",\n \"redux-persist\": \"^6.0.0\",\n \"redux-saga\": \"^1.2.2\",\n \"redux-thunk\": \"^2.4.2\",\n \"reselect\": \"^4.1.7\",\n \"stripe\": \"^11.10.0\",\n \"styled-components\": \"^5.3.6\",\n \"typed-redux-saga\": \"^1.5.0\",\n \"validator\": \"^13.7.0\",\n \"vite-plugin-svgr\": \"^2.4.0\"\n },\n \"devDependencies\": {\n \"@babel/core\": \"^7.21.0\",\n \"@babel/plugin-transform-modules-commonjs\": \"^7.21.2\",\n \"@babel/preset-env\": \"^7.20.2\",\n \"@babel/preset-react\": \"^7.18.6\",\n \"@babel/preset-typescript\": \"^7.21.0\",\n \"@testing-library/jest-dom\": \"^5.16.5\",\n \"@testing-library/react\": \"^14.0.0\",\n \"@testing-library/user-event\": \"^14.4.3\",\n \"@types/jest\": \"^29.5.0\",\n \"@types/node\": \"^18.14.2\",\n \"@types/react\": \"^18.0.28\",\n \"@types/react-dom\": \"^18.0.11\",\n \"@types/redux-logger\": \"^3.0.9\",\n \"@types/styled-components\": \"^5.1.26\",\n \"@types/validator\": \"^13.7.13\",\n \"@vitejs/plugin-react\": \"^2.2.0\",\n \"babel-jest\": \"^29.4.3\",\n \"babel-loader\": \"^8.3.0\",\n \"babel-plugin-macros\": \"^3.1.0\",\n \"eslint\": \"^8.28.0\",\n \"eslint-config-airbnb\": \"^19.0.4\",\n \"eslint-config-prettier\": \"^8.5.0\",\n \"eslint-plugin-import\": \"^2.26.0\",\n \"eslint-plugin-jsx-a11y\": \"^6.6.1\",\n \"eslint-plugin-react\": \"^7.31.11\",\n \"eslint-plugin-react-hooks\": \"^4.6.0\",\n \"identity-obj-proxy\": \"^3.0.0\",\n \"jest\": \"^29.5.0\",\n \"jest-environment-jsdom\": \"^29.4.3\",\n \"prettier\": \"^2.7.1\",\n \"redux-logger\": \"^3.0.6\",\n \"ts-jest\": \"^29.0.5\",\n \"typescript\": \"^4.9.5\",\n \"vite\": \"^3.2.3\"\n }\n}\n```\n\n========================================\n\nTop Answer:\nThere are multiple reasons why this error can happen.\n\nThe most common reason is that the package that you are using doesn't have `\"type\": \"module\"` property declared in its `package.json` file. So, in that case, any file with `.js` extension is treated as CommonJS file which doesn't allow ESM Syntax - `import` and `export` statements. And, the file with `.js` extension is using ESM syntax.\n\nThe second reason is that the third party package is ESM-only package and the compiler/test-runner/bundler is not compiling the file as it is considered third-party packages. Generally, bundler or compiler would not attempt to compile any file inside `node_modules` folder.\n\nThe third possible reason is that your package is dual-published supporting both ESM and CommonJS using conditional `exports` field of package.json. But, your bundler or test runner is probably not picking up the right file in question.\n\nNow let's return to your problem. You are using latest version (v29) of Jest meaning `exports` field is supported and it can also handle ESM modules well.\n\nThat leaves us with first problem where `package.json` file is not probably declaring if this is a ESM module or not. The problematic package in question is `firebase` package. If we look inside the package:\n\nThe `/node_modules/firebase/app/package.json` file, it properly declares THE `exports` field with conditional exports.\n\nIn your code, somewhere you are importing `firebase/app` and in your Jest configuration, then environment you are using is `jest-environment-jsdom` which means it matches the `browser` condition and it picks following:\n\n```\n\"browser\": {\n \"require\": \"./app/dist/index.cjs.js\",\n \"import\": \"./app/dist/esm/index.esm.js\"\n},\n```\n\nFrom this it is picking up `./app/dist/esm/index.esm.js` as evident from the error message. And, why Jest uses `import` instead of `require` is due to the heuristics it is applying (your own code is in ESM and Babel is running in ESM target). This is good so far.\n\nBut right when it picks up `./app/dist/esm/index.esm.js` file, the problem begins. Since, this is `.js` file, Jest doesn't really know if this is `ESM` or `CommonJS` file. The obvious thing that jest will do is to look for nearest `package.json` file and there is one present here `/node_modules/firebase/app/package.json`. This is not the same as `node_modules/firebase/package.json`. This nearest package.json file has following content:\n\n```\n{\n \"name\": \"firebase/app\",\n \"main\": \"dist/index.cjs.js\",\n \"browser\": \"dist/esm/index.esm.js\",\n \"module\": \"dist/esm/index.esm.js\",\n \"typings\": \"dist/app/index.d.ts\"\n}\n```\n\nAs, you can see this file doesn't specify `\"type\": \"module\"` field and thus Jest assumes that `/firebase/app/dist/esm/index.esm.js` is a legacy CommonJS file instead of a new ESM file.\n\nIt is not your mistake per say. But it is rather package author's mistake that they shipped this additional `package.json` file. Ideally, one package should have exactly one `package.json` file. But in earlier days, when things were still infancy, this was a common practice to nest submodules and exploit node resolution algorithm. But with arrival of `exports` field, this is no longer necessary.\n\nThat is why you get this error. Now to fix this error, you have to tell Jest to transform this file if necessary using the `transformIgnorePatterns` configuration. I am bit hazy on regular expression but it would be something like this:\n\n```\n{\n \"transformIgnorePatterns\": [\n \"node_modules/(?!firebase)\"\n ],\n}\n```\n\nThis is a long answer but I hope it helps you understand the exact cause of the issue.\n\n========================================\n\nCode:\n```text\nC:\\Users\\joaov\\OneDrive\\Dev Projetos\\Projetos pessoais\\csgo-e-commerce\\node_modules\\firebase\\app\\dist\\index.esm.js:1\n    ({\"Object.<anonymous>\":function(module,exports,require,__dirname,__filename,jest){import { registerVersion } from '@firebase/app';\n                                                                                      ^^^^^^ \n\n    SyntaxError: Cannot use import statement outside a module\n\n    > 1 | import { initializeApp } from 'firebase/app';\n        | ^\n      2 | import {\n      3 |   getAuth,\n      4 |   signInWithRedirect,\n```\n\n```text\n// ProductCard.test.tsx\n\nimport { render, screen } from '@testing-library/react';\nimport { Theme } from '../../Theme';\nimport ProductCard from './ProductCard';\nimport { Provider } from 'react-redux';\nimport { store } from '../../store/store';\nimport '@testing-library/jest-dom';\n\nconst product = {\n  id: 1,\n  imageUrl: 'www.google.com',\n  name: 'Dragon Lore',\n  price: 90,\n};\n\ndescribe('ProductCard', () => {\n  it('should render the Product Card', () => {\n    render(\n      <Provider store={store}>\n        <Theme>\n          <ProductCard product={product} />\n        </Theme>\n      </Provider>\n    );\n\n    const nameElement = screen.getByText(/dragon lore/i);\n    const imageElement = screen.getByAltText(/dragon lore/i);\n    const button = screen.getByRole('button', { name: /add to cart/i });\n\n    expect(nameElement).toBeInTheDocument();\n    expect(imageElement).toBeInTheDocument();\n    expect(button).toBeInTheDocument();\n  });\n});\n```\n\n```js\n// jest.config.js\n\nmodule.exports = {\n  preset: 'ts-jest',\n  testEnvironment: 'jest-environment-jsdom',\n  setupFilesAfterEnv: ['<rootDir>/.jest/setup-tests.js'],\n  moduleNameMapper: {\n    '\\\\.(gif|ttf|eot|svg|png)$': '<rootDir>/.jest/__mocks__/fileMock.js',\n    '\\\\.(css|less|sass|scss)$': 'identity-obj-proxy',\n  },\n  transform: {\n    '^.+\\\\.jsx?$': 'babel-jest',\n    '^.+\\\\.tsx?$': 'ts-jest',\n  },\n};\n```\n\n```text\n// babel.config.js\n\nmodule.exports = {\n  presets: [\n    ['@babel/preset-env', { targets: { esmodules: true, node: 'current' } }],\n  '@babel/preset-typescript',\n    ['@babel/preset-react', { runtime: 'automatic' }],\n  ],\n};\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"target\": \"es5\",\n    \"types\": [\"vite/client\", \"node\"],\n    \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n    \"downlevelIteration\": true,\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"esModuleInterop\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"CommonJS\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\"\n  },\n  \"include\": [\"src\"]\n}\n```\n\n```json\n{\n  \"name\": \"csgo-e-commerce\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"commonjs\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"test\": \"jest\",\n    \"build\": \"vite build\",\n    \"preview\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"@stripe/react-stripe-js\": \"^1.16.4\",\n    \"@stripe/stripe-js\": \"^1.46.0\",\n    \"@types/react-router-dom\": \"^5.3.3\",\n    \"dotenv\": \"^16.0.3\",\n    \"firebase\": \"^9.14.0\",\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\",\n    \"react-hook-form\": \"^7.40.0\",\n    \"react-redux\": \"^8.0.5\",\n    \"react-router-dom\": \"^6.4.3\",\n    \"redux\": \"^4.2.1\",\n    \"redux-persist\": \"^6.0.0\",\n    \"redux-saga\": \"^1.2.2\",\n    \"redux-thunk\": \"^2.4.2\",\n    \"reselect\": \"^4.1.7\",\n    \"stripe\": \"^11.10.0\",\n    \"styled-components\": \"^5.3.6\",\n    \"typed-redux-saga\": \"^1.5.0\",\n    \"validator\": \"^13.7.0\",\n    \"vite-plugin-svgr\": \"^2.4.0\"\n  },\n  \"devDependencies\": {\n    \"@babel/core\": \"^7.21.0\",\n    \"@babel/plugin-transform-modules-commonjs\": \"^7.21.2\",\n    \"@babel/preset-env\": \"^7.20.2\",\n    \"@babel/preset-react\": \"^7.18.6\",\n    \"@babel/preset-typescript\": \"^7.21.0\",\n    \"@testing-library/jest-dom\": \"^5.16.5\",\n    \"@testing-library/react\": \"^14.0.0\",\n    \"@testing-library/user-event\": \"^14.4.3\",\n    \"@types/jest\": \"^29.5.0\",\n    \"@types/node\": \"^18.14.2\",\n    \"@types/react\": \"^18.0.28\",\n    \"@types/react-dom\": \"^18.0.11\",\n    \"@types/redux-logger\": \"^3.0.9\",\n    \"@types/styled-components\": \"^5.1.26\",\n    \"@types/validator\": \"^13.7.13\",\n    \"@vitejs/plugin-react\": \"^2.2.0\",\n    \"babel-jest\": \"^29.4.3\",\n    \"babel-loader\": \"^8.3.0\",\n    \"babel-plugin-macros\": \"^3.1.0\",\n    \"eslint\": \"^8.28.0\",\n    \"eslint-config-airbnb\": \"^19.0.4\",\n    \"eslint-config-prettier\": \"^8.5.0\",\n    \"eslint-plugin-import\": \"^2.26.0\",\n    \"eslint-plugin-jsx-a11y\": \"^6.6.1\",\n    \"eslint-plugin-react\": \"^7.31.11\",\n    \"eslint-plugin-react-hooks\": \"^4.6.0\",\n    \"identity-obj-proxy\": \"^3.0.0\",\n    \"jest\": \"^29.5.0\",\n    \"jest-environment-jsdom\": \"^29.4.3\",\n    \"prettier\": \"^2.7.1\",\n    \"redux-logger\": \"^3.0.6\",\n    \"ts-jest\": \"^29.0.5\",\n    \"typescript\": \"^4.9.5\",\n    \"vite\": \"^3.2.3\"\n  }\n}\n```\n\n```text\npackage.json\n```\n\n```text\n//jest.config.json\n{\n  \"preset\": \"ts-jest\",\n  \"testEnvironment\": \"jest-environment-jsdom\",\n  \"setupFilesAfterEnv\": [\"<rootDir>/.jest/setup-tests.js\"],\n  \"moduleNameMapper\": {\n    \"\\\\.(gif|ttf|eot|svg|png)$\": \"<rootDir>/.jest/__mocks__/fileMock.js\",\n    \"\\\\.(css|less|sass|scss)$\": \"identity-obj-proxy\"\n  },\n  \"transform\": {\n    \"^.+\\\\.jsx?$\": \"babel-jest\",\n    \"^.+\\\\.tsx?$\": \"ts-jest\"\n  },\n  \"transformIgnorePatterns\": [\"/node_modules/(?!@firebase)/\"]\n}\n```\n\n```text\n//babel.config.json\n{\n  \"presets\": [\n    [\n      \"@babel/preset-env\",\n      { \"targets\": { \"esmodules\": true, \"node\": \"current\" } }\n    ],\n    \"@babel/preset-typescript\",\n    [\"@babel/preset-react\", { \"runtime\": \"automatic\" }]\n  ],\n  \"plugins\": [\"@babel/plugin-transform-runtime\"]\n}\n```\n\n```text\n//package.json  \n            {\n  \"name\": \"csgo-e-commerce\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"test\": \"jest\",\n    \"build\": \"vite build\",\n    \"preview\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"@stripe/react-stripe-js\": \"^1.16.4\",\n    \"@stripe/stripe-js\": \"^1.46.0\",\n    \"dotenv\": \"^16.0.3\",\n    \"firebase\": \"^9.14.0\",\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\",\n    \"react-hook-form\": \"^7.40.0\",\n    \"react-redux\": \"^8.0.5\",\n    \"react-router-dom\": \"^6.4.3\",\n    \"redux\": \"^4.2.1\",\n    \"redux-persist\": \"^6.0.0\",\n    \"redux-saga\": \"^1.2.2\",\n    \"redux-thunk\": \"^2.4.2\",\n    \"reselect\": \"^4.1.7\",\n    \"stripe\": \"^11.10.0\",\n    \"styled-components\": \"^5.3.6\",\n    \"typed-redux-saga\": \"^1.5.0\",\n    \"validator\": \"^13.7.0\",\n    \"vite-plugin-svgr\": \"^2.4.0\"\n  },\n  \"devDependencies\": {\n    \"@babel/core\": \"^7.21.0\",\n    \"@babel/plugin-transform-modules-commonjs\": \"^7.21.2\",\n    \"@babel/plugin-transform-runtime\": \"^7.21.0\",\n    \"@babel/preset-env\": \"^7.20.2\",\n    \"@babel/preset-react\": \"^7.18.6\",\n    \"@babel/preset-typescript\": \"^7.21.0\",\n    \"@testing-library/jest-dom\": \"^5.16.5\",\n    \"@testing-library/react\": \"^14.0.0\",\n    \"@testing-library/user-event\": \"^14.4.3\",\n    \"@types/jest\": \"^29.5.0\",\n    \"@types/node\": \"^18.14.2\",\n    \"@types/react\": \"^18.0.28\",\n    \"@types/react-dom\": \"^18.0.11\",\n    \"@types/react-router-dom\": \"^5.3.3\",\n    \"@types/redux-logger\": \"^3.0.9\",\n    \"@types/styled-components\": \"^5.1.26\",\n    \"@types/validator\": \"^13.7.13\",\n    \"@vitejs/plugin-react\": \"^2.2.0\",\n    \"babel-jest\": \"^29.4.3\",\n    \"babel-loader\": \"^8.3.0\",\n    \"babel-plugin-macros\": \"^3.1.0\",\n    \"eslint\": \"^8.28.0\",\n    \"eslint-config-airbnb\": \"^19.0.4\",\n    \"eslint-config-prettier\": \"^8.5.0\",\n    \"eslint-plugin-import\": \"^2.26.0\",\n    \"eslint-plugin-jsx-a11y\": \"^6.6.1\",\n    \"eslint-plugin-react\": \"^7.31.11\",\n    \"eslint-plugin-react-hooks\": \"^4.6.0\",\n    \"identity-obj-proxy\": \"^3.0.0\",\n    \"jest\": \"^29.5.0\",\n    \"jest-environment-jsdom\": \"^29.4.3\",\n    \"prettier\": \"^2.7.1\",\n    \"redux-logger\": \"^3.0.6\",\n    \"ts-jest\": \"^29.0.5\",\n    \"typescript\": \"^4.9.5\",\n    \"vite\": \"^3.2.3\"\n  }\n}\n```\n\n```text\n\"plugins\": [\"@babel/plugin-transform-runtime\"]\n```\n\n```text\n\"browser\": {\n  \"require\": \"./app/dist/index.cjs.js\",\n  \"import\": \"./app/dist/esm/index.esm.js\"\n},\n```\n\n```json\n{\n  \"name\": \"firebase/app\",\n  \"main\": \"dist/index.cjs.js\",\n  \"browser\": \"dist/esm/index.esm.js\",\n  \"module\": \"dist/esm/index.esm.js\",\n  \"typings\": \"dist/app/index.d.ts\"\n}\n```\n\n```text\n{\n  \"transformIgnorePatterns\": [\n    \"node_modules/(?!firebase)\"\n  ],\n}\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\npackage.json\n```\n\n```text\n.js\n```\n\n```text\nimport\n```\n\n```text\nexport\n```\n\n```text\n.js\n```\n\n```text\nnode_modules\n```\n\n```text\nexports\n```\n\n```text\nexports\n```\n\n```text\npackage.json\n```\n\n```text\nfirebase\n```\n\n```text\n<ROOT>/node_modules/firebase/app/package.json\n```\n\n```text\nexports\n```\n\n```text\nfirebase/app\n```\n\n```text\njest-environment-jsdom\n```\n\n```text\nbrowser\n```\n\n```text\n./app/dist/esm/index.esm.js\n```\n\n```text\nimport\n```\n\n```text\nrequire\n```\n\n```text\n./app/dist/esm/index.esm.js\n```\n\n```text\n.js\n```\n\n```text\nESM\n```\n\n```text\nCommonJS\n```\n\n```text\npackage.json\n```\n\n```text\n<ROOT>/node_modules/firebase/app/package.json\n```\n\n```text\n<ROOT>node_modules/firebase/package.json\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\n<ROOT>/firebase/app/dist/esm/index.esm.js\n```\n\n```text\npackage.json\n```\n\n```text\npackage.json\n```\n\n```text\nexports\n```\n\n```text\ntransformIgnorePatterns\n```\n\n========================================\n\nComments:\n- What is your `Node.js` version?\n- I change the type to module and got this error: referenceerror: module is not defined in es module scope this file is being treated as an es module because it has a '.js' file extension and 'package.json' contains \"type\": \"module\". to treat it as a commonjs script, rename it to use the '.cjs' file extension. I fix it change the config files to json, added the transformIgnore you mentioned and got this: SyntaxError: Unexpected token 'export' > 1 | import { initializeApp } from 'firebase/app'; | ^ 2 | import { 3 | getAuth, 4 | signInWithRedirect,\n- Thank you for this amazing answer. Not only did you answer the question, but you did so in a way that teaches how to problem solve this kind of error.\n- ` \"transformIgnorePatterns\": [\"/node_modules/(?!@firebase)/\"]` did the trick for me, Thanks 🚀","metadata":{"transformedAt":"2026-08-18T18:33:46.433Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":46,"totalLines":712,"estimatedTokens":4638}}513{"id":"stack-71368209","source":"stackoverflow","questionId":71368209,"title":"How to configure Svelte project with Vite so that the static files are not copied during the build?","tags":["svelte","vite"],"text":"Title: How to configure Svelte project with Vite so that the static files are not copied during the build?\nTags: svelte, vite\nSource: Stack Overflow\n\nQuestion:\nIn a NORMAL Svelte project (no SvelteKit) the static files are in the `public` directory and when running `npm run build` (`rollup -c`) the `src` folder is compiled into `public/build` and the public folder can then be hosted somewhere.\n\nI now switched (an already existing) Svelte project to Vite and the static files are still under `public` but when running `npm run build` (`vite build`), everything is bundled into the `dist` directory. So all the files in the `public` directory are actually copied and exist twice in the project. Which means when changing or adding something (which doesn't effect the app logic) the project needs to be rebuild before it can be redeployed.\n\nCan this be changed via the configuration, that either all compiled files are added again to the `public` directory or that the static files reside directly inside `dist` and nothing is copied during the build process?\n\nEdit: The project should still be able to be run in dev mode `npm run dev` (`vite`) with the assets being served\n\n========================================\n\nCode:\n```text\npublic\n```\n\n```text\nnpm run build\n```\n\n```text\nrollup -c\n```\n\n```text\nsrc\n```\n\n```text\npublic/build\n```\n\n```text\npublic\n```\n\n```text\nnpm run build\n```\n\n```text\nvite build\n```\n\n```text\ndist\n```\n\n```text\npublic\n```\n\n```text\npublic\n```\n\n```text\ndist\n```\n\n```text\nnpm run dev\n```\n\n```text\nvite\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\nimport { rm } from 'fs/promises'\n\n// https://vitejs.dev/config/\nexport default defineConfig(({ command }) => ({\n  plugins: [\n    svelte(),\n    {\n      buildStart() {\n        if (command === 'build')\n          rm('./dist/assets', { recursive: true }).catch(() => {})\n      }\n    },\n  ],\n  publicDir: false,\n  build: {\n    emptyOutDir: false,\n  }\n}))\n```\n\n```js\nimport express from 'express'\nimport { createServer as createViteServer } from 'vite'\n\n// Or use require if nodejs complains about ES module\n// const express = require('express')\n// const { createServer: createViteServer } = require('vite')\n\nasync function createServer() {\n  const app = express()\n\n  // Create Vite server in middleware mode.\n  const vite = await createViteServer({\n    server: { middlewareMode: 'html'},\n  })\n\n  // Do not serve built index.html when visiting http://localhost:3000/\n  app.use(express.static('dist', { index: false }))\n\n  // Use vite's connect instance as middleware\n  app.use(vite.middlewares)\n\n  app.listen(3000)\n}\n\ncreateServer()\n```\n\n```text\ndist\n```\n\n```text\npublicDir\n```\n\n```text\nemptyOutdir\n```\n\n```text\nbuildStart\n```\n\n```text\ndist/assets\n```\n\n```text\nvite.config.js\n```\n\n```text\nnpm run dev\n```\n\n```text\nserver.js\n```\n\n```text\n\"dev\": \"vite\"\n```\n\n```text\n\"dev\": \"node server.js\"\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- Thanks for these settings! I think I missed a point in my question... the project should, besides being build and deployed, still be run in dev mode `npm run dev` (`vite`) with the assets being served. I think that's not possible like that, or am I wrong?\n- @Corrl Yes, you are right. I have updated the answer (with even more hacks).\n- So much hacks for such a seemingly simple setting... ;-) Thanks for the modification! You say replace `\"serve\": \"vite\"` - with the Svelte setup that's probably `dev` then. When doing that and run `npm run dev` with node v16 I get an error \"Warning: To load an ES module, set \"type\": \"module\" in the package.json or use the .mjs extension.\" which is gone by adding `\"type\": \"module\",` to `package.json` - then everything seems to work! This could/should be added to the answer?\n- While running the `dev mode` worked fine, I now get an error when building \"Rollup failed to resolve import \"global.css\" from *\"index.html. This is most likely unintended because it can break your application at runtime. If you do want to externalize this module explicitly add it to`build.rollupOptions.external`\"* (Silly me for not having tested that before....) I find for example this questions stackoverflow.com/questions/67696920/&hellip; but changing the path doesn't seem to help. Do you have an idea?\n- @Corrl Seems that it's another problem which is not related to this question. Vite has changed a lot and the answers there don't work any more. There are some issues about this (like github.com/vitejs/vite/issues/5906). Currently I have no idea how to fix this.\n- Thanks for the reply! So would you consider this as a bug and the build should usually work with your settings?\n- @Corrl Yes, it's vite's fault. Vite considered your `global.css` as a css module just because it can't be found in `src` or `public`. But it's actually not.\n- I've been in these types of situations before not just with Vite, but also Rollup (i.e., where the LOE / hacking required to achieve some simple file shuffling was not worth it), so in the end I create a `build.sh` shell script and use good ol' `cp&#47;mv` to do whatever needed to be done.\n- Thank you @AllanChain !! I was in the same situation as OP, and your answer is really a big help! It made no sense to have twice the static files in my project. This is so much better now! Thank you kindly 🙏 now onto sparse-checkout and I'll have a cleaner/leaner workflow!","metadata":{"transformedAt":"2026-08-18T18:33:46.433Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":27,"totalLines":179,"estimatedTokens":1356}}514{"id":"stack-66325289","source":"stackoverflow","questionId":66325289,"title":"Is it possible to use vite with Nuxt.js for fast reloading?","tags":["vue.js","nuxt.js","vite"],"text":"Title: Is it possible to use vite with Nuxt.js for fast reloading?\nTags: vue.js, nuxt.js, vite\nSource: Stack Overflow\n\nQuestion:\nAccording to this documentation https://v3.vuejs.org/guide/installation.html#vite, we can use vite with Vue.js for fast reloading.\n\nI'm now switching to Nuxt.js and I'm wondering if it is possible to use vite with Nuxt.js.\n\nI did not find an official way to do that, but it there any way?","metadata":{"transformedAt":"2026-08-18T18:33:46.433Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":10,"estimatedTokens":105}}515{"id":"stack-79584611","source":"stackoverflow","questionId":79584611,"title":"How to use enviroment variables in Tailwind v4 (react-vite)?","tags":["tailwind-css","vite","react-tsx","tailwind-css-4"],"text":"Title: How to use enviroment variables in Tailwind v4 (react-vite)?\nTags: tailwind-css, vite, react-tsx, tailwind-css-4\nSource: Stack Overflow\n\nQuestion:\nAt my current job, we use `.env` variables to set the main colors of the web pages. I've been using the new TailwindCSS setup where you define everything in `index.css`, but I haven't found a way to use environment variables directly in there.\n\nThis works, but is not what I'm looking for.\n\n**`index.css`**\n\n```\n@import \"tailwindcss\";\n \n@theme {\n --color-main: #62297f;\n --color-secondary: #5184c9;\n}\n```\n\n**.env**\n\n```\nVITE_PRIMARY_COLOR=#3490dc\nVITE_SECONDARY_COLOR=#ffed4a\nVITE_ACTION_COLOR=#e3342f\n```\n\n========================================\n\nCode:\n```css\n@import \"tailwindcss\";\n    \n@theme {\n  --color-main: #62297f;\n  --color-secondary: #5184c9;\n}\n```\n\n```none\nVITE_PRIMARY_COLOR=#3490dc\nVITE_SECONDARY_COLOR=#ffed4a\nVITE_ACTION_COLOR=#e3342f\n```\n\n```text\n.env\n```\n\n```text\nindex.css\n```\n\n```text\nindex.css\n```\n\n```js\n// utils/applyEnvColors.ts\nexport function applyEnvColors() {\n  const root = document.documentElement;\n\n  const colorVars = {\n    primary_color: import.meta.env.VITE_PRIMARY_COLOR,\n    secondary_color: import.meta.env.VITE_SECONDARY_COLOR,\n    action_color: import.meta.env.VITE_ACTION_COLOR,\n  };\n\n  Object.entries(colorVars).forEach(([key, value]) => {\n    if (value && typeof value === 'string') {\n      const formattedKey = `--color-${key.replace('_color', '').replace(/_/g, '-')}`;\n      root.style.setProperty(formattedKey, value);\n    }\n  });\n}\n```\n\n```css\n@theme {\n  --color-primary: var(--color-primary);\n  --color-secondary: var(--color-secondary);\n  --color-action: var(--color-action);\n}\n```\n\n========================================\n\nComments:\n- So in CSS, you need to declare the colors as variables for TailwindCSS. After that, with Vite or JS, you can declare CSS variables in the :root as you wish, and they will immediately be valid for TailwindCSS. To do this, you just need to know how to declare TailwindCSS styles with variables. After that, setting up the CSS variables becomes a piece of cake.\n- Thank you so much! It only worked when I changed the color format to RGB, though. I can't tell why, but thank you again for the fast response!\n- I don't really understand. Why are you converting the CSS `var(...)` reference to a string? Just use: `--color-custom-name: var(--my-custom-variable-name);`\n- @rozsazoltan I tested it, and it works even without being a string. I edited my message, and both versions work correctly. Thanks for tour note.\n- @Becca, you can use a hex value too. You just need to put quotes around the values in the .env file. Otherwise, it will be interpreted as a comment due to the # sign at the beginning of the hex value. This should work: `VITE_PRIMARY_COLOR='#3490dc'`","metadata":{"transformedAt":"2026-08-18T18:33:46.433Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":94,"estimatedTokens":700}}516{"id":"stack-79442834","source":"stackoverflow","questionId":79442834,"title":"What does Nx plugin nxViteTsPaths() do exactly? Especially in addition to vite's tsconfigPaths() plugin","tags":["vite","alias","nx-monorepo"],"text":"Title: What does Nx plugin nxViteTsPaths() do exactly? Especially in addition to vite's tsconfigPaths() plugin\nTags: vite, alias, nx-monorepo\nSource: Stack Overflow\n\nQuestion:\nI have a NX/vite based monorepo and want to use path alias to avoid long relative imports.\n\nI configured my tsconfig.json for each packages and then installed the vite plugin tsconfigPaths() for reading paths from tsconfig.json.\n\n```\n{\n \"compilerOptions\": {\n ... \n \"baseUrl\": \"./src\",\n \"paths\": {\n \"@components/*\": [\"components/*\"],\n \"@constants/*\": [\"constants/*\"],\n \"@pages/*\": [\"pages/*\"]\n }\n },\n ...\n}\n```\n\nScreenshot on the configuraton of nxViteTsPaths and tsconfigPaths plugins\n\nOn Nx's official document for configuring vite https://nx.dev/recipes/vite/configure-vite, they required to use **nxViteTsPaths()** plugin, but I failed to find enough doc or source code from https://nx.dev/plugin-registry.\n\nCould anyone insights on what additional functionality this nxViteTsPaths() does?\n\n========================================\n\nCode:\n```text\n{\n  \"compilerOptions\": {\n    ... \n    \"baseUrl\": \"./src\",\n    \"paths\": {\n      \"@components/*\": [\"components/*\"],\n      \"@constants/*\": [\"constants/*\"],\n      \"@pages/*\": [\"pages/*\"]\n    }\n  },\n  ...\n}\n```\n\n```js\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths';\n\nexport default defineConfig({\n  plugins: [\n    nxViteTsPaths(),\n    react(),\n  ],\n});\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@shared-ui/*\": [\"libs/shared-ui/src/*\"]\n    }\n  }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.433Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":71,"estimatedTokens":402}}517{"id":"stack-79875247","source":"stackoverflow","questionId":79875247,"title":"Pixi.js project has two canvases on reload","tags":["javascript","vite","pixi.js"],"text":"Title: Pixi.js project has two canvases on reload\nTags: javascript, vite, pixi.js\nSource: Stack Overflow\n\nQuestion:\nI'm working on a geometry dash clone with pixi.js and Vite. Everything is working smoothly, except for one development issue. When I run `npm run dev`, the game starts up correctly. However, when I change a line of code and go back to my browser to refresh the page, there's suddenly **two canvases inside the DOM instead of one**. Even though this issue is absent once I build and deploy the game, during development, it messes up the visuals and it even alters the game's physics and the player's jump speed! Note that the number of canvases never exceeds two.\n\nI've tried adding `container.innerHTML = \"\";` right before `container.appendChild(app.canvas);`, but that only removes the visual bug, the physics remain broken and look like they run 2x faster.\n\nScreenshot of the game during the bug\n\nHere's my game's source code: https://github.com/artingzdev/artin-dash, otherwise refer to the following code from `main.js`:\n\n```\nimport { Application } from \"pixi.js\";\nimport { scrollSpeed, speed, gameSpeed, speedMultiplier, tickSpeed } from \"./game-variables.js\";\nimport { createGroundContainer } from \"./ground.js\";\nimport { getRenderedSize, gridSpacesToPixels } from \"./utils.js\";\nimport { createBackgroundContainer } from \"./background.js\";\nimport { createMiddlegroundContainer } from \"./middleground.js\";\nimport { createPlayerContainer } from \"./player.js\";\nimport { jump, physics, resetCubeRotation, rotateCube, updateJumpVelocity, updatePlayerY } from \"./physics.js\";\nimport { jumpHeld } from \"./key-states.js\";\n\nexport let app = new Application();\nexport const defaultGroundPositionPercentage = (409/512);\n \n(async () => {\n await app.init({\n resizeTo: window,\n antialias: true,\n roundPixels: true\n });\n\n const container = document.getElementById(\"pixi-container\");\n container.appendChild(app.canvas);\n\n \n // Create containers\n const groundContainer = await createGroundContainer(app);\n groundContainer.y = app.screen.height - getRenderedSize(512 * defaultGroundPositionPercentage);\n\n const backgroundContainer = await createBackgroundContainer(app);\n const middlegroundContainer = await createMiddlegroundContainer(app);\n const playerContainer = await createPlayerContainer(app);\n\n // add the layers in order\n app.stage.addChild(backgroundContainer);\n app.stage.addChild(middlegroundContainer);\n app.stage.addChild(playerContainer);\n app.stage.addChild(groundContainer);\n app.ticker.speed = tickSpeed;\n\n window.addEventListener('resize', () => {\n app.resizeTo = window;\n })\n\n app.ticker.add((ticker) => {\n const deltaSeconds = ticker.deltaMS / 1000;\n groundContainer.groundSprite.tilePosition.x -= gridSpacesToPixels(scrollSpeed) * deltaSeconds * speed[gameSpeed].game;\n groundContainer.ground2Sprite.tilePosition.x -= gridSpacesToPixels(scrollSpeed) * deltaSeconds * speed[gameSpeed].game;\n backgroundContainer.backgroundSprite.tilePosition.x -= gridSpacesToPixels(scrollSpeed) * deltaSeconds * speed[gameSpeed].game * speedMultiplier.background;\n middlegroundContainer.middlegroundSprite.tilePosition.x -= gridSpacesToPixels(scrollSpeed) * deltaSeconds * speed[gameSpeed].game * speedMultiplier.middlegroundX;\n middlegroundContainer.middleground2Sprite.tilePosition.x -= gridSpacesToPixels(scrollSpeed) * deltaSeconds * speed[gameSpeed].game * speedMultiplier.middlegroundX;\n\n playerContainer.cubeSprite.y = groundContainer.y - gridSpacesToPixels(0.5) - gridSpacesToPixels(physics.playerY);\n updatePlayerY(deltaSeconds);\n rotateCube(deltaSeconds);\n resetCubeRotation(deltaSeconds);\n updateJumpVelocity()\n playerContainer.cubeSprite.rotation = physics.cubeRotation;\n\n if (jumpHeld) {jump()}\n });\n})();\n```\n\n========================================\n\nCode:\n```text\nimport { Application } from \"pixi.js\";\nimport { scrollSpeed, speed, gameSpeed, speedMultiplier, tickSpeed } from \"./game-variables.js\";\nimport { createGroundContainer } from \"./ground.js\";\nimport { getRenderedSize, gridSpacesToPixels } from \"./utils.js\";\nimport { createBackgroundContainer } from \"./background.js\";\nimport { createMiddlegroundContainer } from \"./middleground.js\";\nimport { createPlayerContainer } from \"./player.js\";\nimport { jump, physics, resetCubeRotation, rotateCube, updateJumpVelocity, updatePlayerY } from \"./physics.js\";\nimport { jumpHeld } from \"./key-states.js\";\n\nexport let app = new Application();\nexport const defaultGroundPositionPercentage = (409/512);\n \n(async () => {\n  await app.init({\n    resizeTo: window,\n    antialias: true,\n    roundPixels: true\n  });\n\n  const container = document.getElementById(\"pixi-container\");\n  container.appendChild(app.canvas);\n\n  \n  // Create containers\n  const groundContainer = await createGroundContainer(app);\n  groundContainer.y = app.screen.height - getRenderedSize(512 * defaultGroundPositionPercentage);\n\n  const backgroundContainer = await createBackgroundContainer(app);\n  const middlegroundContainer = await createMiddlegroundContainer(app);\n  const playerContainer = await createPlayerContainer(app);\n\n\n\n  // add the layers in order\n  app.stage.addChild(backgroundContainer);\n  app.stage.addChild(middlegroundContainer);\n  app.stage.addChild(playerContainer);\n  app.stage.addChild(groundContainer);\n  app.ticker.speed = tickSpeed;\n\n  window.addEventListener('resize', () => {\n    app.resizeTo = window;\n  })\n\n  app.ticker.add((ticker) => {\n    const deltaSeconds = ticker.deltaMS / 1000;\n    groundContainer.groundSprite.tilePosition.x -= gridSpacesToPixels(scrollSpeed) * deltaSeconds * speed[gameSpeed].game;\n    groundContainer.ground2Sprite.tilePosition.x -= gridSpacesToPixels(scrollSpeed) * deltaSeconds * speed[gameSpeed].game;\n    backgroundContainer.backgroundSprite.tilePosition.x -= gridSpacesToPixels(scrollSpeed) * deltaSeconds * speed[gameSpeed].game * speedMultiplier.background;\n    middlegroundContainer.middlegroundSprite.tilePosition.x -= gridSpacesToPixels(scrollSpeed) * deltaSeconds * speed[gameSpeed].game * speedMultiplier.middlegroundX;\n    middlegroundContainer.middleground2Sprite.tilePosition.x -= gridSpacesToPixels(scrollSpeed) * deltaSeconds * speed[gameSpeed].game * speedMultiplier.middlegroundX;\n\n    playerContainer.cubeSprite.y = groundContainer.y - gridSpacesToPixels(0.5) - gridSpacesToPixels(physics.playerY);\n    updatePlayerY(deltaSeconds);\n    rotateCube(deltaSeconds);\n    resetCubeRotation(deltaSeconds);\n    updateJumpVelocity()\n    playerContainer.cubeSprite.rotation = physics.cubeRotation;\n\n    if (jumpHeld) {jump()}\n  });\n})();\n```\n\n```text\nnpm run dev\n```\n\n```text\ncontainer.innerHTML = \"\";\n```\n\n```text\ncontainer.appendChild(app.canvas);\n```\n\n```text\nmain.js\n```\n\n```js\n// at the top of main.js (before creating the app)\nwindow.__ARTIN_GEN__ = (window.__ARTIN_GEN__ || 0) + 1;\nconst currentGen = window.__ARTIN_GEN__;\n```\n\n```js\nawait app.init({ ... });\n\nif (window.__ARTIN_GEN__ !== currentGen) {\n  app.destroy(true);\n  return;\n}\n```\n\n```js\nconst container = document.getElementById(\"pixi-container\");\ncontainer.replaceChildren();\ncontainer.appendChild(app.canvas);\n```\n\n```js\napp.ticker.add((ticker) => {\n  if (window.__ARTIN_GEN__ !== currentGen) {\n    app.ticker.stop();\n    app.destroy(true);\n    return;\n  }\n\n  // ... game logic\n});\n```\n\n```js\nwindow.addEventListener(\"resize\", () => {\n  if (window.__ARTIN_GEN__ === currentGen) {\n    app.resizeTo = window;\n  }\n});\n```\n\n```js\nif (import.meta.hot) {                                               \n    import.meta.hot.accept();                                          \n  }\n```\n\n```js\nimport { Application } from \"pixi.js\";\nimport {\n  scrollSpeed,\n  speed,\n  gameSpeed,\n  speedMultiplier,\n  tickSpeed,\n} from \"./game-variables.js\";\nimport { createGroundContainer } from \"./ground.js\";\nimport { getRenderedSize, gridSpacesToPixels } from \"./utils.js\";\nimport { createBackgroundContainer } from \"./background.js\";\nimport { createMiddlegroundContainer } from \"./middleground.js\";\nimport { createPlayerContainer } from \"./player.js\";\nimport {\n  jump,\n  physics,\n  resetCubeRotation,\n  rotateCube,\n  updateJumpVelocity,\n  updatePlayerY,\n} from \"./physics.js\";\nimport { jumpHeld } from \"./key-states.js\";\n\n\nwindow.__ARTIN_GEN__ = (window.__ARTIN_GEN__ || 0) + 1;\nconst currentGen = window.__ARTIN_GEN__;\n\nexport let app = new Application();\nexport const defaultGroundPositionPercentage = 409 / 512;\n\n(async () => {\n  await app.init({\n    resizeTo: window,\n    antialias: true,\n    roundPixels: true,\n  });\n\n  // if a newer generation started while awaiting, abort this one\n  if (window.__ARTIN_GEN__ !== currentGen) {\n    app.destroy(true);\n    return;\n  }\n\n  const container = document.getElementById(\"pixi-container\");\n  // remove any leftover canvases from previous instances\n  container.replaceChildren();\n  container.appendChild(app.canvas);\n\n  // create containers\n  const groundContainer = await createGroundContainer(app);\n  if (window.__ARTIN_GEN__ !== currentGen) {\n    app.destroy(true);\n    return;\n  }\n\n  groundContainer.y =\n    app.screen.height - getRenderedSize(512 * defaultGroundPositionPercentage);\n\n  const backgroundContainer = await createBackgroundContainer(app);\n  if (window.__ARTIN_GEN__ !== currentGen) {\n    app.destroy(true);\n    return;\n  }\n\n  const middlegroundContainer = await createMiddlegroundContainer(app);\n  if (window.__ARTIN_GEN__ !== currentGen) {\n    app.destroy(true);\n    return;\n  }\n\n  const playerContainer = await createPlayerContainer(app);\n  if (window.__ARTIN_GEN__ !== currentGen) {\n    app.destroy(true);\n    return;\n  }\n\n  // add the layers in order\n  app.stage.addChild(backgroundContainer);\n  app.stage.addChild(middlegroundContainer);\n  app.stage.addChild(playerContainer);\n  app.stage.addChild(groundContainer);\n  app.ticker.speed = tickSpeed;\n\n  window.addEventListener(\"resize\", () => {\n    if (window.__ARTIN_GEN__ === currentGen) {\n      app.resizeTo = window;\n    }\n  });\n\n  app.ticker.add((ticker) => {\n    // if a newer instance has started, stop this stale ticker\n    if (window.__ARTIN_GEN__ !== currentGen) {\n      app.ticker.stop();\n      app.destroy(true);\n      return;\n    }\n\n    const deltaSeconds = ticker.deltaMS / 1000;\n    groundContainer.groundSprite.tilePosition.x -=\n      gridSpacesToPixels(scrollSpeed) * deltaSeconds * speed[gameSpeed].game;\n    groundContainer.ground2Sprite.tilePosition.x -=\n      gridSpacesToPixels(scrollSpeed) * deltaSeconds * speed[gameSpeed].game;\n    backgroundContainer.backgroundSprite.tilePosition.x -=\n      gridSpacesToPixels(scrollSpeed) *\n      deltaSeconds *\n      speed[gameSpeed].game *\n      speedMultiplier.background;\n    middlegroundContainer.middlegroundSprite.tilePosition.x -=\n      gridSpacesToPixels(scrollSpeed) *\n      deltaSeconds *\n      speed[gameSpeed].game *\n      speedMultiplier.middlegroundX;\n    middlegroundContainer.middleground2Sprite.tilePosition.x -=\n      gridSpacesToPixels(scrollSpeed) *\n      deltaSeconds *\n      speed[gameSpeed].game *\n      speedMultiplier.middlegroundX;\n\n    playerContainer.cubeSprite.y =\n      groundContainer.y -\n      gridSpacesToPixels(0.5) -\n      gridSpacesToPixels(physics.playerY);\n    updatePlayerY(deltaSeconds);\n    rotateCube(deltaSeconds);\n    resetCubeRotation(deltaSeconds);\n    updateJumpVelocity();\n    playerContainer.cubeSprite.rotation = physics.cubeRotation;\n\n    if (jumpHeld) {\n      jump();\n    }\n  });\n})();\n\nif (import.meta.hot) {\n  import.meta.hot.accept();\n}\n```\n\n```text\napp.ticker\n```\n\n```text\nwindow\n```\n\n```text\nawait\n```\n\n```text\nmain.js\n```\n\n========================================\n\nComments:\n- Incredible work 🙏 I also noticed now that it the page automatically reloads when I edit a file, unlike before. How did you do that?\n- @ArtinGoodarzi if (import.meta.hot) { import.meta.hot.accept(); }","metadata":{"transformedAt":"2026-08-18T18:33:46.433Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":370,"estimatedTokens":2942}}518{"id":"stack-79815537","source":"stackoverflow","questionId":79815537,"title":"How to import types from module without qualified name?","tags":["typescript","vite","react-typescript"],"text":"Title: How to import types from module without qualified name?\nTags: typescript, vite, react-typescript\nSource: Stack Overflow\n\nQuestion:\nIn a React web app I have a typescript module from which I'm exporting a series of types, and I want to import some of them into my App.tsx. The module exporting the types looks like this:\n\n```\n// poker_messages.ts\nexport type Card = { suit: string; rank: string };\n//...\nexport type IncomingPokerMessage = General | PlaceBet | Error;\n```\n\nIn App.tsx I can import them like this:\n\n```\nimport * as PM from './poker_messages';\n```\n\nThen refer to the types as `PM.Card` etc. But if I try\n\n```\nimport { Card, IncomingPokerMessage } from './poker_messages';\n```\n\nI get an error that the module does not export those names. What's the right way to import only those things I need and without the qualified name?\n\n========================================\n\nCode:\n```text\n// poker_messages.ts\nexport type Card = { suit: string; rank: string };\n//...\nexport type IncomingPokerMessage = General | PlaceBet | Error;\n```\n\n```text\nimport * as PM from './poker_messages';\n```\n\n```text\nimport { Card, IncomingPokerMessage } from './poker_messages';\n```\n\n```text\nPM.Card\n```\n\n```js\nimport * as PM from './poker_messages';\n```\n\n```text\nimport { Card, IncomingPokerMessage } from './poker_messages';\n```\n\n```text\nimport type { Card, IncomingPokerMessage } from './poker_messages';\n```\n\n```text\ntype\n```\n\n```text\nimport\n```\n\n```text\nimport type { A } from './foo';\n```\n\n```text\nimport { type A } from './foo';\n```\n\n```text\nimport { A } from './foo';\n```\n\n```text\ntsconfig.json\n```\n\n```text\npoker_messages.ts\n```\n\n```text\nPM\n```\n\n========================================\n\nComments:\n- import type { Card, IncomingPokerMessage } from './poker_messages'; or try { \"compilerOptions\": { \"isolatedModules\": false } }","metadata":{"transformedAt":"2026-08-18T18:33:46.433Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":98,"estimatedTokens":457}}519{"id":"stack-77886982","source":"stackoverflow","questionId":77886982,"title":"Failed to load resources with vite pwa plugin in dev mode","tags":["vue.js","vite","progressive-web-apps","service-worker","workbox"],"text":"Title: Failed to load resources with vite pwa plugin in dev mode\nTags: vue.js, vite, progressive-web-apps, service-worker, workbox\nSource: Stack Overflow\n\nQuestion:\nI have a really simple vite app on which I try to use vite-pwa plugin in order to use it offline. It works well when building the app (`npm run build` and then `npm run preview`), but not in dev mode. When running `npm run dev`, no resources are loaded correctly:\nhttps://i.sstatic.net/N2p0w.png\n\nMy vite.config.ts looks like this:\n\n```\n...\nimport { VitePWA } from 'vite-plugin-pwa'\n\nexport default defineConfig({\n plugins: [vue(), VitePWA({\n registerType: 'autoUpdate',\n devOptions: {\n enabled: true,\n },\n manifest: {\n name: 'Your App Name',\n start_url: '.',\n display: 'standalone',\n icons: [\n {\n src: 'icon.svg',\n sizes: '192x192',\n type: 'image/svg+xml',\n }\n ],\n },\n })],\n})\n```\n\nI've tried to add a custom cache using the workbox option in the vite.config.ts, but with no success.\n\n```\nworkbox: {\n {\n urlPattern: ({ url }) => {\n let suffixArray = [\".ts\", \".vue\", \".svg\", \".css\", \".webmanifest\", \".js\"];\n return suffixArray.some(suffix => url.pathname.endsWith(suffix));\n },\n handler: 'CacheFirst',\n options: {\n cacheName: 'static-cache',\n expiration: {\n maxEntries: 10,\n maxAgeSeconds: 60 * 60 * 24 * 365\n },\n cacheableResponse: {\n statuses: [0, 200]\n },\n }\n }\n```\n\nThis `static-cache` seems to be caching some of the files, but not all, such as the main.ts file. And when I switch to offline mode, no resources are loaded.\n\nSo basically, I dont understand why the offline mode works well when the app is built, but not when in dev mode? I have read a lot on this subject, and it is still unclear to me what the underlying problem is. Any help would be really appreciated!\n\n========================================\n\nTop Answer:\nInside your VitePWA({}), add these lines to cache all the required data:\n\n```\nworkbox: {\n globPatterns: [\"**/*\"],\n },\n includeAssets: [\"**/*\"],\n```\n\n========================================\n\nCode:\n```text\n...\nimport { VitePWA } from 'vite-plugin-pwa'\n\nexport default defineConfig({\n  plugins: [vue(), VitePWA({\n    registerType: 'autoUpdate',\n    devOptions: {\n      enabled: true,\n    },\n    manifest: {\n      name: 'Your App Name',\n      start_url: '.',\n      display: 'standalone',\n      icons: [\n        {\n          src: 'icon.svg',\n          sizes: '192x192',\n          type: 'image/svg+xml',\n        }\n      ],\n    },\n  })],\n})\n```\n\n```text\nworkbox: {\n  {\n    urlPattern: ({ url }) => {\n      let suffixArray = [\".ts\", \".vue\", \".svg\", \".css\", \".webmanifest\", \".js\"];\n      return suffixArray.some(suffix => url.pathname.endsWith(suffix));\n    },\n    handler: 'CacheFirst',\n    options: {\n      cacheName: 'static-cache',\n      expiration: {\n        maxEntries: 10,\n        maxAgeSeconds: 60 * 60 * 24 * 365\n      },\n      cacheableResponse: {\n        statuses: [0, 200]\n      },\n    }\n  }\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm run preview\n```\n\n```text\nnpm run dev\n```\n\n```text\nstatic-cache\n```\n\n```text\nmaxEntries:10\n```\n\n```text\nworkbox: {\n    globPatterns: [\"**/*\"],\n  },\n  includeAssets: [\"**/*\"],\n```\n\n========================================\n\nComments:\n- I've just had the same issue, but found this...maybe there's an answer there ? vite-pwa-org.netlify.app/guide/development#generatesw-strate&zwnj;&#8203;gy In my case the error is occurring on the built app, not in Dev.\n- I did try this solution but it didn't work. I really had to specify every different URL pattern possible to successfully store all the resources needed.","metadata":{"transformedAt":"2026-08-18T18:33:46.434Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":157,"estimatedTokens":886}}520{"id":"stack-77804403","source":"stackoverflow","questionId":77804403,"title":"Angular new Vite builder compilation error when using sass with @use statements","tags":["angular","sass","vite"],"text":"Title: Angular new Vite builder compilation error when using sass with @use statements\nTags: angular, sass, vite\nSource: Stack Overflow\n\nQuestion:\nCompilation error when trying to use Vite builder.\n\n```\n[ERROR] Can't find stylesheet to import.\n@use 'src/styles/utils/mixins' as mixins;\nsrc\\app\\app.component.scss 1:1 root stylesheet [plugin angular-sass]\n```\n\nhttps://i.sstatic.net/uLPoY.png\n\nConfigs:\nhttps://i.sstatic.net/4SwNZ.png\n\nthere was no issue with esbuild browser builder.\n\n========================================\n\nCode:\n```text\n[ERROR] Can't find stylesheet to import.\n@use 'src/styles/utils/mixins' as mixins;\nsrc\\app\\app.component.scss 1:1 root stylesheet [plugin angular-sass]\n```\n\n```text\n\"stylePreprocessorOptions\": {\n  \"includePaths\": [\n    \"\"\n  ]\n},\n```\n\n```text\n\"stylePreprocessorOptions\": {\n  \"includePaths\": [\n    \"projects/<project-name>\"\n  ]\n},\n```\n\n```text\nincludePaths\n```\n\n```text\nincludePaths\n```\n\n```text\nangular.json\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.434Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":56,"estimatedTokens":238}}521{"id":"stack-77559137","source":"stackoverflow","questionId":77559137,"title":"Why do my React routes no longer match when I configure Vite base?","tags":["react-router-dom","vite"],"text":"Title: Why do my React routes no longer match when I configure Vite base?\nTags: react-router-dom, vite\nSource: Stack Overflow\n\nQuestion:\nBefore setting `base` in my Vite configuration I can visit the app root at http://localhost:5173 without issue (renders 'Home'). When I add base though with a value of `/tools/evidence` and visit http://localhost:5173/tools/evidence as helpfully output by the Vite dev server it doesn't work - its instead renders the `` component.\n\nI have put some debug in Not Found component and the paths are as expected. I can't figure out why they aren't resolving ...\n\nHere are my routes ...\n\n```\n// ... imports ...\n\nconst NotFound = () => {\n const location = useLocation()\n console.log(location)\n return \n\n### Not Found\n\n}\n\nReactDOM.createRoot(document.getElementById(\"root\")!).render(\n \n \n \n \n Home} />\n \n \n \n \n }\n />\n } />\n } />\n } />\n } />\n } />\n } />\n \n \n \n \n);\n```\n\nhere is my `vite.config.ts`\n\n```\n// ... imports ...\n\nexport default defineConfig({\n plugins: [react()],\n base: '/tools/evidence',\n css: {\n postcss: {\n plugins: [\n postcssNesting\n ]\n }\n }\n})\n```\n\n========================================\n\nCode:\n```text\n// ... imports ...\n\nconst NotFound = () => {\n  const location = useLocation()\n  console.log(location)\n  return <h1>Not Found</h1>\n}\n\nReactDOM.createRoot(document.getElementById(\"root\")!).render(\n  <React.StrictMode>\n    <ApolloProvider client={client}>\n      <BrowserRouter>\n        <Routes>\n          <Route index element={<div>Home</div>} />\n          <Route\n            path=\"/topics/*\"\n            element={\n              <>\n                <EditorRoutes />\n                <PrintRoutes />\n              </>\n            }\n          />\n          <Route path=\"/feedback\" element={<FeedbackPage />} />\n          <Route path=\"/accessibility\" element={<Accessibility />} />\n          <Route path=\"/cookies\" element={<Cookies />} />\n          <Route path=\"/algorithms\" element={<Algorithms />} />\n          <Route path=\"/privacy\" element={<Privacy />} />\n          <Route path=\"*\" element={<NotFound />} />\n        </Routes>\n      </BrowserRouter>\n    </ApolloProvider>\n  </React.StrictMode>\n);\n```\n\n```text\n// ... imports ...\n\nexport default defineConfig({\n  plugins: [react()],\n  base: '/tools/evidence',\n  css: {\n    postcss: {\n      plugins: [\n        postcssNesting\n      ]\n    }\n  }\n})\n```\n\n```text\nbase\n```\n\n```text\n/tools/evidence\n```\n\n```text\n<Not Found />\n```\n\n```text\nvite.config.ts\n```\n\n```text\nReactDOM.createRoot(document.getElementById(\"root\")!).render(\n  <React.StrictMode>\n    <ApolloProvider client={client}>\n      <BrowserRouter basename=\"/tools/evidence\">    // <-- router basename\n        <Routes>\n          <Route index element={<div>Home</div>} /> // \"/tools/evidence\"\n          <Route\n            path=\"/topics/*\"                        // \"/tools/evidence/topics/*\"\n            element={\n              <>\n                <EditorRoutes />\n                <PrintRoutes />\n              </>\n            }\n          />\n          <Route\n            path=\"/feedback\"                        // \"/tools/evidence/feedback\"\n            element={<FeedbackPage />}\n          />\n          <Route path=\"/accessibility\" element={<Accessibility />} />\n          <Route path=\"/cookies\" element={<Cookies />} />\n          <Route path=\"/algorithms\" element={<Algorithms />} />\n          <Route path=\"/privacy\" element={<Privacy />} />\n          <Route path=\"*\" element={<NotFound />} />\n        </Routes>\n      </BrowserRouter>\n    </ApolloProvider>\n  </React.StrictMode>\n);\n```\n\n```text\nbasename\n```\n\n```text\n\"/tools/evidence/feedback\"\n```\n\n========================================\n\nComments:\n- Yes! Funny this isn't in the Vite docs ... for what its worth, you can use `basename={import.meta.env.BASE_URL}` instead of hard-coding","metadata":{"transformedAt":"2026-08-18T18:33:46.434Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":182,"estimatedTokens":947}}522{"id":"stack-77765741","source":"stackoverflow","questionId":77765741,"title":"How to add global variable if not defined","tags":["javascript","reactjs","vite"],"text":"Title: How to add global variable if not defined\nTags: javascript, reactjs, vite\nSource: Stack Overflow\n\nQuestion:\nWhen d3.js moved to version 4, there was a significant rewrite of the Api, and also a change to modular packaging.\n\nI don't want to upgrade to version 4 of d3.js but I have to rewrite the react/redux web app portion of my project using Vite, and version 3 of d3.js and it's use of global is not compatible with the JavaScript modular system used by Vite.\n\nThe error I'm getting is that \"global\" is not defined, and version 3 of d3.js uses \"global.\"\n\nThis is what it says it `node_modules/d3/index.js (index.js:4:13)`\n\n```\nvar globals = {};\n\n// Stash old global.\nif (\"d3\" in global) globals.d3 = global.d3;\n\nmodule.exports = require(\"./d3\");\n\n// Restore old global.\nif (\"d3\" in globals) global.d3 = globals.d3; else delete global.d3;\n```\n\nTherefore, I commented out that reference to global in the d3/index.js file to see what would happen, and I got a similar property, \"cannot read properties of undefined (document)\" This is the source code\n\n```\nvar d3_document = this.document;\nfunction d3_documentElement(node) {\n return node && (node.ownerDocument || node.document || node).documentElement;\n}\n```\n\nI'm guessing this has something to do with the shift to modular d3 in version 4, but d3.js version 3.5.5 works fine when I don't use it with Vite.js. For example, if I just source it in an index.html file and run it with an http-server.\n\nQuestion: is there a way to configure Vite.js to make it work with d3.js version 3.5.5? or can I alter the d3.js version 3.5.5 source code to make it run on Vite.js?\n\nUpdate\n\nI added this to the Vite.config.js\n\n```\ndefine: {\n global: {},\n document: {}\n }\n```\n\nNow Vite complains that the property `document` cannot be set on `#.`\n\n`3env.ts:24 Uncaught TypeError: Cannot set property document of # which has only a getter`\n\nThis StackOverflow question helps but it doesn't explain when \"document\" is undefined and it can't be \"set\" on Window.\n\nProbably irrelevant but here's the source code for d3 version 3.5.5 on unpkg.com\nd3 version 3.5.5`\n\nHere's the source code for d3 version 4 on unpkg.com\nd3 version 4\n\n========================================\n\nCode:\n```text\nvar globals = {};\n\n// Stash old global.\nif (\"d3\" in global) globals.d3 = global.d3;\n\nmodule.exports = require(\"./d3\");\n\n// Restore old global.\nif (\"d3\" in globals) global.d3 = globals.d3; else delete global.d3;\n```\n\n```text\nvar d3_document = this.document;\nfunction d3_documentElement(node) {\n  return node && (node.ownerDocument || node.document || node).documentElement;\n}\n```\n\n```text\ndefine: {\n    global: {},\n    document: {}\n  }\n```\n\n```text\nnode_modules/d3/index.js (index.js:4:13)\n```\n\n```text\ndocument\n```\n\n```text\n#<Window>.\n```\n\n```text\n3env.ts:24  Uncaught TypeError: Cannot set property document of #<Window> which has only a getter\n```\n\n```js\n!function() {\n  // ...\n}()\n```\n\n```js\n(function() {\n  // ...\n}).call(window)\n```\n\n```text\nnode_modules/d3/d3.js\n```\n\n```text\nthis\n```\n\n```text\nthis.document\n```\n\n```text\nwindow.document\n```\n\n```text\ndocument\n```\n\n```text\nthis\n```\n\n```text\nindex.html\n```\n\n```text\n<script type=\"text/javascript\">\n```\n\n```text\nthis\n```\n\n```text\nwindow\n```\n\n```text\n<script type=\"module\">\n```\n\n```text\nthis\n```\n\n```text\nundefined\n```\n\n```text\nvite.config.js\n```\n\n```text\nthis\n```\n\n```text\nthis.document\n```\n\n```text\nthis\n```\n\n```text\nfunction(){}\n```\n\n```text\nthis\n```\n\n```text\nthis\n```\n\n```text\nthis:'window'\n```\n\n```text\n'this.document':'window.document'\n```\n\n```text\nthis\n```\n\n```text\nnode_modules/d3/d3.js\n```\n\n```text\nnode_modules\n```\n\n```text\nnode_modules/d3/index.js\n```\n\n```text\n3.5.17\n```\n\n========================================\n\nComments:\n- Does stackoverflow.com/q/72114775/51685 help?\n- @AKK yes, it does help a lot, at least it explains that I can define things in the Vite.config.js. However, (see update in OP). I can't set \"document\" on Window.\n- `document` will always be set, though.\n- @AKX that's what I assumed but this is the error message: `Cannot read properties of undefined (document)`: `var d3_document = this.document;`\n- If altering the d3 source is an option then can't you just give it the `this` parameter explicitly? You'd only have to put `.call(window)` or `.call(globalThis)` at the end of the file, so it would look like this `(function(){...}).call(window)`, instead of like this `!function(){...}()`. Their code works in a simple `index.html` file because by default `this` is `window`. The fact that their code uses `this` makes it easy to supply a custom object.\n- @zoran404 this is a good fallback option. My bounty said I'd prefer a solution involving the Vite config, but if it doesn't come I will give you the bounty, but you'd have to post an answer.\n- Maybe it's possible to only use the config. I can check later. This is just the first solution that came to my mind.","metadata":{"transformedAt":"2026-08-18T18:33:46.434Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":36,"totalLines":236,"estimatedTokens":1219}}523{"id":"stack-77130763","source":"stackoverflow","questionId":77130763,"title":"Trouble with Gitlab CI and VITE environment variables","tags":["reactjs","gitlab","vite"],"text":"Title: Trouble with Gitlab CI and VITE environment variables\nTags: reactjs, gitlab, vite\nSource: Stack Overflow\n\nQuestion:\nI have searched (both offical documentation and what feels like all of the internet) and tested multiple approaches, but I cannot for the life of me wrap my head around environment variables in VITE with Gitlab pipelines.\n\nWith CRA this worked great (using `CREATE_APP_var1`).\n\nI now have the following setup in my pipeline, and deployments to dev and production got their different set of variable-values (shortened for brevity):\n\n```\nstages:\n - build\n - image\n - chart\n - deploy\n.build:\n stage: build\n image: node:16\n variables:\n CI: 'false'\n VITE_ENV: '$ENVIRONMENT'\n VITE_COMMIT: '$CI_COMMIT_MESSAGE'\n before_script:\n - printenv | grep -E '^(VITE_|ENVIRONMENT)' # this is to print what gitlab sees, and it sees the correct values from `build:dev:`-step\n script:\n - npm ci\n - npm run build\n artifacts:\n paths:\n - build\n expire_in: 2 weeks\n\nbuild:dev:\n extends:\n - .build\n environment:\n name: Dev\n variables:\n ENVIRONMENT: 'development'\n IMAGE_NAME: 'image/path'\n VITE_var1: 'value1'\n VITE_TESTMESSAGE: 'This is a test message'\n only:\n - develop-branch\n\nbuild:prod:\n extends:\n - .build\n variables:\n ENVIRONMENT: 'production'\n VITE_BUILD: '$CI_COMMIT_TAG'\n VITE_var1: 'value1'\n VITE_var2: 'value2'\n only:\n variables:\n - $CI_COMMIT_TAG =~ /^\\d+\\.\\d+\\.\\d+$/\n```\n\nSo my pipeline triggers on any pushed commit to develop-branch, and for production only commits with a tag. So far so good.\n\nIn my repository I also have the files:\n\n- .env.development.local - this is loaded fine and localhost holds development values\n\n- .env.production - this works in production, all values are loaded\n\nNow, seeing as I am passing to the build stage, via extension build:dev the values for `VITE_var1` and `VITE_TESTMESSAGE` I assume that these will \"win\" over any other variables with the same name. I am accessing the values in my code like this, just to verify if it works:\n\n```\nconfig.js\nconsole.log('VITE_var1 env', import.meta.env.VITE_var1); // returns prod value\nconsole.log('VITE_TESTMESSAGE env', import.meta.env.VITE_TESTMESSAGE); // returns undefined\n```\n\nNo matter what I do here I get the values from .env.production (when running the dev-steps) and variables set in the ci-file is ignored.\n\nI have also tried setting up .env.development and running a separate build-dev script in package.json:\n\n```\n\"build-dev\": \"tsc && vite build --mode development\",\n```\n\nand if ci commit branch == develop-branch:\n\n```\n- if [[ \"$CI_COMMIT_BRANCH\" == \"Dev\" ]]; then npm run build-dev; else npm run build; fi\n```\n\nAny pointers as to what I am clearly not understanding here would be greatly appreciated.\n\n========================================\n\nCode:\n```text\nstages:\n  - build\n  - image\n  - chart\n  - deploy\n.build:\n  stage: build\n  image: node:16\n  variables:\n    CI: 'false'\n    VITE_ENV: '$ENVIRONMENT'\n    VITE_COMMIT: '$CI_COMMIT_MESSAGE'\n  before_script:\n    - printenv | grep -E '^(VITE_|ENVIRONMENT)' # this is to print what gitlab sees, and it sees the correct values from `build:dev:`-step\n  script:\n    - npm ci\n    - npm run build\n  artifacts:\n    paths:\n      - build\n    expire_in: 2 weeks\n\nbuild:dev:\n  extends:\n    - .build\n  environment:\n    name: Dev\n  variables:\n    ENVIRONMENT: 'development'\n    IMAGE_NAME: 'image/path'\n    VITE_var1: 'value1'\n    VITE_TESTMESSAGE: 'This is a test message'\n  only:\n    - develop-branch\n\nbuild:prod:\n  extends:\n    - .build\n  variables:\n    ENVIRONMENT: 'production'\n    VITE_BUILD: '$CI_COMMIT_TAG'\n    VITE_var1: 'value1'\n    VITE_var2: 'value2'\n  only:\n    variables:\n      - $CI_COMMIT_TAG =~ /^\\d+\\.\\d+\\.\\d+$/\n```\n\n```text\nconfig.js\nconsole.log('VITE_var1 env', import.meta.env.VITE_var1); // returns prod value\nconsole.log('VITE_TESTMESSAGE env', import.meta.env.VITE_TESTMESSAGE); // returns undefined\n```\n\n```text\n\"build-dev\": \"tsc && vite build --mode development\",\n```\n\n```text\n- if [[ \"$CI_COMMIT_BRANCH\" == \"Dev\" ]]; then npm run build-dev; else npm run build; fi\n```\n\n```text\nCREATE_APP_var1\n```\n\n```text\nVITE_var1\n```\n\n```text\nVITE_TESTMESSAGE\n```\n\n```text\nbuild\n```\n\n```text\nimage\n```\n\n```text\nimage:dev\n```\n\n```text\nimage:prod\n```\n\n```text\ndockerfile\n```\n\n```text\ntsc && vite build\n```\n\n```text\ntsc && vite build --mode development\n```\n\n```text\n.env.production\n```\n\n```text\n.env.development\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.434Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":205,"estimatedTokens":1093}}524{"id":"stack-76208122","source":"stackoverflow","questionId":76208122,"title":"New TypeScript React app using Vite - JSX.IntrinsicElements errors","tags":["reactjs","typescript","jsx","vite"],"text":"Title: New TypeScript React app using Vite - JSX.IntrinsicElements errors\nTags: reactjs, typescript, jsx, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying out Vite with React TS and using their official documentation. The app builds and runs, however viewing it in VS Code shows a whole bunch of `Property 'div' does not exist on type 'JSX.IntrinsicElements'.ts(2339)` errors.\n\nI've created a new React TS application using `npx create-react-app my-app --template typescript` and am not getting this issue.\n\nLooking at Vite documentation once again, they've got a stackblitz link that exhibits the same issue, so this means that this is not my environment that's the problem.\n\nAm I missing something? Surely this should not be a problem for official Vite documentation? Please note however, that I'm new to React and Vite.\n\n========================================\n\nCode:\n```text\nProperty 'div' does not exist on type 'JSX.IntrinsicElements'.ts(2339)\n```\n\n```text\nnpx create-react-app my-app --template typescript\n```\n\n```text\n\"moduleResolution\": \"bundler\"\n```\n\n```text\n\"moduleResolution\": \"node\"\n```\n\n========================================\n\nComments:\n- Seems not even to be so well documented what bundler is doing: typescriptlang.org/docs/handbook/module-resolution.html Here it says to strategies: Node or Classic but nothing about bundler","metadata":{"transformedAt":"2026-08-18T18:33:46.434Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":36,"estimatedTokens":337}}525{"id":"stack-77025254","source":"stackoverflow","questionId":77025254,"title":"Error when using Web3.js with Vite and TypeScript in a React.js Project: \"Module 'events' has been externalized for browser compatibility\"","tags":["reactjs","typescript","vite","web3js","web3-react"],"text":"Title: Error when using Web3.js with Vite and TypeScript in a React.js Project: \"Module 'events' has been externalized for browser compatibility\"\nTags: reactjs, typescript, vite, web3js, web3-react\nSource: Stack Overflow\n\nQuestion:\nI'm developing a React.js project with TypeScript managed with Vite, and I'm facing an issue when trying to integrate Web3.js for communication with Ethereum Smart Contracts. The project is set up to connect to a local Ethereum blockchain running on Ganache at `http://localhost:7545`.\n\nI installed Web3.js using `npm install web3` and attempted to create a Web3 instance like this:\n\n```\nimport Web3 from 'web3';\n\nconst web3 = new Web3(Web3.givenProvider || 'http://localhost:7545');\n```\n\nHowever, as soon as I call any Web3.js functions, such as `const web3 = new Web3(Web3.givenProvider || 'http://localhost:7545');` or `Web3.version`, I receive the following warnings and errors in the console:\n\n- `Module \"events\" has been externalized for browser compatibility. Cannot access \"events.EventEmitter\" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`\n\n- `Uncaught TypeError: Class extends value undefined is not a constructor or null at common.ts:58:29 (anonymous) @ common.ts:58`\n\nThis is a React.js project managed with Vite, and I have limited experience with modern frontend technology stacks. I'm wondering if there are additional configurations or setups I need to perform to successfully integrate Web3.js into my frontend project.\n\nAny guidance, suggestions, or insights on how to resolve these issues and correctly configure Web3.js within my React.js/Vite/TypeScript project would be highly appreciated.\n\n========================================\n\nTop Answer:\nFor the sake of completeness here are the steps that solved my problem for the community:\n\n- Run in the project directory `npm install --save-dev vite-plugin-node-polyfills` in order to install `vite-plugin-node-polyfills`.\n\n- Add the `nodePolyfills`-plugin into your `vite.config.ts`-file:\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport {nodePolyfills} from 'vite-plugin-node-polyfills';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react(), nodePolyfills()],\n})\n```\n\n========================================\n\nCode:\n```js\nimport Web3 from 'web3';\n\nconst web3 = new Web3(Web3.givenProvider || 'http://localhost:7545');\n```\n\n```text\nhttp://localhost:7545\n```\n\n```text\nnpm install web3\n```\n\n```text\nconst web3 = new Web3(Web3.givenProvider || 'http://localhost:7545');\n```\n\n```text\nWeb3.version\n```\n\n```text\nModule \"events\" has been externalized for browser compatibility. Cannot access \"events.EventEmitter\" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\n```\n\n```text\nUncaught TypeError: Class extends value undefined is not a constructor or null at common.ts:58:29 (anonymous) @ common.ts:58\n```\n\n```text\nevents\n```\n\n```text\nvite.config\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport {nodePolyfills} from 'vite-plugin-node-polyfills';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react(), nodePolyfills()],\n})\n```\n\n```text\nnpm install --save-dev vite-plugin-node-polyfills\n```\n\n```text\nvite-plugin-node-polyfills\n```\n\n```text\nnodePolyfills\n```\n\n```text\nvite.config.ts\n```\n\n========================================\n\nComments:\n- just a heads up, you dont need neccesary all the polyfills, I would just reduce to the one you need","metadata":{"transformedAt":"2026-08-18T18:33:46.434Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":117,"estimatedTokens":909}}526{"id":"stack-76049117","source":"stackoverflow","questionId":76049117,"title":"CypressError: Timed out after 5000ms `cy.wait()` ...No Request ever occurred","tags":["reactjs","typescript","cypress","vite"],"text":"Title: CypressError: Timed out after 5000ms `cy.wait()` ...No Request ever occurred\nTags: reactjs, typescript, cypress, vite\nSource: Stack Overflow\n\nQuestion:\nI have decided to build a React app using Vite, Chakra-UI, and TypeScript with testing done in Cypress. The goal was to learn more about some of these technologies. Coincidentally, this is my first time using Cypress.\n\nUnfortunately, I've gotten snagged on the issue regarding testing the `.wait()` in an E2E test. The error specifically reads: `CypressError: Timed out retrying after 5000ms:`cy.wait()`timed out waiting`5000ms`for the 1st request to the route:`getGames`. No request ever occurred.` I've seen a lot of advice regarding stubbing first before visiting the page and then waiting for the call. However, after multiple attempts, I just can't seem to get the wait call to NOT time out. My latest attempt has been to intercept in a before call before beforeEach-ing the visit function call. As you can see from the image I've uploaded, the intercept seems to be registered, but never increments.\n\nHas anyone encountered this, and has a potential solution? Thank you in advance!\n\nCypress Console:\n\nhttps://i.sstatic.net/exXno.png\n\nI have a fixture defined as `games.json` which contains the following content:\n\n```\n[\n {\n \"id\": 1,\n \"name\": \"The Witcher 3: Wild Hunt\",\n \"background_image\": \"https://media.rawg.io/media/crop/600/400/games/618/618c2031a07bbff6b4f611f10b6bcdbc.jpg\",\n \"parent_platforms\": [\n { \"id\": 1, \"name\": \"PC\", \"slug\": \"pc\" },\n { \"id\": 2, \"name\": \"PlayStation\", \"slug\": \"playstation\" },\n { \"id\": 3, \"name\": \"Xbox\", \"slug\": \"xbox\" },\n { \"id\": 7, \"name\": \"Nintendo\", \"slug\": \"nintendo\" }\n ],\n \"metacritic\": \"92\"\n },\n {\n \"id\": 2,\n \"name\": \"BioShock Infinite\",\n \"background_image\": \"https://media.rawg.io/media/crop/600/400/games/fc1/fc1307a2774506b5bd65d7e8424664a7.jpg\",\n \"parent_platforms\": [\n { \"id\": 1, \"name\": \"PC\", \"slug\": \"pc\" },\n { \"id\": 2, \"name\": \"PlayStation\", \"slug\": \"playstation\" },\n { \"id\": 3, \"name\": \"Xbox\", \"slug\": \"xbox\" },\n { \"id\": 6, \"name\": \"Linux\", \"slug\": \"linux\" },\n { \"id\": 7, \"name\": \"Nintendo\", \"slug\": \"nintendo\" }\n ],\n \"metacritic\": \"94\"\n }\n]\n```\n\n`../support/commands.ts`:\n\n```\nconst baseURL = \"**http://api.rawg.io/api*\";\n\nCypress.Commands.add(\"landing\", () => {\n cy.intercept(\"GET\", `${baseURL}/games`, { fixture: \"games.json\" }).as(\n \"getGames\"\n );\n});\n```\n\nAnd my test file:\n\n```\ndescribe(\"The Home Page\", () => {\n before(() => {\n cy.landing();\n });\n\n beforeEach(() => {\n cy.visit(\"/\");\n });\n\n it(\"successfully loads\", () => {\n cy.wait(\"@getGames\");\n });\n});\n```\n\n========================================\n\nCode:\n```text\n[\n  {\n    \"id\": 1,\n    \"name\": \"The Witcher 3: Wild Hunt\",\n    \"background_image\": \"https://media.rawg.io/media/crop/600/400/games/618/618c2031a07bbff6b4f611f10b6bcdbc.jpg\",\n    \"parent_platforms\": [\n      { \"id\": 1, \"name\": \"PC\", \"slug\": \"pc\" },\n      { \"id\": 2, \"name\": \"PlayStation\", \"slug\": \"playstation\" },\n      { \"id\": 3, \"name\": \"Xbox\", \"slug\": \"xbox\" },\n      { \"id\": 7, \"name\": \"Nintendo\", \"slug\": \"nintendo\" }\n    ],\n    \"metacritic\": \"92\"\n  },\n  {\n    \"id\": 2,\n    \"name\": \"BioShock Infinite\",\n    \"background_image\": \"https://media.rawg.io/media/crop/600/400/games/fc1/fc1307a2774506b5bd65d7e8424664a7.jpg\",\n    \"parent_platforms\": [\n      { \"id\": 1, \"name\": \"PC\", \"slug\": \"pc\" },\n      { \"id\": 2, \"name\": \"PlayStation\", \"slug\": \"playstation\" },\n      { \"id\": 3, \"name\": \"Xbox\", \"slug\": \"xbox\" },\n      { \"id\": 6, \"name\": \"Linux\", \"slug\": \"linux\" },\n      { \"id\": 7, \"name\": \"Nintendo\", \"slug\": \"nintendo\" }\n    ],\n    \"metacritic\": \"94\"\n  }\n]\n```\n\n```text\nconst baseURL = \"**http://api.rawg.io/api*\";\n\nCypress.Commands.add(\"landing\", () => {\n  cy.intercept(\"GET\", `${baseURL}/games`, { fixture: \"games.json\" }).as(\n    \"getGames\"\n  );\n});\n```\n\n```text\ndescribe(\"The Home Page\", () => {\n  before(() => {\n    cy.landing();\n  });\n\n  beforeEach(() => {\n    cy.visit(\"/\");\n  });\n\n  it(\"successfully loads\", () => {\n    cy.wait(\"@getGames\");\n  });\n});\n```\n\n```text\n.wait()\n```\n\n```text\nCypressError: Timed out retrying after 5000ms:\n```\n\n```text\ntimed out waiting\n```\n\n```text\nfor the 1st request to the route:\n```\n\n```text\n. No request ever occurred.\n```\n\n```text\ngames.json\n```\n\n```text\n../support/commands.ts\n```\n\n```js\ndescribe(\"The Home Page\", () => {\n  beforeEach(() => {\n\n    // these all work (use only one)\n    cy.intercept('https://api.rawg.io/api/games?key=my-key-goes-here').as('games')\n    cy.intercept('**/api/games?key=my-key-goes-here').as('games')\n    cy.intercept('**/api/games?*').as('games')\n    cy.intercept('**/api/*').as('games')\n    cy.intercept('**//api.rawg.io/api/*').as('games')\n    cy.intercept({pathname: '**/api/*'}).as('games')\n    cy.intercept({pathname: '**/api/games'}).as('games')\n\n    cy.visit(\"/\");\n  });\n\n  it(\"successfully loads\", () => {\n    cy.wait(\"@games\")\n      .its('response.body.count')\n      .should('be.gt', 900000)\n  })\n\n  it(\"successfully loads again\", () => {\n    cy.wait(\"@games\")\n      .its('response.body.count')\n      .should('be.gt', 900000)\n  });\n})\n```\n\n```text\nhttps://api.rawg.io/api\n```\n\n```text\nhttps://api.rawg.io/api\n```\n\n```text\n**\n```\n\n```text\n/\n```\n\n```text\n//\n```\n\n```text\nbefore()\n```\n\n```text\nbeforeEach()\n```\n\n========================================\n\nComments:\n- What do you see in network requests? Does your app even call these api endpoints?\n- @nucleartux, thanks for asking, that's a good clarifying question! In my cypress console, I can see the real request going out, and responding with a status 200. In cypress browser, I can see that all the data has been fetched, and is displayed as intended. Now, there is an API key involved, so I updated my base URL to be more verbose by specifying the key, and the `wait` is still throwing the same error.\n- @nucleartux, wait a minute, I still had the interpolation of `${baseUrl}&#47;games` which was improper formatting after adding in the api key. Fixing the url now has the stub working properly. Thank you much!\n- Thanks @Tucker.Bowman! Yes, you made some important points (thanks for reminding me to fix the protocol!). This implementation is currently working for me. The real issue I was having was fixed by including the api key, which @nucleartux also helped with. Thanks for the help!","metadata":{"transformedAt":"2026-08-18T18:33:46.434Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":229,"estimatedTokens":1566}}527{"id":"stack-75992050","source":"stackoverflow","questionId":75992050,"title":"How can I deploy a react vite application with a public folder to a subfolder on my domain?","tags":["reactjs","deployment","vite","rollupjs"],"text":"Title: How can I deploy a react vite application with a public folder to a subfolder on my domain?\nTags: reactjs, deployment, vite, rollupjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to deploy a react application with vite as the bundler to a subfolder on my domain (i.e. https://example.com/my-app).\n\nMy `vite.config.ts` is as follows:\n\n```\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\nexport default defineConfig({\n plugins: [react()],\n root: \"./\",\n build: {\n outDir: \"dist\",\n },\n base: \"/my-app/\",\n publicDir: \"public\"\n});\n```\n\nI'm deploying this as a static site, so I'm basically copying the `dist` folder from running `vite build` to my digital ocean droplet.\n\nWhen I navigate to https://example.com/my-app, I am able to receive the initial javascript and css files. However, when the javascript runs, I get a 404 error on a file that is in the `public` folder. The `GET` request indicates that it is no longer looking in the subfolder, but looking for the asset directly in the root domain.\n\nSo, `GET` request for javascript looks like this:\n\n`https://example.com/my-app/assets/index-95119c9d.js`\n\n`GET` request based on the served javascript for the static asset (`my-asset`)looks like this:\n\n`https://example.com/my-asset`\n\nHow do I indicate in my `vite.config.ts` that references to the `public` folder assets should *also* be searched for at the subfolder specified as `base` in my config file.\n\n========================================\n\nTop Answer:\nI think you can use `base` in `vite` config:\n\nhttps://github.com/antfu/vitesse/discussions/226\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\nexport default defineConfig({\n  plugins: [react()],\n  root: \"./\",\n  build: {\n    outDir: \"dist\",\n  },\n  base: \"/my-app/\",\n  publicDir: \"public\"\n});\n```\n\n```text\nvite.config.ts\n```\n\n```text\ndist\n```\n\n```text\nvite build\n```\n\n```text\npublic\n```\n\n```text\nGET\n```\n\n```text\nGET\n```\n\n```text\nhttps://example.com/my-app/assets/index-95119c9d.js\n```\n\n```text\nGET\n```\n\n```text\nmy-asset\n```\n\n```text\nhttps://example.com/my-asset\n```\n\n```text\nvite.config.ts\n```\n\n```text\npublic\n```\n\n```text\nbase\n```\n\n```text\n/my-app/my-asset\n```\n\n```text\nvite.config.ts\n```\n\n```text\nbase\n```\n\n```text\nvite\n```\n\n========================================\n\nComments:\n- did u find any solution to this?\n- Been working on this problem forever. Thinking the solution/problem was within nginx. create-react-app has a built in solution in which you modify homepage:'*' before build.\n- crazy that there is no easier way to do this -.-\n- vite-plugin-ssr.com/base-url#base","metadata":{"transformedAt":"2026-08-18T18:33:46.434Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":138,"estimatedTokens":666}}528{"id":"stack-74938778","source":"stackoverflow","questionId":74938778,"title":"How to use the WebSpeech API in svelte","tags":["svelte","vite","webspeech-api"],"text":"Title: How to use the WebSpeech API in svelte\nTags: svelte, vite, webspeech-api\nSource: Stack Overflow\n\nQuestion:\nI am working on a frontend project which involves the use of the google WebSpeech API. When I try to declare the speech recognition, I get errors saying speech recognition is not defined or window is not defined. The project fails to compile. How do I fix this?\n\nThe code inside my tag is below;\n\n```\nconst SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;\nconst recognition = new SpeechRecognition();\n```\n\nThis is the error\n\nwindow is not defined\nReferenceError: window is not defined\n\nI am using vite-plugin-svelte for compiling & Chrome browser for testing.\n\n========================================\n\nCode:\n```text\nconst SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;\nconst recognition = new SpeechRecognition();\n```\n\n```html\n<script>\n  import { onMount } from 'svelte';\n\n  let recognition;\n\n  onMount(() => {\n    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;\n    recognition = new SpeechRecognition();\n  });\n</script>\n```\n\n```text\nwindow\n```\n\n```text\nrecognition\n```\n\n```text\nonMount\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.434Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":53,"estimatedTokens":302}}529{"id":"stack-75591817","source":"stackoverflow","questionId":75591817,"title":"encodeURI (or encodeURIComponent) returns different encodings in different parts of my code","tags":["javascript","reactjs","vite"],"text":"Title: encodeURI (or encodeURIComponent) returns different encodings in different parts of my code\nTags: javascript, reactjs, vite\nSource: Stack Overflow\n\nQuestion:\n(disclaimer: this is the first time I post a question on SO, so I apologize in advance if I did anything wrong)\n\nI have an URI pointing to an image with this structure:\n\n(stuff...)/acryagl_violencia física/(more stuff...).jpg\n\nI tried to encode it but I get two different results in two different script files and I don't see the reason why.\n\n```\n// Script one:\n`stuff.../${ encodeURIComponent(element.article_id_thumbnail) }/...stuff`\n// I get 'acryagl_violencia%20fi%CC%81sica', which does NOT work\n\n// Script two (and Chrome console):\n`stuff.../${ encodeURIComponent(element.id) }/...stuff`\n// I get 'acryagl_violencia%20f%C3%ADsica', which DOES work\n\n// Notice the difference is on the 'í' from 'física'\n```\n\nAccording to https://www.url-encode-decode.com/, both strings should decode to the same, which is weird to me. I am totally lost on this one.\n\nIn case it helps, this is a React + Vite project, although I don't see how this could be related with the bundler. I am also testing everything on Chrome.\n\nI fixed it by manually encoding the `í` character, but there should be a better fix.\nHas anyone faced this problem before?\n\n========================================\n\nTop Answer:\n`String.prototype.normalize` to the rescue:\n\n`encodeURIComponent(element.article_id_thumbnail.normalize())`\n\nand\n\n`encodeURIComponent(element.id.normalize())`\n\nshould give you the result you are looking for.\n\n\r\n\r\n\n```\nconst a = encodeURIComponent(decodeURIComponent(\"acryagl_violencia%20fi%CC%81sica\").normalize())\nconst b = encodeURIComponent(decodeURIComponent(\"acryagl_violencia%20f%C3%ADsica\").normalize())\nconsole.log(a === b) // true\n```\n\n========================================\n\nCode:\n```text\n// Script one:\n`stuff.../${ encodeURIComponent(element.article_id_thumbnail) }/...stuff`\n// I get 'acryagl_violencia%20fi%CC%81sica', which does NOT work\n\n// Script two (and Chrome console):\n`stuff.../${ encodeURIComponent(element.id) }/...stuff`\n// I get 'acryagl_violencia%20f%C3%ADsica', which DOES work\n\n// Notice the difference is on the 'í' from 'física'\n```\n\n```text\ní\n```\n\n```js\nconsole.log(\n decodeURI('%C3%AD').normalize('NFKD')\n ===\n decodeURI('i%CC%81')\n); // true\n// both are two (same) codepoints;\n// first was decomposed from single codepoint\n\nconsole.log(\n decodeURI('%C3%AD')\n ===\n decodeURI('i%CC%81').normalize('NFKC')\n); // true\n// both are same single codepoint;\n// second was composed into it from two codepoints\n```\n\n```text\nnormalize\n```\n\n```js\nconst a = encodeURIComponent(decodeURIComponent(\"acryagl_violencia%20fi%CC%81sica\").normalize())\nconst b = encodeURIComponent(decodeURIComponent(\"acryagl_violencia%20f%C3%ADsica\").normalize())\nconsole.log(a === b) // true\n```\n\n```text\nString.prototype.normalize\n```\n\n```text\nencodeURIComponent(element.article_id_thumbnail.normalize())\n```\n\n```text\nencodeURIComponent(element.id.normalize())\n```\n\n========================================\n\nComments:\n- Are you sure the two values are the same? Because when i do `encodeURIComponent(\"acryagl_violencia física\")` in the Chrome console I get the same as the first script.\n- what is the value of `element.article_id_thumbnail` and `element.id` ?\n- *\"both strings should decode to the same\"* - they might *look* the same when rendered, but they aren't the same. In the second case, you got `C3 AD`, which is unicode code point `U+00ED`, an *actual* `&#237;` character. In the first case, there is a *normal* `i`, followed by `CC 81`, code point `0301`, which is the COMBINING ACUTE ACCENT character. Your *input data* was different here, and so you get a different result as well.\n- this is not a matter of function the problem here is that the source string is different from the start\n- @TachibanaShin \"different\"/\"same\" is not a concrete concept in unicode when looking at byte sequences.\n- @spender clearly 1 byte is different from 2 bytes. If you see the two strings as the same, it's just that your font automatically merges them. in standard fonts like japanese i see 2 completely different strings\n- @TachibanaShin Indeed, but, in their normalized forms, the strings become the same.\n- Thanks a lot, this worked like a charm :) Accepting the other answer simply because it helped me understand the reason why my code was failing\n- Great! This worked! I accept this one since both answers work but this one helped me understand better the source of the problem. Thanks a lot! :D\n- Side note: It's weird though that they are inconsistent since they are connected by a foreign key in the database, so MySQL thinks they are similar enough to pass the check...\n- Hm, that sound like an interesting MySQL question; some implicit normalization during lookup sounds plausible, yet matching differently normalized Unicode sequences in foreign keys feels … strange. But would probably make sense as well.","metadata":{"transformedAt":"2026-08-18T18:33:46.434Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":127,"estimatedTokens":1244}}530{"id":"stack-69348903","source":"stackoverflow","questionId":69348903,"title":"How to create Subdomains in Development environment with VIteJS?","tags":["subdomain","vite"],"text":"Title: How to create Subdomains in Development environment with VIteJS?\nTags: subdomain, vite\nSource: Stack Overflow\n\nQuestion:\nI have the following subdomains:\n\n- admin.myapp.dev\n\n- buyers.myapp.dev\n\n- sellers.myapp.dev\n\nI tried running several servers on different ports but those didn't work.\n\nWhat is the correct way to config the ViteJS to resolve those subdomains?\n\n========================================\n\nCode:\n```text\nserver: {\n    proxy: {\n      // forward localhost:3000/admin -> to -> admin.myapp.dev\n      '/admin': {\n        target: 'admin.myapp.dev/'\n      },\n\n      '/buyers': {\n        target: 'buyers.myapp.dev'\n      },\n      \n      '/sellers': {\n        target: 'sellers.myapp.dev'\n      }      \n    }\n  }\n```\n\n```text\nserver.proxy\n```\n\n========================================\n\nComments:\n- I need the vise-versa, from subdomains index like example1.test to myapp/ something\n- @ИгорТашевски you should set a reverse-proxy in front of your app to achieve that and avoid headhaches.","metadata":{"transformedAt":"2026-08-18T18:33:46.434Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":48,"estimatedTokens":251}}531{"id":"stack-73068610","source":"stackoverflow","questionId":73068610,"title":"VUE: SFC - use markdown in tag - vite throwing eror","tags":["vuejs2","vite"],"text":"Title: VUE: SFC - use markdown in tag - vite throwing eror\nTags: vuejs2, vite\nSource: Stack Overflow\n\nQuestion:\nSo I inherited an old (Vue 2) app that uses Styleguidist for creating style guide and documenting components...\n\nIt was running extra slow so my first task was to upgrade to using vite instead of webpack. Almost there... fixed almost all the issue, the one is outstanding though... this app uses this format of *.vue components\n\n```\n...\n...\n...\n\n Example of usage\n ```jsx\n ...\n\n```\n\nwhere content inside is markdown, so one can write nicer documentation with code example\n\nNow, vite is complaining that I am trying to use jsx (where I am not)...\n\nthis is the error\n\n3:36:36 PM [vite] Internal server error: Failed to parse source for\nimport analysis because the content contains invalid JS syntax. If you\nare using JSX, make sure to name the file with the .jsx or .tsx\nextension. Plugin: vite:import-analysis\n\nSo what am I to do? How do I tell VITE to ignore that part?\n\n========================================\n\nCode:\n```text\n<template>...</template>\n<script>...</script>\n<style>...</style>\n<docs>\n  Example of usage\n  ```jsx\n  <MyComponent>...</MyComponent>\n</docs>\n```\n\n```js\nconst vueDocsPlugin = {\n    name: 'vue-docs',\n    transform(code, id) {\n        if (!/vue&type=docs/.test(id))\n            return;\n        return `export default ''`;\n    }\n};\n```\n\n```js\nexport default defineConfig({\n    plugins: [\n        // vue() will be here...\n        vueDocsPlugin,\n    ],\n});\n```\n\n```text\n<docs>\n```\n\n```text\nvite.config.js\n```\n\n```text\nplugins\n```\n\n========================================\n\nComments:\n- seems to work! thank you. this really should be documented better in the vite docs, especially with vitepress on the rise.","metadata":{"transformedAt":"2026-08-18T18:33:46.434Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":83,"estimatedTokens":435}}532{"id":"stack-74769990","source":"stackoverflow","questionId":74769990,"title":"How to override the rollup output.format setting in vite?","tags":["vite","rollupjs"],"text":"Title: How to override the rollup output.format setting in vite?\nTags: vite, rollupjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to solve the Vite build error I get:\n\nRollupError: Invalid value \"iife\" for option \"output.format\" - UMD and IIFE output formats are not supported for code-splitting builds.\n\nThe file name reported with this error points to\nmy web worker code, so I assumed that this setting belongs to the `worker` section in vite.config.ts:\n\n```\nimport { defineConfig } from \"vite\";\nimport preact from \"@preact/preset-vite\";\nimport basicSsl from \"@vitejs/plugin-basic-ssl\";\n\nimport { NodeGlobalsPolyfillPlugin } from \"@esbuild-plugins/node-globals-polyfill\";\nimport { NodeModulesPolyfillPlugin } from \"@esbuild-plugins/node-modules-polyfill\";\nimport rollupNodePolyFill from \"rollup-plugin-node-polyfills\";\n\nexport default defineConfig({\n plugins: [\n preact(),\n basicSsl(),\n ],\n server: {\n port: 3001,\n https: true,\n },\n optimizeDeps: {\n esbuildOptions: {\n // Node.js global to browser globalThis\n define: {\n global: \"globalThis\",\n },\n // Enable esbuild polyfill plugins\n plugins: [\n NodeGlobalsPolyfillPlugin({\n process: true,\n buffer: true,\n }),\n NodeModulesPolyfillPlugin(),\n ],\n },\n },\n worker: {\n rollupOptions: {\n output: {\n format: \"esm\",\n },\n },\n },\n build: {\n rollupOptions: {\n plugins: [\n // Enable rollup polyfills plugin\n // used during production bundling\n rollupNodePolyFill(),\n ],\n output: {\n format: \"esm\",\n },\n },\n },\n});\n```\n\nAdditionally, I set the output format in the build rollup options. However, neither of the two settings are applied and I still get the said error.\n\nWhat is the correct way to change the rollup output format setting in Vite?\n\n========================================\n\nCode:\n```js\nimport { defineConfig } from \"vite\";\nimport preact from \"@preact/preset-vite\";\nimport basicSsl from \"@vitejs/plugin-basic-ssl\";\n\nimport { NodeGlobalsPolyfillPlugin } from \"@esbuild-plugins/node-globals-polyfill\";\nimport { NodeModulesPolyfillPlugin } from \"@esbuild-plugins/node-modules-polyfill\";\nimport rollupNodePolyFill from \"rollup-plugin-node-polyfills\";\n\nexport default defineConfig({\n    plugins: [\n        preact(),\n        basicSsl(),\n    ],\n    server: {\n        port: 3001,\n        https: true,\n    },\n    optimizeDeps: {\n        esbuildOptions: {\n            // Node.js global to browser globalThis\n            define: {\n                global: \"globalThis\",\n            },\n            // Enable esbuild polyfill plugins\n            plugins: [\n                NodeGlobalsPolyfillPlugin({\n                    process: true,\n                    buffer: true,\n                }),\n                NodeModulesPolyfillPlugin(),\n            ],\n        },\n    },\n    worker: {\n        rollupOptions: {\n            output: {\n                format: \"esm\",\n            },\n        },\n    },\n    build: {\n        rollupOptions: {\n            plugins: [\n                // Enable rollup polyfills plugin\n                // used during production bundling\n                rollupNodePolyFill(),\n            ],\n            output: {\n                format: \"esm\",\n            },\n        },\n    },\n});\n```\n\n```text\nworker\n```\n\n```js\nimport { defineConfig } from \"vite\";\nimport preact from \"@preact/preset-vite\";\nimport basicSsl from \"@vitejs/plugin-basic-ssl\";\n\nimport { NodeGlobalsPolyfillPlugin } from \"@esbuild-plugins/node-globals-polyfill\";\nimport { NodeModulesPolyfillPlugin } from \"@esbuild-plugins/node-modules-polyfill\";\nimport rollupNodePolyFill from \"rollup-plugin-node-polyfills\";\n\nexport default defineConfig({\n    plugins: [\n        preact(),\n        basicSsl(),\n    ],\n    server: {\n        port: 3001,\n        https: true,\n    },\n    optimizeDeps: {\n        esbuildOptions: {\n            // Node.js global to browser globalThis\n            define: {\n                global: \"globalThis\",\n            },\n            // Enable esbuild polyfill plugins\n            plugins: [\n                NodeGlobalsPolyfillPlugin({\n                    process: true,\n                    buffer: true,\n                }),\n                NodeModulesPolyfillPlugin(),\n            ],\n        },\n    },\n    worker: {\n        format: \"es\",\n    },\n    build: {\n        rollupOptions: {\n            plugins: [\n                // Enable rollup polyfills plugin\n                // used during production bundling\n                rollupNodePolyFill(),\n            ],\n            output: {\n                format: \"esm\",\n            },\n        },\n    },\n});\n```\n\n========================================\n\nComments:\n- Gotta love how this just randomly starts happening...","metadata":{"transformedAt":"2026-08-18T18:33:46.434Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":191,"estimatedTokens":1149}}533{"id":"stack-72035203","source":"stackoverflow","questionId":72035203,"title":"TypeError: Cannot read properties of undefined (reading 'call') on build but not dev","tags":["npm","web3js","vite"],"text":"Title: TypeError: Cannot read properties of undefined (reading 'call') on build but not dev\nTags: npm, web3js, vite\nSource: Stack Overflow\n\nQuestion:\nI am running a `vite.js` app with web3 installed.\nWhen I run the app in dev mode, all works fine but when I run it in production mode (build) it fails with:\n`\"TypeError: Cannot read properties of undefined (reading 'call')\"`.\n\nI can confirm that the error comes from the contract method generated from my ABI:\ncontract.methods.isOwner(sender)`.call`({from: sender}, function (err, res)\n\nIf I comment this line out I wont get the error.\n\nYou can reproduce the error by using my test repo:\ndownload my test repo:\nhttps://github.com/nybroe/web3_vite_call_of_undefined/tree/main\n\n the readme with repo steps:\n\n**setup:**\n\n- download the repro\n\n- navigate to \"app\"\n\n- npm install\n\n**dev test (which works)**\n\n- npm run dev\n\n- check the console - no errors\n\n**build test (which breaks)**\n\n- npm run build\n\n- npm run preview\n\n- check the console - you will see the following errors: \"TypeError: Cannot read properties of undefined (reading 'call')\"\n\n========================================\n\nCode:\n```text\nvite.js\n```\n\n```text\n\"TypeError: Cannot read properties of undefined (reading 'call')\"\n```\n\n```text\n.call\n```\n\n```js\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  ⋮\n  resolve: {\n    alias: {\n      web3: 'web3/dist/web3.min.js',\n    },\n\n    // or\n    alias: [\n      {\n        find: 'web3',\n        replacement: 'web3/dist/web3.min.js',\n      },\n    ],\n  },\n})\n```\n\n```text\nvite.config.js\n```\n\n```text\nweb3\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.434Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":85,"estimatedTokens":395}}534{"id":"stack-74369103","source":"stackoverflow","questionId":74369103,"title":"Include 3rd party scss in component library using Vue 3 + Vite","tags":["vuejs3","vite"],"text":"Title: Include 3rd party scss in component library using Vue 3 + Vite\nTags: vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI'm currently building an external component library using Vue 3 + Vite. I'm using 3rd party component and style, but the style doesn't apply when I used it in my main project. It used to work before when I use Vue 2 + Vue CLI.\n\nMy component library project looks like this:\n\nhttps://i.sstatic.net/8G2gS.png\n\nand here's the detail for my code\n\n### vite.config.js\n\n```\nimport { resolve } from 'path'\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [vue()],\n build: {\n lib: {\n entry: resolve(__dirname, 'src/main.js'),\n name: 'custom-lib',\n fileName: 'custom-lib',\n },\n rollupOptions: {\n external: ['vue'],\n output: {\n globals: {\n vue: 'Vue'\n }\n }\n }\n }\n})\n```\n\n### package.json\n\n```\n{\n \"name\": \"custom-lib\",\n \"private\": true,\n \"version\": \"0.0.0\",\n \"type\": \"module\",\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/custom-lib.umd.cjs\",\n \"module\": \"./dist/custom-lib.js\",\n \"exports\": {\n \".\": {\n \"import\": \"./dist/custom-lib.js\",\n \"require\": \"./dist/custom-lib.umd.cjs\"\n }\n },\n \"scripts\": {\n \"build\": \"vite build\"\n },\n \"dependencies\": {\n \"moment\": \"^2.29.4\",\n \"vue\": \"^3.2.41\",\n \"vue-datepicker-next\": \"^1.0.2\"\n },\n \"devDependencies\": {\n \"@vitejs/plugin-vue\": \"^3.2.0\",\n \"sass\": \"^1.56.0\",\n \"sass-loader\": \"^13.1.0\",\n \"vite\": \"^3.2.3\"\n }\n}\n```\n\n### src/components/Datepicker.vue\n\n```\n\n \n\nimport DatePicker from 'vue-datepicker-next';\nimport moment from 'moment';\n\nexport default {\n name: 'Datepicker',\n components: {\n DatePicker\n },\n props: {\n id: {\n type: String,\n required: true\n },\n modelValue: null,\n dateFormat: String,\n disabled: Boolean\n },\n computed: {\n inputVal: {\n get() {\n if (this.modelValue) {\n return moment(this.modelValue).toDate();\n }\n return null;\n },\n set(val) {\n let strVal = undefined;\n let m = moment(val);\n if (m.isValid()) {\n strVal = m.format(\"YYYY-MM-DDTHH:mm:ss\");\n }\n\n this.$emit('update:modelValue', strVal);\n }\n }\n }\n};\n\n@import \"vue-datepicker-next/scss/index.scss\";\n\n```\n\n### src/main.js\n\n```\nimport Datepicker from './components/Datepicker.vue';\n\nexport {\n Datepicker\n}\n```\n\nMy Datepicker style not working in my main project, is there something missing from the config?\n\n========================================\n\nCode:\n```js\nimport { resolve } from 'path'\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue()],\n  build: {\n    lib: {\n      entry: resolve(__dirname, 'src/main.js'),\n      name: 'custom-lib',\n      fileName: 'custom-lib',\n    },\n    rollupOptions: {\n      external: ['vue'],\n      output: {\n        globals: {\n          vue: 'Vue'\n        }\n      }\n    }\n  }\n})\n```\n\n```json\n{\n  \"name\": \"custom-lib\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"files\": [\n    \"dist\"\n  ],\n  \"main\": \"./dist/custom-lib.umd.cjs\",\n  \"module\": \"./dist/custom-lib.js\",\n  \"exports\": {\n    \".\": {\n      \"import\": \"./dist/custom-lib.js\",\n      \"require\": \"./dist/custom-lib.umd.cjs\"\n    }\n  },\n  \"scripts\": {\n    \"build\": \"vite build\"\n  },\n  \"dependencies\": {\n    \"moment\": \"^2.29.4\",\n    \"vue\": \"^3.2.41\",\n    \"vue-datepicker-next\": \"^1.0.2\"\n  },\n  \"devDependencies\": {\n    \"@vitejs/plugin-vue\": \"^3.2.0\",\n    \"sass\": \"^1.56.0\",\n    \"sass-loader\": \"^13.1.0\",\n    \"vite\": \"^3.2.3\"\n  }\n}\n```\n\n```html\n<template>\n  <DatePicker\n    :id=\"id\"\n    v-model:value=\"inputVal\"\n    value-type=\"date\"\n    type=\"date\"\n    :format=\"dateFormat\"\n    :placeholder=\"dateFormat\"\n    :disabled=\"disabled\"\n    input-class=\"mx-input\"\n  />\n</template>\n\n<script>\nimport DatePicker from 'vue-datepicker-next';\nimport moment from 'moment';\n\nexport default {\n  name: 'Datepicker',\n  components: {\n    DatePicker\n  },\n  props: {\n    id: {\n      type: String,\n      required: true\n    },\n    modelValue: null,\n    dateFormat: String,\n    disabled: Boolean\n  },\n  computed: {\n    inputVal: {\n      get() {\n        if (this.modelValue) {\n          return moment(this.modelValue).toDate();\n        }\n        return null;\n      },\n      set(val) {\n        let strVal = undefined;\n        let m = moment(val);\n        if (m.isValid()) {\n          strVal = m.format(\"YYYY-MM-DDTHH:mm:ss\");\n        }\n\n        this.$emit('update:modelValue', strVal);\n      }\n    }\n  }\n};\n</script>\n\n<style lang=\"scss\">\n@import \"vue-datepicker-next/scss/index.scss\";\n</style>\n```\n\n```js\nimport Datepicker from './components/Datepicker.vue';\n\nexport {\n    Datepicker\n}\n```\n\n```js\nimport { resolve } from 'path'\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js' // 👈\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    vue(),\n    cssInjectedByJsPlugin() // 👈\n  ],\n  build: {\n    lib: {\n      entry: resolve(__dirname, 'src/main.js'),\n      name: 'custom-lib',\n      fileName: 'custom-lib',\n    },\n    rollupOptions: {\n      external: ['vue'],\n      output: {\n        globals: {\n          vue: 'Vue'\n        }\n      }\n    }\n  }\n})\n```\n\n```text\nnpm i vite-plugin-css-injected-by-js --save\n```\n\n```text\ntest\n```\n\n```text\ncd test\n```\n\n```text\nyarn dev\n```\n\n========================================\n\nComments:\n- You mean the style does apply to your component. But when you use it as a library on another project, the style does not apply, right?\n- Usually, you need to import your component style into your main project to make the style work.\n- Use the following plugin - vite-plugin-css-injected-by-js - if you can't get it working, I will make you an example in a answer.\n- @James you might try this answer\n- @Duannx yes, when I used it as components in my main project. the style working, but when I put the components in my library and used components from there. the style not working. I already tried to import the style in my main project, the style not applying too. I'm importing like this: `@import \"custom-lib&#47;dist&#47;style.css\"`\n- @flydev where do you put this `cssInjectedByJsPlugin` ?\n- @James Can you reproduce your problem on stackblitz.com?\n- You're a life-saver. I've been drowning in config for the past 2 days. Thank you for this\n- Hi i am also facing this issue, tried to import node modules scss of 3rd party library but its not working. Tried above solution but no use. Can you please help.","metadata":{"transformedAt":"2026-08-18T18:33:46.434Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":325,"estimatedTokens":1607}}535{"id":"stack-66612914","source":"stackoverflow","questionId":66612914,"title":"vue3, vite and vue-router@next, cannot resolve component router-view","tags":["vue.js","vuejs3","vite","vue-router4"],"text":"Title: vue3, vite and vue-router@next, cannot resolve component router-view\nTags: vue.js, vuejs3, vite, vue-router4\nSource: Stack Overflow\n\nQuestion:\nI created a project using Vite and added vue-router@next. I am using the router inside of the main.js as I've browsed around and seemed like this was the problem, however it does not fix the issue I am having.\n\n```\n// package.json\n{\n \"name\": \"rng-alpha\",\n \"version\": \"0.0.0\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"serve\": \"vite preview\"\n },\n \"dependencies\": {\n \"vue\": \"^3.0.5\",\n \"vue-router\": \"^4.0.5\"\n },\n \"devDependencies\": {\n \"@vitejs/plugin-vue\": \"^1.1.5\",\n \"@vue/compiler-sfc\": \"^3.0.7\",\n \"vite\": \"^2.0.5\"\n }\n}\n\n// main.js\nimport { createApp } from 'vue';\nimport App from './App.vue';\nimport router from './router/router';\n\nconst app = createApp(App);\napp.use(router);\napp.mount('#app');\n\n// router.js\nimport {\n createWebHistory,\n createRouter\n} from 'vue-router'\n\nimport Home from '../components/Home.vue'\n\nconst routes = [{\n path: \"/\",\n name: \"Home\",\n component: Home\n}]\n\nconst router = createRouter[{\n history: createWebHistory,\n routes,\n}]\n\nexport default router\n\n// App.vue\n\n \n hi\n \n \n\n```\n\nThe warnings I am getting are the following:\nhttps://i.sstatic.net/kaMBB.png\n\nHow can I make the router-view work? Since I am not able to utilize it right now.\n\n========================================\n\nCode:\n```text\n// package.json\n{\n  \"name\": \"rng-alpha\",\n  \"version\": \"0.0.0\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"serve\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"vue\": \"^3.0.5\",\n    \"vue-router\": \"^4.0.5\"\n  },\n  \"devDependencies\": {\n    \"@vitejs/plugin-vue\": \"^1.1.5\",\n    \"@vue/compiler-sfc\": \"^3.0.7\",\n    \"vite\": \"^2.0.5\"\n  }\n}\n\n// main.js\nimport { createApp } from 'vue';\nimport App from './App.vue';\nimport router from './router/router';\n\nconst app = createApp(App);\napp.use(router);\napp.mount('#app');\n\n// router.js\nimport {\n  createWebHistory,\n  createRouter\n} from 'vue-router'\n\nimport Home from '../components/Home.vue'\n\nconst routes = [{\n  path: \"/\",\n  name: \"Home\",\n  component: Home\n}]\n\nconst router = createRouter[{\n  history: createWebHistory,\n  routes,\n}]\n\nexport default router\n\n// App.vue\n<template>\n  <div>\n    <div>hi</div>\n    <router-view />\n  </div>\n</template>\n```\n\n```text\nconst router = createRouter({\n  history: createWebHistory,\n  routes,\n})\n```\n\n```text\ncreateRouter\n```\n\n```text\n()\n```\n\n```text\n[]\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.434Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":153,"estimatedTokens":609}}536{"id":"stack-79751936","source":"stackoverflow","questionId":79751936,"title":"Chakra UI Card and CardBody won't render in React App","tags":["reactjs","vite","chakra-ui","card"],"text":"Title: Chakra UI Card and CardBody won't render in React App\nTags: reactjs, vite, chakra-ui, card\nSource: Stack Overflow\n\nQuestion:\nMy apologies if this question has been asked, but I can't find the issue I'm having.\nI'm using React Vite and Chakra-UI. Everything works fine, until I use Card.\n\nThis works fine (Item and Flex also work):\n\n```\nimport React from 'react';\nimport {\n Card,\n CardBody\n} from '@chakra-ui/react';\n\nexport const LocationItemCard = () => {\n\n return (\n <>\n test\n\n \n \n );\n\n}\n```\n\nHowever, as soon as I add Card and CardBody, nothing works anymore:\n\n```\nimport React from 'react';\nimport {\n Card,\n CardBody\n} from '@chakra-ui/react';\n\nexport const LocationItemCard = () => {\n return (\n <>\n \n \n test\n\n \n \n \n );\n}\n```\n\nThis is my root app, which won't work without adding the value defaultSystem:\n\n```\nimport React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { App } from './App';\nimport { ChakraProvider, defaultSystem } from '@chakra-ui/react'\n\nReactDOM.createRoot(document.getElementById('root')).render(\n \n \n \n \n ,\n)\n```\n\nWhen I display the images without Card, they do show up and I can style them. It's been a year since I worked with React/Vite and Chakra. I had to upgrade to other versions and now I'm having all these issues. Perhaps the different versions are collapsing somehow.\n\nI have already reinstalled Chakra, I've tried downgrading to React 18. Nothing helps. Should I just give up Card and use Box or something else to style them? Or is there a stupid mistake I'm missing?\n\nThis is the browser console error:\n\n*Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.*\n\n========================================\n\nCode:\n```text\nimport React from 'react';\nimport {\n    Card,\n    CardBody\n} from '@chakra-ui/react';\n\nexport const LocationItemCard = () => {\n\n    return (\n        <>\n            <p>test</p>\n \n        </>\n    );\n\n}\n```\n\n```text\nimport React from 'react';\nimport {\n    Card,\n    CardBody\n} from '@chakra-ui/react';\n\nexport const LocationItemCard = () => {\n    return (\n        <>\n          <Card h=\"xl\" w=\"100%\" bg=\"blue.300\" >\n            <CardBody>\n              <p>test</p>\n            </CardBody>\n          </Card>\n        </>\n    );\n}\n```\n\n```text\nimport React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { App } from './App';\nimport { ChakraProvider, defaultSystem } from '@chakra-ui/react'\n\nReactDOM.createRoot(document.getElementById('root')).render(\n  <React.StrictMode>\n      <ChakraProvider value={ defaultSystem }>\n          <App />\n      </ChakraProvider>\n  </React.StrictMode>,\n)\n```\n\n```text\nimport { Button, Card } from '@chakra-ui/react';\n\nexport const App = () => {\n  return (\n    <Card.Root h=\"xl\" w=\"100%\" bg=\"blue.300\">\n      <Card.Body gap=\"2\">\n        <Card.Title mt=\"2\">Title</Card.Title>\n        <Card.Description>\n          <p>test</p>\n        </Card.Description>\n      </Card.Body>\n      <Card.Footer justifyContent=\"flex-end\">\n        <Button variant=\"outline\">View</Button>\n        <Button>Join</Button>\n      </Card.Footer>\n    </Card.Root>\n  );\n};\n```\n\n========================================\n\nComments:\n- Thank you very much for taking the time to explain this. I should have read the instructions on the website instead of trying to work the way I'm used to. I didn't realize so much has changed. I learnt a valuable lesson from this.\n- @Sahdia Don't mention it. Glad I could help.","metadata":{"transformedAt":"2026-08-18T18:33:46.435Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":161,"estimatedTokens":873}}537{"id":"stack-77570491","source":"stackoverflow","questionId":77570491,"title":"Issues with HMR in Vite React App with Node.js and Shopify Integration","tags":["vite","shopify-app","hmr"],"text":"Title: Issues with HMR in Vite React App with Node.js and Shopify Integration\nTags: vite, shopify-app, hmr\nSource: Stack Overflow\n\nQuestion:\nI'm currently configuring a Shopify app using React (with Vite) and Node.js. However, I've encountered an issue with Hot Module Replacement (HMR).\n\nMy vite.config.js file is as follows:\n\n```\nimport path, { dirname } from 'node:path';\n\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig } from 'vite';\nimport tsconfigPaths from 'vite-tsconfig-paths';\nimport sassDts from 'vite-plugin-sass-dts';\nimport react from '@vitejs/plugin-react';\n\nconst proxyOptions = {\n target: `http://127.0.0.1:${process.env.WEB_PORT}`,\n changeOrigin: false,\n secure: true,\n ws: false,\n};\n\nconst host = process.env.HOST ? process.env.HOST.replace(/https?:\\/\\//, '') : 'localhost';\n\nlet hmrConfig;\n\nif (host === 'localhost') {\n hmrConfig = {\n protocol: 'ws',\n host: 'localhost',\n port: 64999,\n clientPort: 64999,\n };\n} else {\n hmrConfig = {\n protocol: 'wss',\n host: host,\n port: process.env.FRONTEND_PORT,\n clientPort: 443,\n };\n}\n\nexport default defineConfig({\n root: dirname(fileURLToPath(import.meta.url)),\n plugins: [react(), tsconfigPaths(), sassDts()],\n\n resolve: { preserveSymlinks: true, alias: { '@/styles': path.join(__dirname, 'src', 'styles') } },\n\n server: {\n host: 'localhost',\n port: process.env.FRONTEND_PORT,\n hmr: hmrConfig,\n proxy: {\n '^/(\\\\?.*)?$': proxyOptions,\n '^/api(/|(\\\\?.*)?$)': proxyOptions,\n },\n },\n});\n```\n\nThe problem arises when I add `proxyOptions` to the server configurations. Once added, HMR doesn't function as expected. I can only see changes in my React components after manually refreshing the web page.\n\nConversely, when I remove the `proxyOptions` from the server configurations, HMR works correctly.\n\nI have verified that `process.env.WEB_PORT` corresponds to the port where my server is listening.\n\nAny insights or solutions to fix the HMR issue while using `proxyOptions` would be greatly appreciated.\n\n`@shopify/app\": \"3.46.5`,\n\n========================================\n\nCode:\n```js\nimport path, { dirname } from 'node:path';\n\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig } from 'vite';\nimport tsconfigPaths from 'vite-tsconfig-paths';\nimport sassDts from 'vite-plugin-sass-dts';\nimport react from '@vitejs/plugin-react';\n\nconst proxyOptions = {\n    target: `http://127.0.0.1:${process.env.WEB_PORT}`,\n    changeOrigin: false,\n    secure: true,\n    ws: false,\n};\n\nconst host = process.env.HOST ? process.env.HOST.replace(/https?:\\/\\//, '') : 'localhost';\n\nlet hmrConfig;\n\nif (host === 'localhost') {\n    hmrConfig = {\n        protocol: 'ws',\n        host: 'localhost',\n        port: 64999,\n        clientPort: 64999,\n    };\n} else {\n    hmrConfig = {\n        protocol: 'wss',\n        host: host,\n        port: process.env.FRONTEND_PORT,\n        clientPort: 443,\n    };\n}\n\nexport default defineConfig({\n    root: dirname(fileURLToPath(import.meta.url)),\n    plugins: [react(), tsconfigPaths(), sassDts()],\n\n    resolve: { preserveSymlinks: true, alias: { '@/styles': path.join(__dirname, 'src', 'styles') } },\n\n    server: {\n        host: 'localhost',\n        port: process.env.FRONTEND_PORT,\n        hmr: hmrConfig,\n        proxy: {\n            '^/(\\\\?.*)?$': proxyOptions,\n            '^/api(/|(\\\\?.*)?$)': proxyOptions,\n        },\n    },\n});\n```\n\n```text\nproxyOptions\n```\n\n```text\nproxyOptions\n```\n\n```text\nprocess.env.WEB_PORT\n```\n\n```text\nproxyOptions\n```\n\n```text\n@shopify/app\": \"3.46.5\n```\n\n```text\nproxyOptions.ws\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.435Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":153,"estimatedTokens":880}}538{"id":"stack-78337258","source":"stackoverflow","questionId":78337258,"title":"Where do I set NODE_OPTIONS when using Vite and ReactJS?","tags":["reactjs","node.js","vite","package.json"],"text":"Title: Where do I set NODE_OPTIONS when using Vite and ReactJS?\nTags: reactjs, node.js, vite, package.json\nSource: Stack Overflow\n\nQuestion:\nI need to increase the Maximum Http Header Size for some of the API calls on my website. When I run the function in question, I get this error:\n\n```\nServer responded with status code 431. See https://vitejs.dev/guide/troubleshooting.html#_431-request-header-fields-too-large.\n```\n\nHowever, if I simply reduce the length of the input, it works perfectly fine.\nIt's not a cookies issue, I'm just sending back a very large string(think a long article), but when it reaches a certain size, it no longer allows the user to submit it. So I need to use the option listed in the link the terminal provided(https://vitejs.dev/guide/troubleshooting.html#_431-request-header-fields-too-large) to increase the max-http-header-size. However, I don't know where to do this.\n\nIn the package.json, there is a scripts section containing this:\n\n```\n\"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"lint\": \"eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0\",\n \"preview\": \"vite preview\"\n },\n```\n\nThe startup script is \"npm run dev\". So I tried to simply modify the \"dev\" startup script:\n\n```\n\"scripts\": {\n \"dev\": \"vite NODE_OPTIONS=--max_http_header_size=128000\",\n \"build\": \"vite build\",\n \"lint\": \"eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0\",\n \"preview\": \"vite preview\"\n },\n```\n\nThis doesn't work, and the website simply doesn't work at all. So I tried to modify the startup script from:\n\n```\nnpm run dev\n```\n\nTo:\n\n```\nnpu NODE_OPTIONS=--max_http_header_size=128000 run dev\n```\n\nBut that also didn't work. I just need to know how to set the NODE_OPTION for max_http_header_size when using vite, since \"vite\" replaces \"node\" as the binary to run. For regular React-JS websites, the startup script is \"node\", and you can simply put the NODE_OPTIONS after that. But since we're using Vite, the startup script isn't \"node\" and adding the NODE_OPTIONS after \"vite\" doesn't work.\n\n========================================\n\nCode:\n```text\nServer responded with status code 431. See https://vitejs.dev/guide/troubleshooting.html#_431-request-header-fields-too-large.\n```\n\n```text\n\"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"lint\": \"eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0\",\n    \"preview\": \"vite preview\"\n  },\n```\n\n```text\n\"scripts\": {\n    \"dev\": \"vite NODE_OPTIONS=--max_http_header_size=128000\",\n    \"build\": \"vite build\",\n    \"lint\": \"eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0\",\n    \"preview\": \"vite preview\"\n  },\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpu NODE_OPTIONS=--max_http_header_size=128000 run dev\n```\n\n```text\ncross-env NODE_OPTIONS=--max_http_header_size=128000 vite\n```\n\n```text\nnode --max_http_header_size=128000 node_modules/vite/bin/vite.js\n```\n\n```text\nNODE_OPTIONS\n```\n\n```text\nnode\n```\n\n```text\ncross-env\n```\n\n```text\nvite\n```\n\n========================================\n\nComments:\n- Use instead node command that \"vite\" actually means, something like `node --max_http_header_size=128000 node_modules&#47;vite&#47;bin&#47;vite.js`\n- @Estus Flask Worked perfectly. I'm getting a 414 URI too long error now, instead of 431, but you answered EXACTLY what I was looking for. If you post it as an answer I'll accept it. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:46.435Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":112,"estimatedTokens":851}}539{"id":"stack-78397311","source":"stackoverflow","questionId":78397311,"title":"Error on Node JS npm/npx project creating with vite/react js \"node:internal/modules/cjs/loader:1205 throw err\"","tags":["reactjs","node.js","npm","vite","npx"],"text":"Title: Error on Node JS npm/npx project creating with vite/react js \"node:internal/modules/cjs/loader:1205 throw err\"\nTags: reactjs, node.js, npm, vite, npx\nSource: Stack Overflow\n\nQuestion:\nCurrently i'm running node -v v22.0.0\nHere I'm creating a new React Js porject. but when initiating the project with vite technology, it errors like this in the terminal.\n\n```\nnpm create vite@latest\n```\n\n```\nnode:internal/modules/cjs/loader:1205\n throw err;\n ^\n\nError: Cannot find module 'C:\\Users\\rvdas\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js' \n at Module._resolveFilename (node:internal/modules/cjs/loader:1202:15)\n at Module._load (node:internal/modules/cjs/loader:1027:27)\n at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:187:14)\n at node:internal/main/run_main_module:28:49 {\n code: 'MODULE_NOT_FOUND',\n requireStack: []\n}\n\nNode.js v22.0.0\n```\n\nAlso, when I try to create app using\n\n```\nnpx create-react-app projectName\n```\n\nIt also errors like above.\n\nI tried clearning cache\n\n```\nnpm cache clean --force\n```\n\nDidn't work.\n\n========================================\n\nTop Answer:\nNode.js 22.1.0 has been released and `npm create vite@latest` (and other commands) now work properly on Windows with this new version:\n\n```\nC:\\Development> npm create vite@latest\n\n> npx\n> create-vite\n\n√ Project name: ... vite-node22\n√ Select a framework: » React\n√ Select a variant: » TypeScript + SWC\n\nScaffolding project in C:\\Development\\vite-node22...\n\nDone. Now run:\n\n cd vite-node22\n npm install\n npm run dev\n```\n\n========================================\n\nCode:\n```text\nnpm create vite@latest\n```\n\n```text\nnode:internal/modules/cjs/loader:1205\n  throw err;\n  ^\n\nError: Cannot find module 'C:\\Users\\rvdas\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js'       \n    at Module._resolveFilename (node:internal/modules/cjs/loader:1202:15)\n    at Module._load (node:internal/modules/cjs/loader:1027:27)\n    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:187:14)\n    at node:internal/main/run_main_module:28:49 {\n  code: 'MODULE_NOT_FOUND',\n  requireStack: []\n}\n\nNode.js v22.0.0\n```\n\n```text\nnpx create-react-app projectName\n```\n\n```text\nnpm cache clean --force\n```\n\n```text\nC:\\Program Files\\nodejs\\node_modules\\npm\n```\n\n```text\n%AppData%\\Roaming\\npm\\node_modules\n```\n\n```text\nnpm i -g npm\n```\n\n```text\nC:\\Development> npm create vite@latest\n\n> npx\n> create-vite\n\n√ Project name: ... vite-node22\n√ Select a framework: » React\n√ Select a variant: » TypeScript + SWC\n\nScaffolding project in C:\\Development\\vite-node22...\n\nDone. Now run:\n\n  cd vite-node22\n  npm install\n  npm run dev\n```\n\n```text\nnpm create vite@latest\n```\n\n========================================\n\nComments:\n- Please try with node LTS 20.9.0v .\n- On macOS, I'm not able to reproduce this issue. How did you install Node.js 22 on Windows?\n- @Valentin now node js running version 20.12.2 which is with Long Term Support (LTS). But you can download version 22 selecting manually from drop down list. Link\n- @MdShorifulIslam I already had Node.js 22 on Windows. I was asking how you installed it. Today I was able to test on Windows and I reproduce your issue. I use pnpm usually and it's working properly with it. I'm not sure what's the cause of the issue but is either in create-vite or npm/cli.\n- it was a technical error after installing Visual Studio 2022. Appdata->roaming->npm directory was deleted somehow. then i created it manually. then its solved.\n- Tried downgrading to 20.12.2 LTS, it worked\n- @MdShorifulIslam I have the issue when trying to invoke `npm config` as well and there's an issue on npm-cli GitHub","metadata":{"transformedAt":"2026-08-18T18:33:46.435Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":146,"estimatedTokens":910}}540{"id":"stack-75188900","source":"stackoverflow","questionId":75188900,"title":"Vue - get UiKit images in Vite build","tags":["vue.js","uikit","vuejs3","vite"],"text":"Title: Vue - get UiKit images in Vite build\nTags: vue.js, uikit, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\ni'm using Vue Single-file-components with UiKit.\n\n**main.js**\n\n```\nimport App from './App.vue'\nimport \"../node_modules/uikit/src/less/uikit.theme.less\";\n\nconst app = createApp(App)\nconst globals = reactive({})\napp.mount('#app')\n```\n\nuikit includes a few SVG files for things like the arrows on ``:\nhttps://i.sstatic.net/Dpm6e.png\n\n```\n/path/to/project/node_modules/uikit/src/images/backgrounds\n├── accordion-close.svg\n├── accordion-open.svg\n├── divider-icon.svg\n├── form-checkbox-indeterminate.svg\n├── form-checkbox.svg\n├── form-datalist.svg\n├── form-radio.svg\n├── form-select.svg\n└── list-bullet.svg\n```\n\nunfortunately, the SVGs don't end up in `dist/` when i `npm run build` (or `npm run dev`, etc.)\n\nhttps://i.sstatic.net/16Y84.png\n\nHow do i get those images working?\n\nThe path in the image above is correct relative to the less sources; i get the impression that something is supposed to automagically change them on compile (lessc doesn't seem to have any relevant options?)\n\n### Edit\n\nI noticed this in the output of `vue build`:\n\n```\n$ npm run build\n\n> junctspace-web-designer@0.0.0 build\n> vite build\n\nvite v4.0.4 building for production...\ntransforming (106) node_modules/yaml/browser/dist/compose/util-contains-newline.js\n../../images/backgrounds/divider-icon.svg referenced in /home/tether/Clones/junctspace-web-designer/src/assets/main.less didn't resolve at build time, it will remain unchanged to be resolved at runtime\n\n../../images/backgrounds/list-bullet.svg referenced in /home/tether/Clones/junctspace-web-designer/src/assets/main.less didn't resolve at build time, it will remain unchanged to be resolved at runtime\n\n../../images/backgrounds/form-select.svg referenced in /home/tether/Clones/junctspace-web-designer/src/assets/main.less didn't resolve at build time, it will remain unchanged to be resolved at runtime\n\n../../images/backgrounds/form-datalist.svg referenced in /home/tether/Clones/junctspace-web-designer/src/assets/main.less didn't resolve at build time, it will remain unchanged to be resolved at runtime\n\n../../images/backgrounds/form-radio.svg referenced in /home/tether/Clones/junctspace-web-designer/src/assets/main.less didn't resolve at build time, it will remain unchanged to be resolved at runtime\n\n../../images/backgrounds/form-checkbox.svg referenced in /home/tether/Clones/junctspace-web-designer/src/assets/main.less didn't resolve at build time, it will remain unchanged to be resolved at runtime\n\n../../images/backgrounds/form-checkbox-indeterminate.svg referenced in /home/tether/Clones/junctspace-web-designer/src/assets/main.less didn't resolve at build time, it will remain unchanged to be resolved at runtime\n\n../../images/backgrounds/accordion-close.svg referenced in /home/tether/Clones/junctspace-web-designer/src/assets/main.less didn't resolve at build time, it will remain unchanged to be resolved at runtime\n\n../../images/backgrounds/accordion-open.svg referenced in /home/tether/Clones/junctspace-web-designer/src/assets/main.less didn't resolve at build time, it will remain unchanged to be resolved at runtime\n✓ 116 modules transformed.\ndist/index.html 0.76 kB\ndist/assets/index-9a8004d3.css 113.23 kB │ gzip: 19.09 kB\ndist/assets/index-08c469df.js 206.39 kB │ gzip: 70.56 kB\n```\n\n========================================\n\nCode:\n```text\nimport App from './App.vue'\nimport \"../node_modules/uikit/src/less/uikit.theme.less\";\n\nconst app = createApp(App)\nconst globals = reactive({})\napp.mount('#app')\n```\n\n```none\n/path/to/project/node_modules/uikit/src/images/backgrounds\n├── accordion-close.svg\n├── accordion-open.svg\n├── divider-icon.svg\n├── form-checkbox-indeterminate.svg\n├── form-checkbox.svg\n├── form-datalist.svg\n├── form-radio.svg\n├── form-select.svg\n└── list-bullet.svg\n```\n\n```none\n$ npm run build\n\n> junctspace-web-designer@0.0.0 build\n> vite build\n\nvite v4.0.4 building for production...\ntransforming (106) node_modules/yaml/browser/dist/compose/util-contains-newline.js\n../../images/backgrounds/divider-icon.svg referenced in /home/tether/Clones/junctspace-web-designer/src/assets/main.less didn't resolve at build time, it will remain unchanged to be resolved at runtime\n\n../../images/backgrounds/list-bullet.svg referenced in /home/tether/Clones/junctspace-web-designer/src/assets/main.less didn't resolve at build time, it will remain unchanged to be resolved at runtime\n\n../../images/backgrounds/form-select.svg referenced in /home/tether/Clones/junctspace-web-designer/src/assets/main.less didn't resolve at build time, it will remain unchanged to be resolved at runtime\n\n../../images/backgrounds/form-datalist.svg referenced in /home/tether/Clones/junctspace-web-designer/src/assets/main.less didn't resolve at build time, it will remain unchanged to be resolved at runtime\n\n../../images/backgrounds/form-radio.svg referenced in /home/tether/Clones/junctspace-web-designer/src/assets/main.less didn't resolve at build time, it will remain unchanged to be resolved at runtime\n\n../../images/backgrounds/form-checkbox.svg referenced in /home/tether/Clones/junctspace-web-designer/src/assets/main.less didn't resolve at build time, it will remain unchanged to be resolved at runtime\n\n../../images/backgrounds/form-checkbox-indeterminate.svg referenced in /home/tether/Clones/junctspace-web-designer/src/assets/main.less didn't resolve at build time, it will remain unchanged to be resolved at runtime\n\n../../images/backgrounds/accordion-close.svg referenced in /home/tether/Clones/junctspace-web-designer/src/assets/main.less didn't resolve at build time, it will remain unchanged to be resolved at runtime\n\n../../images/backgrounds/accordion-open.svg referenced in /home/tether/Clones/junctspace-web-designer/src/assets/main.less didn't resolve at build time, it will remain unchanged to be resolved at runtime\n✓ 116 modules transformed.\ndist/index.html                   0.76 kB\ndist/assets/index-9a8004d3.css  113.23 kB │ gzip: 19.09 kB\ndist/assets/index-08c469df.js   206.39 kB │ gzip: 70.56 kB\n```\n\n```text\n<select>\n```\n\n```text\ndist/\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm run dev\n```\n\n```text\nvue build\n```\n\n```js\nexport default defineConfig({\n  resolve: {\n    alias: {\n      '../../images/backgrounds': 'uikit/src/images/backgrounds',\n      '../../images/components': 'uikit/src/images/components',\n      '../../images/icons': 'uikit/src/images/icons'\n    }\n  }\n});\n```\n\n```text\nvite.config.js\n```\n\n========================================\n\nComments:\n- was hoping for a way that would work in general (mostly for the sake of people in the future googling this) but i'll take it :3","metadata":{"transformedAt":"2026-08-18T18:33:46.435Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":173,"estimatedTokens":1671}}541{"id":"stack-69113480","source":"stackoverflow","questionId":69113480,"title":"Sveltekit: Cannot find module 'swiper'","tags":["svelte","swiper.js","vite","codesandbox","sveltekit"],"text":"Title: Sveltekit: Cannot find module 'swiper'\nTags: svelte, swiper.js, vite, codesandbox, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI tried the sveltekit-swiper example from\nhttps://swiperjs.com/svelte\n\n```\n08:07:51 [vite] Error when evaluating SSR module /src/routes/s.svelte: Error: Cannot find module 'swiper' from 'C:/Svelte/tw09swipe/src/routes'\n at Function.resolveSync [as sync] (C:\\Svelte\\tw09swipe\\node_modules\\resolve\\lib\\sync.js:102:15)\n at resolveFrom$3 (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:4081:29)\n at resolve (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:75136:22)\n at nodeRequire (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:75115:25)\n at ssrImport (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:75057:20)\n at eval (/src/routes/s.svelte:7:37)\n at async instantiateModule (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:75100:9)\n```\n\nI have installed new copies of sveltekit and swiper. Versions:\n\n```\nswiper@7.0.4\nvite@2.5.6\n@sveltejs/kit@1.0.0-next.165\n```\n\nA working example with Swiper 7 can be found in the codesandbox: https://codesandbox.io/s/3dxrg\nIt uses Swiper 7.0.3 and SvelteKit v1.0.0-next.104\n\nI have installed svelte/kit and swiper without any changes:\n\n```\nmkdir tw09swipe\ncd tw09swipe\nnpm init svelte@next\nnpm install\nnpm i swiper\n```\n\nThis is **my** package.json:\n\n```\n{\n \"name\": \"~TODO~\",\n \"version\": \"0.0.1\",\n \"scripts\": {\n \"dev\": \"svelte-kit dev\",\n \"build\": \"svelte-kit build\",\n \"preview\": \"svelte-kit preview\",\n \"check\": \"svelte-check --tsconfig ./tsconfig.json\",\n \"check:watch\": \"svelte-check --tsconfig ./tsconfig.json --watch\"\n },\n \"devDependencies\": {\n \"@sveltejs/kit\": \"next\",\n \"svelte\": \"^3.34.0\",\n \"svelte-check\": \"^2.0.0\",\n \"svelte-preprocess\": \"^4.9.4\",\n \"tslib\": \"^2.0.0\",\n \"typescript\": \"^4.0.0\"\n },\n \"type\": \"module\",\n \"dependencies\": {\n \"swiper\": \"^7.0.5\"\n }\n}\n```\n\nAnd here is tsconfig.json:\n\n```\n{\n \"compilerOptions\": {\n \"moduleResolution\": \"node\",\n \"module\": \"es2020\",\n \"lib\": [\"es2020\", \"DOM\"],\n \"target\": \"es2019\",\n /**\n svelte-preprocess cannot figure out whether you have a value or a type, so tell TypeScript\n to enforce using \\`import type\\` instead of \\`import\\` for Types.\n */\n \"importsNotUsedAsValues\": \"error\",\n \"isolatedModules\": true,\n \"resolveJsonModule\": true,\n /**\n To have warnings/errors of the Svelte compiler at the correct position,\n enable source maps by default.\n */\n \"sourceMap\": true,\n \"esModuleInterop\": true,\n \"skipLibCheck\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"baseUrl\": \".\",\n \"allowJs\": true,\n \"checkJs\": true,\n \"paths\": {\n \"$lib\": [\"src/lib\"],\n \"$lib/*\": [\"src/lib/*\"]\n }\n },\n \"include\": [\"src/**/*.d.ts\", \"src/**/*.js\", \"src/**/*.ts\", \"src/**/*.svelte\"]\n}\n```\n\nAnd svelte.config.js:\n\n```\nimport preprocess from 'svelte-preprocess';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: preprocess(),\n\n kit: {\n // hydrate the element in src/app.html\n target: '#svelte'\n }\n};\n\nexport default config;\n```\n\nroutes/s.svelte\n\n```\n\n // Import Swiper Svelte components \n import { Navigation, Pagination, Scrollbar, A11y } from \"swiper\";\n import { Swiper, SwiperSlide } from \"swiper/svelte\"; \n\n // Import Swiper styles\n import \"swiper/css\";\n import \"swiper/css/navigation\";\n import \"swiper/css/pagination\";\n import \"swiper/css/scrollbar\";\n\n console.log(\"slide change\")}\n on:swiper={(e) => console.log(e.detail[0])}\n>\n Slide 1\n Slide 2\n Slide 3\n Slide 4\n ...\n\n```\n\n========================================\n\nCode:\n```text\n08:07:51 [vite] Error when evaluating SSR module /src/routes/s.svelte: Error: Cannot find module 'swiper' from 'C:/Svelte/tw09swipe/src/routes'\n    at Function.resolveSync [as sync] (C:\\Svelte\\tw09swipe\\node_modules\\resolve\\lib\\sync.js:102:15)\n    at resolveFrom$3 (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:4081:29)\n    at resolve (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:75136:22)\n    at nodeRequire (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:75115:25)\n    at ssrImport (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:75057:20)\n    at eval (/src/routes/s.svelte:7:37)\n    at async instantiateModule (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:75100:9)\n```\n\n```text\nswiper@7.0.4\nvite@2.5.6\n@sveltejs/kit@1.0.0-next.165\n```\n\n```text\nmkdir tw09swipe\ncd tw09swipe\nnpm init svelte@next\nnpm install\nnpm i swiper\n```\n\n```text\n{\n  \"name\": \"~TODO~\",\n  \"version\": \"0.0.1\",\n  \"scripts\": {\n    \"dev\": \"svelte-kit dev\",\n    \"build\": \"svelte-kit build\",\n    \"preview\": \"svelte-kit preview\",\n    \"check\": \"svelte-check --tsconfig ./tsconfig.json\",\n    \"check:watch\": \"svelte-check --tsconfig ./tsconfig.json --watch\"\n  },\n  \"devDependencies\": {\n    \"@sveltejs/kit\": \"next\",\n    \"svelte\": \"^3.34.0\",\n    \"svelte-check\": \"^2.0.0\",\n    \"svelte-preprocess\": \"^4.9.4\",\n    \"tslib\": \"^2.0.0\",\n    \"typescript\": \"^4.0.0\"\n  },\n  \"type\": \"module\",\n  \"dependencies\": {\n    \"swiper\": \"^7.0.5\"\n  }\n}\n```\n\n```text\n{\n    \"compilerOptions\": {\n        \"moduleResolution\": \"node\",\n        \"module\": \"es2020\",\n        \"lib\": [\"es2020\", \"DOM\"],\n        \"target\": \"es2019\",\n        /**\n            svelte-preprocess cannot figure out whether you have a value or a type, so tell TypeScript\n            to enforce using \\`import type\\` instead of \\`import\\` for Types.\n            */\n        \"importsNotUsedAsValues\": \"error\",\n        \"isolatedModules\": true,\n        \"resolveJsonModule\": true,\n        /**\n            To have warnings/errors of the Svelte compiler at the correct position,\n            enable source maps by default.\n            */\n        \"sourceMap\": true,\n        \"esModuleInterop\": true,\n        \"skipLibCheck\": true,\n        \"forceConsistentCasingInFileNames\": true,\n        \"baseUrl\": \".\",\n        \"allowJs\": true,\n        \"checkJs\": true,\n        \"paths\": {\n            \"$lib\": [\"src/lib\"],\n            \"$lib/*\": [\"src/lib/*\"]\n        }\n    },\n    \"include\": [\"src/**/*.d.ts\", \"src/**/*.js\", \"src/**/*.ts\", \"src/**/*.svelte\"]\n}\n```\n\n```text\nimport preprocess from 'svelte-preprocess';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n    // Consult https://github.com/sveltejs/svelte-preprocess\n    // for more information about preprocessors\n    preprocess: preprocess(),\n\n    kit: {\n        // hydrate the <div id=\"svelte\"> element in src/app.html\n        target: '#svelte'\n    }\n};\n\nexport default config;\n```\n\n```text\n<script>\n\n    // Import Swiper Svelte components    \n    import { Navigation, Pagination, Scrollbar, A11y } from \"swiper\";\n    import { Swiper, SwiperSlide } from \"swiper/svelte\";    \n\n    // Import Swiper styles\n    import \"swiper/css\";\n    import \"swiper/css/navigation\";\n    import \"swiper/css/pagination\";\n    import \"swiper/css/scrollbar\";\n</script>\n\n<Swiper\n    modules={[Navigation, Pagination, Scrollbar, A11y]}\n    spaceBetween={50}\n    slidesPerView={3}\n    navigation\n    pagination={{ clickable: true }}\n    scrollbar={{ draggable: true }}\n    on:slideChange={() => console.log(\"slide change\")}\n    on:swiper={(e) => console.log(e.detail[0])}\n>\n    <SwiperSlide>Slide 1</SwiperSlide>\n    <SwiperSlide>Slide 2</SwiperSlide>\n    <SwiperSlide>Slide 3</SwiperSlide>\n    <SwiperSlide>Slide 4</SwiperSlide>\n    ...\n</Swiper>\n```\n\n```text\n<script>\n    import { Swiper, SwiperSlide } from 'swiper/svelte';\n    import SwiperCore, { Mousewheel, Pagination } from 'swiper';\n    import 'swiper/css';\n    import 'swiper/css/pagination';\n\n    ...\n\n    SwiperCore.use([Mousewheel, Pagination]);\n</script>\n\n...\n    <Swiper\n        direction='vertical'\n        mousewheel={true}\n        pagination={true}\n        slidesPerView={1}\n        on:slideChange={onSlideChange}\n        on:swiper={(e) => console.log(e.detail[0])}\n    >\n        <SwiperSlide>\n    </Swiper>\n...\n```\n\n```text\n<script>\n    ...\n    let Slider;\n    onMount(async () => {\n        const module = await import('./components/Slider.svelte');\n        Slider = module.default;\n    });\n    ...\n</script>\n\n<svelte:component this={Slider}/>\n\n...\n```\n\n```text\nonMount\n```\n\n```text\nonMount\n```\n\n========================================\n\nComments:\n- The new swiper@7.0.5 did not solve this problem.\n- Weird response here. I created skeleton Sveltekit with TS. When I go to `localhost:3000&#47;s` the browser shows error `Cannot find module 'swiper' from 'M:&#47;Temp&#47;swiper_test&#47;src&#47;routes'` while in VSCode, import clearly points to `module \"m:&#47;Temp&#47;swiper_test&#47;node_modules&#47;swiper&#47;svelte&#47;swiper-svelt&zwnj;&#8203;e\"` as it should. Essentially same failure as you.\n- When I do a search for `sync.js:102:15` I do see issues out there. Check out github.com/sveltejs/kit/issues/2237 Pretty good analysis of what is driving the error. And they say 1.0.0-next.160 release fixes it. sigh.\n- Sorry for asking again. I have tried `import { Swiper, SwiperSlide } from 'swiper&#47;swiper-svelte.cjs.js';` And `npm run build`. Nothing worked. Any hints?\n- Thank you! This is how it works. I don't understand why the detour via a component is necessary. Maybe someone in the know can explain it. But anyway - it works, also with SvelteKit v1.0.0-next.173. In Slider.svelte is missing `import '.&#47;style.css';` `style.css` can be found for example here codesandbox.io/s/mop0u\n- But this is a really interesting solution, best thanks!\n- When SvelteKit bundles files (even for dev server), it simulates server-side like environment, to run and optimize code faster (and other things like supporting pre-rendering out of box). Some of modules don't expect this and trying to access `window&#47;document` variable (there is none in server-side JS) - so we need to load these modules `onMount`, because code there executes only in client side environment, where `window` object exists.\n- Thank you for this explanation. I believed that an \"onMount\" in \"index.svelte\" would be sufficient. But I understand now why a separate module is necessary.","metadata":{"transformedAt":"2026-08-18T18:33:46.435Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":348,"estimatedTokens":2540}}542{"id":"stack-79853496","source":"stackoverflow","questionId":79853496,"title":"Laravel with Vite: Running dev server in an iFrame","tags":["php","laravel","iframe","vite","inertiajs"],"text":"Title: Laravel with Vite: Running dev server in an iFrame\nTags: php, laravel, iframe, vite, inertiajs\nSource: Stack Overflow\n\nQuestion:\nI'm developing a Laravel app that runs inside an iFrame. While everything works fine with production builds (`npm run build`), I'm unable to get Vite working in development mode, which makes the development workflow very cumbersome.\n\nI am developing for a web-application which has an app-store, where \"apps\" are actually just iframes who get passed certain query params.\n\n**Current Setup:**\n\n```\n# Terminal 1\nphp artisan serve\n\n# Terminal 2 \nnpm run dev\n\n# Terminal 3\nngrok http 8000\n```\n\n**The Issue:**\n\nWhen accessing the ngrok URL directly in the browser, everything works perfectly. However, when the app is loaded through the iFrame, I get CORS and mixed content errors:\n\n```\nAccess to script at 'http://[::1]:5173/@vite/client' from origin 'https://.eu.ngrok.io' \nhas been blocked by CORS policy: Permission was denied for this request to access the `unknown` address space.\n\nGET http://[::1]:5173/@vite/client net::ERR_FAILED\n\nAccess to script at 'http://[::1]:5173/resources/js/app.ts' from origin 'https://.eu.ngrok.io' \nhas been blocked by CORS policy: Permission was denied for this request to access the `unknown` address space.\n\nMixed Content: The page at 'https:///' was loaded over HTTPS, but requested an \ninsecure script 'http://0.0.0.0:5173/resources/js/app.ts'. This request has been blocked; \nthe content must be served over HTTPS.\n```\n\n**What I've Tried:**\n\n**Basic HTTPS with mkcert**\n\nCreated local certificates: `mkcert localhost`.\n\nUpdated `vite.config.ts` to include the certificates:\n\n```\nserver: {\n https: {\n key: fs.readFileSync(path.resolve(__dirname, \"localhost-key.pem\")),\n cert: fs.readFileSync(path.resolve(__dirname, \"localhost.pem\"))\n },\n host: '0.0.0.0'\n}\n```\n\nResult: Got ERR_BLOCKED_BY_CLIENT errors because browser was trying to load from https://0.0.0.0:5173\n\n**Laravel proxy for Vite:**\n\nAdded proxy route in routes/web.php:\n\n```\nRoute::any('{vite_path}', function ($vite_path) {\n // Proxy logic to forward requests to https://localhost:5173\n})->where('vite_path', '.*');\n```\n\n**Result**: Getting 404 errors for certain Vite internal modules:\n\n```\nGET https://.eu.ngrok.io/node_modules/vite/dist/client/env.mjs net::ERR_ABORTED 404\nGET https://.eu.ngrok.io/@id/__x00__plugin-vue:export-helper net::ERR_ABORTED 404\n```\n\n**How can I configure Laravel and Vite to work together with HMR?**\n\n- Ideally I want only 1 ngrok tunnel running.\n\n- Running `npm run build` works perfectly, but this of course removes HMR.\n\n- The iFrame is on a different domain than the ngrok tunnel.\n\n========================================\n\nCode:\n```text\n# Terminal 1\nphp artisan serve\n\n# Terminal 2  \nnpm run dev\n\n# Terminal 3\nngrok http 8000\n```\n\n```text\nAccess to script at 'http://[::1]:5173/@vite/client' from origin 'https://<ngrok-url>.eu.ngrok.io' \nhas been blocked by CORS policy: Permission was denied for this request to access the `unknown` address space.\n\nGET http://[::1]:5173/@vite/client net::ERR_FAILED\n\nAccess to script at 'http://[::1]:5173/resources/js/app.ts' from origin 'https://<ngrok-url>.eu.ngrok.io' \nhas been blocked by CORS policy: Permission was denied for this request to access the `unknown` address space.\n\nMixed Content: The page at 'https://<parent-web-url>/' was loaded over HTTPS, but requested an \ninsecure script 'http://0.0.0.0:5173/resources/js/app.ts'. This request has been blocked; \nthe content must be served over HTTPS.\n```\n\n```text\nserver: {\n    https: {\n        key: fs.readFileSync(path.resolve(__dirname, \"localhost-key.pem\")),\n        cert: fs.readFileSync(path.resolve(__dirname, \"localhost.pem\"))\n    },\n    host: '0.0.0.0'\n}\n```\n\n```text\nRoute::any('{vite_path}', function ($vite_path) {\n    // Proxy logic to forward requests to https://localhost:5173\n})->where('vite_path', '.*');\n```\n\n```text\nGET https://<ngrok-url>.eu.ngrok.io/node_modules/vite/dist/client/env.mjs net::ERR_ABORTED 404\nGET https://<ngrok-url>.eu.ngrok.io/@id/__x00__plugin-vue:export-helper net::ERR_ABORTED 404\n```\n\n```text\nnpm run build\n```\n\n```text\nmkcert localhost\n```\n\n```text\nvite.config.ts\n```\n\n```text\nnpm run build\n```\n\n```text\nVITE_DEV_SERVER_URL=vite-<your-domain>.eu.ngrok.io\n```\n\n```text\ntunnels:\n  laravel:\n    proto: http\n    addr: 8000\n    hostname: your-domain.eu.ngrok.io\n  vite:\n    proto: http\n    addr: 5173\n    hostname: vite-your-domain.eu.ngrok.io\n```\n\n```text\nexport default defineConfig(({ mode }) => {\n    const env = loadEnv(mode, process.cwd());\n\n    return {\n        server:\n            process.env.NODE_ENV === \"development\"\n                ? {\n                      host: \"0.0.0.0\",\n                      strictPort: true,\n                      hmr: {\n                          // The browser inside the iframe will connect to this URL for HMR updates.\n                          host: env.VITE_DEV_SERVER_URL,\n                          protocol: \"wss\", sites\n                          clientPort: 443\n                      }\n                  }\n                : {},\n        ...rest of config\n    };\n});\n```\n\n```text\nVITE_DEV_SERVER_URL\n```\n\n```text\n.env\n```\n\n```text\nngrok.yml\n```\n\n```text\nvite.config\n```\n\n========================================\n\nComments:\n- Nice find. Vite HMR needs to be accessible from the iframe origin, so exposing the Vite dev server via its own ngrok tunnel and configuring hmr.host is the correct approach.","metadata":{"transformedAt":"2026-08-18T18:33:46.435Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":209,"estimatedTokens":1362}}543{"id":"stack-79195401","source":"stackoverflow","questionId":79195401,"title":"ShadCN-Vue installation - did not recognize object of type \"TSInterfaceHeritage\"","tags":["vue.js","vite","shadcnui"],"text":"Title: ShadCN-Vue installation - did not recognize object of type \"TSInterfaceHeritage\"\nTags: vue.js, vite, shadcnui\nSource: Stack Overflow\n\nQuestion:\nI'm trying to install ShadCN for VueJS but I'm encountering a weird error after successful installation.\n\nI've followed each step of the installation guide under:\nhttps://www.shadcn-vue.com/docs/installation/vite\n\nTerminal/Vite says everything went successfully after step number 8.\n\nStep 9 on the docs:\n\nWhen I'm trying to add a button with: npx shadcn-vue@latest add button\n\nin order to verify that the installation worked / use the a component\n\nI'm encountering the followin error:\n\nError: did not recognize object of type \"TSInterfaceHeritage\"\n\nWhat am I doing wrong? How can I fix it?\n\nThanks.\n\n========================================\n\nCode:\n```text\nnpx shadcn-vue@0.10 add button\n```\n\n========================================\n\nComments:\n- Thank you for the hint. I was hoping to offer ShadCN as an alternative to Vuetify at my new work. However, running into this issue as a first dev-experience made think twice about this.\n- My experience was all good with the previous version. The latest one seems to have few bugs. @user3135691","metadata":{"transformedAt":"2026-08-18T18:33:46.435Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":38,"estimatedTokens":298}}544{"id":"stack-77792682","source":"stackoverflow","questionId":77792682,"title":"Redirecting of HTTP request on Vite-Vue app - DEV mode","tags":["javascript","vue.js","vuejs3","vite"],"text":"Title: Redirecting of HTTP request on Vite-Vue app - DEV mode\nTags: javascript, vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI want to change base URL of HTTP requests from host address of Vite.js app (`http://localhost:5173`) to host address of my ASP .NET API (`http://localhost:5815`) on dev mode (`npm run dev`).\n\nhttps://i.sstatic.net/jJJad.png\n\nBut I have such error during run of my Vite-Vue app after apply proxy to redirecting requests:\n\nhttps://i.sstatic.net/rHW6M.png\n\nMy vite.config.js file:\n\n```\nimport { fileURLToPath, URL } from 'node:url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n vue(),\n ],\n build: {\n cssCodeSplit: false,\n },\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url))\n }\n },\n server: {\n proxy: {\n '/': {\n target: 'http://localhost:5815',\n changeOrigin: true,\n rewrite: (path) => path.replace(/^\\//, '')\n }\n }\n }\n})\n```\n\nI also tried such `vite.config.js`\n\n```\nimport { fileURLToPath, URL } from 'node:url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n vue(),\n ],\n build: {\n cssCodeSplit: false,\n },\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url))\n }\n },\n server: {\n proxy: {\n '/api': {\n target: 'http://localhost:5815',\n changeOrigin: true,\n rewrite: (path) => path.replace(/^\\/api/, '')\n }\n }\n }\n})\n```\n\nResult was that:\n\nhttps://i.sstatic.net/D1HFn.png\n\nWhat I should do in order to redirect all of my HTTP requests from\n`localhost:5173` to `localhost:5815` during run my in dev mode (`npm run dev`)?\n\nI mention only that similar project with only Vue.js, worked with this `vue.config.js`:\n\n```\nconst { defineConfig } = require('@vue/cli-service');\n\nmodule.exports = defineConfig({\n transpileDependencies: true,\n lintOnSave: false,\n devServer: {\n proxy: 'http://localhost:5815',\n },\n});\n```\n\n========================================\n\nCode:\n```text\nimport { fileURLToPath, URL } from 'node:url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    vue(),\n  ],\n  build: {\n    cssCodeSplit: false,\n  },\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url))\n    }\n  },\n  server: {\n    proxy: {\n      '/': {\n        target: 'http://localhost:5815',\n        changeOrigin: true,\n        rewrite: (path) => path.replace(/^\\//, '')\n      }\n    }\n  }\n})\n```\n\n```js\nimport { fileURLToPath, URL } from 'node:url'\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    vue(),\n  ],\n  build: {\n    cssCodeSplit: false,\n  },\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url))\n    }\n  },\n  server: {\n    proxy: {\n      '/api': {\n        target: 'http://localhost:5815',\n        changeOrigin: true,\n        rewrite: (path) => path.replace(/^\\/api/, '')\n      }\n    }\n  }\n})\n```\n\n```js\nconst { defineConfig } = require('@vue/cli-service');\n\nmodule.exports = defineConfig({\n  transpileDependencies: true,\n  lintOnSave: false,\n  devServer: {\n    proxy: 'http://localhost:5815',\n  },\n});\n```\n\n```text\nhttp://localhost:5173\n```\n\n```text\nhttp://localhost:5815\n```\n\n```text\nnpm run dev\n```\n\n```text\nvite.config.js\n```\n\n```text\nlocalhost:5173\n```\n\n```text\nlocalhost:5815\n```\n\n```text\nnpm run dev\n```\n\n```text\nvue.config.js\n```\n\n```js\nexport default defineConfig({\n  server: {\n    proxy: {\n      // With options:\n      // http://localhost:5173/api/users\n      //   -> http://localhost:5815/users\n      '/api': {\n        target: 'http://localhost:5815',\n        changeOrigin: true,\n        rewrite: (path) => path.replace(/^\\/api/, ''), // It removes the /api from the request address, so it will truly be used only for differentiation\n      },\n    },\n  },\n})\n```\n\n```js\n// Before (NOT WORKING)\n// The proxy cannot be recognized without a prefix.\naxios.get('/some-endpoint') // With what you are currently trying, it will never work from the root\n// Call http://localhost:5173/some-endpoint (Vite Host)\n```\n\n```js\n// After (SUCCESSFULLY)\naxios.get('/api/some-endpoint') // With the /api proxy route defined now, it works\n// Call http://localhost:5815/some-endpoint (Your Custom API)\n```\n\n```js\nconst API_URI = process.env.NODE_ENV === 'production'\n  ? 'http://example.com'    // in prod\n  : 'http://localhost:5815' // in dev\n\nexport default defineConfig({\n  server: {\n    // (DEV MODE) With options:\n    // http://localhost:5173/api/users\n    //   -> http://localhost:5815/users\n    //\n    // (PROD MODE) With options:\n    // http://yourdomain.com/api/users\n    //   -> http://example.com/users\n    proxy: {\n      '/api': {\n        target: API_URI,\n        changeOrigin: true,\n        rewrite: (path) => path.replace(/^\\/api/, ''),\n      },\n    },\n  },\n})\n```\n\n```text\nserver.proxy.rewirte\n```\n\n```text\nserver.proxy.rewrite\n```\n\n```text\nProxyOptions\n```\n\n```text\nrewrite\n```\n\n```text\n/api\n```\n\n```text\nlocalhost:5815\n```\n\n```text\nlocalhost:5815/some-endpoint\n```\n\n```text\nserver.host\n```\n\n```text\nserver.host + /api\n```\n\n========================================\n\nComments:\n- I modified my vite.config.js file, but when page requesting for example localhost:5173/getarticles, I have 404 response.\n- And i forget to tell that in project I not have requests with URL like that: \"[localhost or something else]/api\". Example of my request is: localhost:5173/getarticles, without \"api\".\n- I feel that you want to achieve the impossible. You want to say that the requests coming out of your application sometimes need to be loaded from `localhost:5173`, such as the app's index.html, JS files, CSS files, images, fonts, etc., but you also want to fetch your API routes from here in a mixed manner. If rewriting the routes is not feasible, you are in a difficult situation. Because you have to declare each API route individually, such as `&#47;getusers`, `&#47;getposts`, `&#47;getarticles`, etc., and redirect each one to its counterpart on `localhost:5815`.\n- I find it more practical to create a common `&#47;api` route under which you will handle these. The /api is just a common group name in your frontend app, as mentioned, it won't be included in the URL thanks to `path.replace()`. So, following my solution, it's your job to add a `&#47;api` prefix before each API route call in your frontend application.\n- So when you call the `&#47;api&#47;getarticles` example endpoint, Vite will automatically invoke `http:&#47;&#47;localhost:5815&#47;getarticles`, thanks to the `&#47;api` proxy. Due to `path.replace()`, as you can see, the `&#47;api` prefix will not be included in the new URL address.\n- You don't need to include the domain in the URL address; Vite will handle that for you since you've set up the proxy. In this case, `localhost:5173&#47;api&#47;getarticles` will be redirected to `localhost:5815&#47;getarticles`. If this is not suitable for you, then you would have to individually set up a proxy for each address. However, I believe this is not a good solution and is not standard practice. In any case, I recommend consolidating your API routes under the mentioned API (or a name of your choice) group, so you can easily identify that URLs starting with this group name are API queries.\n- you explained me this perfectly - I modified according to your advices and it work!\n- not working and not replacing anything.\n- @ИгорТашевски I tested it again. It works. I expanded my answer with some additional resources. It seems to be version-compatible with Vite 6 as well.","metadata":{"transformedAt":"2026-08-18T18:33:46.435Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":24,"totalLines":312,"estimatedTokens":1931}}545{"id":"stack-72836961","source":"stackoverflow","questionId":72836961,"title":"How to Build Vue 3 Vite App for production","tags":["javascript","vue.js","production","vite"],"text":"Title: How to Build Vue 3 Vite App for production\nTags: javascript, vue.js, production, vite\nSource: Stack Overflow\n\nQuestion:\nI created a fresh vue project with the new version which includes vite init.\n\nWhen I run `npm run build` a `dist/` is created. But when I open `dist/index.html` inside the dist folder it doesn't show anything. My question is how can I build the app and run it without any command (Building for production). Thanks\n\n========================================\n\nCode:\n```text\nnpm run build\n```\n\n```text\ndist/\n```\n\n```text\ndist/index.html\n```\n\n```text\nnpm run preview\n```\n\n========================================\n\nComments:\n- You cannot build the app and run it without any command. It's how it works in the documentation. Or do you have any information that might be helpful for your project?\n- So when we run npm run preview is it loading the dist/index.html file?\n- Practically yes, though technically it's just serving everything in `dist`. However without running this, you're missing all the files except `dist&#47;index.html`, which is why you had the empty page.\n- Note that it's *technically* possible to run an app without this using `base: '.&#47;'`, but I wouldn't recommend it as you can't use more modern features that require a server (such as client side routing in the path).","metadata":{"transformedAt":"2026-08-18T18:33:46.435Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":35,"estimatedTokens":329}}546{"id":"stack-77346263","source":"stackoverflow","questionId":77346263,"title":"How to use $app/navigation inside the vitest unit test","tags":["reactjs","svelte","vite","sveltekit","vitest"],"text":"Title: How to use $app/navigation inside the vitest unit test\nTags: reactjs, svelte, vite, sveltekit, vitest\nSource: Stack Overflow\n\nQuestion:\nGetting this error in files where I am using $app/navigation:\n`Error: Failed to resolve import \"$app/navigation\" from \"src/utils/navigationUtils.js\". Does the file exist?`.\n\nHere is my setupTests.js file but now getting the same error in this file.\n\n```\nimport \"@testing-library/jest-dom\";\nimport { vi } from \"vitest\";\nimport * as navigation from \"$app/navigation\";\n\n// Mock SvelteKit runtime module $app/navigation\nvi.mock(\"$app/navigation\", () => ({\n afterNavigate: () => {},\n beforeNavigate: () => {},\n disableScrollHandling: () => {},\n goto: () => Promise.resolve(),\n invalidate: () => Promise.resolve(),\n invalidateAll: () => Promise.resolve(),\n prefetch: () => Promise.resolve(),\n prefetchRoutes: () => Promise.resolve(),\n}));\n```\n\nAfter this configration now getting:\n`Error: Failed to resolve import \"$app/navigation\" from \"setupTests.js\". Does the file exist?`\n\nI have tried to mock the `$app/navigation` module in setupTests.js file but no success.\n\n========================================\n\nTop Answer:\nThx this worked for me! @possum\nMy folder-structure is:\n\n**mocks**/app/navigation.js\n\nAnd this is the code i wrote to mock:\n\n\r\n\r\n\n```\nimport { vi } from 'vitest';\n\nconst goto = vi.fn();\nconst invalidate = vi.fn();\nconst invalidateAll = vi.fn();\n\nmodule.exports = {\n goto,\n invalidate,\n invalidateAll\n};\n```\n\n========================================\n\nCode:\n```text\nimport \"@testing-library/jest-dom\";\nimport { vi } from \"vitest\";\nimport * as navigation from \"$app/navigation\";\n\n\n// Mock SvelteKit runtime module $app/navigation\nvi.mock(\"$app/navigation\", () => ({\n  afterNavigate: () => {},\n  beforeNavigate: () => {},\n  disableScrollHandling: () => {},\n  goto: () => Promise.resolve(),\n  invalidate: () => Promise.resolve(),\n  invalidateAll: () => Promise.resolve(),\n  prefetch: () => Promise.resolve(),\n  prefetchRoutes: () => Promise.resolve(),\n}));\n```\n\n```text\nError: Failed to resolve import \"$app/navigation\" from \"src/utils/navigationUtils.js\". Does the file exist?\n```\n\n```text\nError: Failed to resolve import \"$app/navigation\" from \"setupTests.js\". Does the file exist?\n```\n\n```text\n$app/navigation\n```\n\n```text\nresolve: {\n    alias: {\n      $app: path.resolve(__dirname, '__mocks__/app')\n    }\n}\n```\n\n```text\n$xxx\n```\n\n```text\n$env\n```\n\n```text\n$app\n```\n\n```text\n$lib\n```\n\n```text\n__mocks__/xxx\n```\n\n```text\n__mocks__/app\n```\n\n```text\nnavigation.ts\n```\n\n```text\nvitest.config.ts\n```\n\n```js\nimport { vi } from 'vitest';\n\nconst goto = vi.fn();\nconst invalidate = vi.fn();\nconst invalidateAll = vi.fn();\n\nmodule.exports = {\n    goto,\n    invalidate,\n    invalidateAll\n};\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.435Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":147,"estimatedTokens":685}}547{"id":"stack-74120349","source":"stackoverflow","questionId":74120349,"title":"Building bundle for web in vite","tags":["javascript","vite"],"text":"Title: Building bundle for web in vite\nTags: javascript, vite\nSource: Stack Overflow\n\nQuestion:\nI am trying to move from Webpack to Vite. I am using the library mode, but every time I build it, I get node-based code in the built file. This is what I have so far:\n\n```\nimport {resolve} from 'path'\nimport {defineConfig, splitVendorChunkPlugin} from 'vite'\n\nexport default defineConfig(({mode}) => {\n return {\n plugins: [splitVendorChunkPlugin()],\n build: {\n emptyOutDir: false,\n minify: mode === \"dev\" ? false : 'terser',\n target: 'es2015',\n lib: {\n formats: ['cjs'],\n name: 'Spark2',\n entry: resolve(__dirname, 'src/app.ts'),\n },\n commonjsOptions: {\n include: [/node_modules/]\n },\n outDir: './static',\n rollupOptions: {\n output: {\n manualChunks: (id) => {\n if (id.includes('node_modules')) {\n return 'vendors';\n }\n },\n entryFileNames: mode === \"dev\" ? 'js/main.js' : 'js/main.min.js',\n chunkFileNames: mode === \"dev\" ? 'js/[name].js' : 'js/[name].min.js',\n assetFileNames: mode === \"dev\" ? '[ext]/[name].[ext]' : '[ext]/[name].min.[ext]',\n },\n }\n }\n }\n})\n```\n\nIt builds fine but in the browser, I get an error as:\n\n```\nUncaught ReferenceError: process is not defined\n at vendors.js:70:19\n```\n\nLooking into the code, I get a line something similar to `const EMPTY_OBJ = process.env.NODE_ENV !== \"production\" ? Object.freeze({}) : {};`\n\nHow should I build the bundle for the web?\n\n========================================\n\nTop Answer:\nanother solution you could try is to add the `nodePolyfills` plugin. A project I was working on that converts React to a Web Component was having issues with process being undefined in the browser. After importing\n\n```\nimport { nodePolyfills } from \"vite-plugin-node-polyfills\";\n```\n\nand adding nodePolyfills to the plugins array, the component would render correctly.\n\n```\n// vite.config.js\nplugins: [\n ...,\n nodePolyfills\n]\n```\n\n========================================\n\nCode:\n```text\nimport {resolve} from 'path'\nimport {defineConfig, splitVendorChunkPlugin} from 'vite'\n\nexport default defineConfig(({mode}) => {\n    return {\n        plugins: [splitVendorChunkPlugin()],\n        build: {\n            emptyOutDir: false,\n            minify: mode === \"dev\" ? false : 'terser',\n            target: 'es2015',\n            lib: {\n                formats: ['cjs'],\n                name: 'Spark2',\n                entry: resolve(__dirname, 'src/app.ts'),\n            },\n            commonjsOptions: {\n                include: [/node_modules/]\n            },\n            outDir: './static',\n            rollupOptions: {\n                output: {\n                    manualChunks: (id) => {\n                        if (id.includes('node_modules')) {\n                            return 'vendors';\n                        }\n                    },\n                    entryFileNames: mode === \"dev\" ? 'js/main.js' : 'js/main.min.js',\n                    chunkFileNames: mode === \"dev\" ? 'js/[name].js' : 'js/[name].min.js',\n                    assetFileNames: mode === \"dev\" ? '[ext]/[name].[ext]' : '[ext]/[name].min.[ext]',\n                },\n            }\n        }\n    }\n})\n```\n\n```text\nUncaught ReferenceError: process is not defined\n    at vendors.js:70:19\n```\n\n```text\nconst EMPTY_OBJ = process.env.NODE_ENV !== \"production\" ? Object.freeze({}) : {};\n```\n\n```text\n// removed for brevity\n        plugins: [splitVendorChunkPlugin()],\n        define: {\n            'process.env.NODE_ENV': JSON.stringify(mode),\n        },\n// removed for brevity\n```\n\n```text\ndefine\n```\n\n```text\nplugins\n```\n\n```js\nimport { nodePolyfills } from \"vite-plugin-node-polyfills\";\n```\n\n```js\n// vite.config.js\nplugins: [\n  ...,\n  nodePolyfills\n]\n```\n\n```text\nnodePolyfills\n```\n\n========================================\n\nComments:\n- vite.dev/guide/&hellip;\n- I had a very similar issue with a dependency directly using `process.env` (`@krakenjs&#47;zoid`) and I used a similar solution.\n- Hopefully this will be fixed somehow in future because this very feels like hack even the fact it works for me now. I don't understand how I am getting process.env.NODE_ENV references in my bundle, because when I build latest clean vue project there are non references. It would be very costly to find out, I already spend couple of hours but did not succeed :/\n- The deconstructed mode in `({ mode }) =>` might be an empty object so there's should be an fallback to read `process.env.NODE_ENV`.","metadata":{"transformedAt":"2026-08-18T18:33:46.435Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":163,"estimatedTokens":1097}}548{"id":"stack-71912584","source":"stackoverflow","questionId":71912584,"title":"vue3 and vite.js, docker build production failed \"Error: Could not resolve entry module (index.html).\"","tags":["docker","dockerfile","vuejs3","rollupjs","vite"],"text":"Title: vue3 and vite.js, docker build production failed \"Error: Could not resolve entry module (index.html).\"\nTags: docker, dockerfile, vuejs3, rollupjs, vite\nSource: Stack Overflow\n\nQuestion:\nI am trying to build a vue3 project with vite.js. I want to build it in a Dockerfile, but I get the following error.\n\n```\nvite v2.9.5 building for production...\n✓ 0 modules transformed.\nCould not resolve entry module (index.html).\nerror during build:\nError: Could not resolve entry module (index.html).\n at error (/panda-planner/frontend-planner/node_modules/rollup/dist/shared/rollup.js:198:30)\n at ModuleLoader.loadEntryModule (/panda-planner/frontend-planner/node_modules/rollup/dist/shared/rollup.js:22480:20)\n at async Promise.all (index 0)\nError response from daemon: The command '/bin/sh -c npm run build' returned a non-zero code: 1\nFailed to deploy ' Dockerfile: Dockerfile': Can't retrieve image ID from build stream\n```\n\nI have been looking for information on rollup but I don't understand what it is. Also my command `npm run build` works perfectly on my computer.\n\nCan someone help me, please?\n\nMy vite.config.js\n\n```\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\";\nimport eslintPlugin from \"vite-plugin-eslint\";\n\nconst path = require(\"path\");\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [vue(), eslintPlugin()],\n resolve: {\n alias: {\n \"@\": path.resolve(__dirname, \"src\"),\n },\n },\n});\n```\n\nMy Dockerfile\n\n```\n# Build backend application\nFROM node:14.19.1-alpine AS builder\nWORKDIR /panda-planner/backend-planner/\nCOPY /backend-planner/package*.json .\nRUN npm install\nCOPY . .\nRUN npm run build\nEXPOSE 1337\nCMD [\"npm\", \"run\", \"start\" ]\n\n# Build frontend application\nFROM builder as frontend\nWORKDIR /panda-planner/frontend-planner/\nCOPY /frontend-planner/package*.json .\nRUN npm install --legacy-peer-deps\nCOPY . .\nRUN npm run build\n\n# Setup nginx server for frontend\nFROM nginx:stable-alpine as nginx\nCOPY --from=frontend /frontend-planner/dist /usr//nginx/html\n#COPY ./default.conf /etc/nginx/conf.d/default.conf\nEXPOSE 80\nCMD [\"nginx\", \"-g\", \"daemon off;\" ]\n```\n\n========================================\n\nCode:\n```sh\nvite v2.9.5 building for production...\n✓ 0 modules transformed.\nCould not resolve entry module (index.html).\nerror during build:\nError: Could not resolve entry module (index.html).\n    at error (/panda-planner/frontend-planner/node_modules/rollup/dist/shared/rollup.js:198:30)\n    at ModuleLoader.loadEntryModule (/panda-planner/frontend-planner/node_modules/rollup/dist/shared/rollup.js:22480:20)\n    at async Promise.all (index 0)\nError response from daemon: The command '/bin/sh -c npm run build' returned a non-zero code: 1\nFailed to deploy '<unknown> Dockerfile: Dockerfile': Can't retrieve image ID from build stream\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\";\nimport eslintPlugin from \"vite-plugin-eslint\";\n\nconst path = require(\"path\");\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue(), eslintPlugin()],\n  resolve: {\n    alias: {\n      \"@\": path.resolve(__dirname, \"src\"),\n    },\n  },\n});\n```\n\n```text\n# Build backend application\nFROM node:14.19.1-alpine AS builder\nWORKDIR /panda-planner/backend-planner/\nCOPY /backend-planner/package*.json .\nRUN npm install\nCOPY . .\nRUN npm run build\nEXPOSE 1337\nCMD [\"npm\", \"run\", \"start\" ]\n\n# Build frontend application\nFROM builder as frontend\nWORKDIR /panda-planner/frontend-planner/\nCOPY /frontend-planner/package*.json .\nRUN npm install --legacy-peer-deps\nCOPY . .\nRUN npm run build\n\n# Setup nginx server for frontend\nFROM nginx:stable-alpine as nginx\nCOPY --from=frontend /frontend-planner/dist /usr/share/nginx/html\n#COPY ./default.conf /etc/nginx/conf.d/default.conf\nEXPOSE 80\nCMD [\"nginx\", \"-g\", \"daemon off;\" ]\n```\n\n```text\nnpm run build\n```\n\n```text\n# Build backend application\nFROM node:14.19.1-alpine AS builder\nWORKDIR /panda-planner/backend-planner/\nCOPY /backend-planner/package*.json .\nRUN npm install\nCOPY /backend-planner/ .\nRUN npm run build\nEXPOSE 1337\nCMD [\"npm\", \"run\", \"start\" ]\n\n# Build frontend application\nFROM builder AS frontend\nWORKDIR /panda-planner/frontend-planner/\nCOPY /frontend-planner/package*.json .\nRUN npm install --legacy-peer-deps\nCOPY /frontend-planner/ .\nRUN npm run build\n\n# Setup nginx server for frontend\nFROM nginx:stable-alpine AS nginx\nCOPY --from=frontend /panda-planner/frontend-planner/dist/ /usr/share/nginx/html/\n#COPY ./default.conf /etc/nginx/conf.d/default.conf\nEXPOSE 80\nCMD [\"nginx\", \"-g\", \"daemon off;\" ]\n```\n\n========================================\n\nComments:\n- There are many COPY commands here. Please specify which one was problematic.","metadata":{"transformedAt":"2026-08-18T18:33:46.435Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":169,"estimatedTokens":1175}}549{"id":"stack-76943080","source":"stackoverflow","questionId":76943080,"title":"2023 August: Error: @vitejs/plugin-vue requires vue (>=3.2.13) or @vue/compiler-sfc to be present in the dependency tree","tags":["vuejs3","vite","package.json","vue-cli"],"text":"Title: 2023 August: Error: @vitejs/plugin-vue requires vue (>=3.2.13) or @vue/compiler-sfc to be present in the dependency tree\nTags: vuejs3, vite, package.json, vue-cli\nSource: Stack Overflow\n\nQuestion:\n**Context**\n\nI am migrating a project from Vue 2 to Vue 3. I fixed all the breaking changes and syntax, the app worked. Before removing the vue compat mode, I had to do one more step: replace a Vue-2-only plugin with a similar Vue-3 plugin. In the process, I upgraded some packages, and now cannot run the app anymore.\n\n**Error**\n\nRunning `npm run serve` causes this console error:\n\n```\nERROR Error: @vitejs/plugin-vue requires vue (>=3.2.13) or @vue/compiler-sfc to be present in the dependency tree.\nError: @vitejs/plugin-vue requires vue (>=3.2.13) or @vue/compiler-sfc to be present in the dependency tree.\n```\n\nI still use Vue-CLI and never install Vite. In the `package.json`, `vue` is upgraded to the latest version 3.3.4. I don't understand why there is an error about vitejs and vue >= 3.2.13. Below is the full error message:\n\n```\nERROR Error: @vitejs/plugin-vue requires vue (>=3.2.13) or @vue/compiler-sfc to be present in the dependency tree.\nError: @vitejs/plugin-vue requires vue (>=3.2.13) or @vue/compiler-sfc to be present in the dependency tree.\n at Object. (-----HIDE FULL PATH DUE TO WORK RELATED FILES---\\MigratingToVue3\\client\\node_modules\\vue-loader\\dist\\compiler.js:14:15)\n at Module._compile (internal/modules/cjs/loader.js:1015:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)\n at Module.load (internal/modules/cjs/loader.js:879:32)\n at Function.Module._load (internal/modules/cjs/loader.js:724:14)\n at Module.require (internal/modules/cjs/loader.js:903:19)\n at require (internal/modules/cjs/helpers.js:74:18)\n at Object. (-----HIDE FULL PATH DUE TO WORK RELATED FILES---\\MigratingToVue3\\client\\node_modules\\vue-loader\\dist\\index.js:29:20)\n at Module._compile (internal/modules/cjs/loader.js:1015:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)\nnpm ERR! code ELIFECYCLE\nnpm ERR! errno 1\nnpm ERR! ams-client@1.1.134 serve: `vue-cli-service serve`\nnpm ERR! Exit status 1\nnpm ERR!\nnpm ERR! Failed at the ams-client@1.1.134 serve script.\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n```\n\n**Environment**\n\nI use `Node v12.19.0`, `npm v6.14.8` in this project, no change.\n\nThis is my `package.json` file:\n\n```\n{\n \"name\": \"client\",\n \"version\": \"1.1.134\",\n \"private\": true,\n \"scripts\": {\n \"serve\": \"vue-cli-service serve\",\n \"prebuild\": \"npm version patch\",\n \"build\": \"vue-cli-service build\",\n \"serve-dev\": \"vue-cli-service serve --mode dev\",\n \"serve-prod\": \"vue-cli-service serve --mode prod\",\n \"build-dev\": \"vue-cli-service build --mode dev\",\n \"build-prod\": \"vue-cli-service build --mode prod\",\n \"postbuild\": \"node configure.js\",\n \"lint\": \"vue-cli-service lint\",\n \"build:nobump\": \"vue-cli-service build\",\n \"deploy-dev\": \"cli-confirm \\\"Do you really want to deploy the application on DEV?\\\" && npm run build-dev && msdeploy --verb sync --source contentPath=dist --dest contentPath=---HIDE PATH DUE TO WORK---,ComputerName=---HIDE PATH DUE TO WORK---\",\n \"deploy-prod\": \"cli-confirm \\\"Do you really want to deploy the application on PRODUCTION?\\\" && npm run build-prod && msdeploy --verb sync --source contentPath=dist --dest contentPath=---HIDE PATH DUE TO WORK---,ComputerName=---HIDE PATH DUE TO WORK---\"\n },\n \"dependencies\": {\n \"@fortawesome/fontawesome-svg-core\": \"^1.2.36\",\n \"@fortawesome/free-solid-svg-icons\": \"^5.15.4\",\n \"@fortawesome/vue-fontawesome\": \"^3.0.3\",\n \"@vue/compat\": \"^3.3.4\", \n \"axios\": \"^0.22.0\",\n \"cli-confirm\": \"^1.0.1\",\n \"core-js\": \"^3.32.0\",\n \"d3\": \"^5.15.1\",\n \"dexie\": \"^3.2.4\",\n \"msdeploy\": \"^1.2.1\",\n \"npm\": \"^7.24.2\",\n \"sass\": \"^1.64.2\",\n \"vue\": \"^3.3.4\", \n \"vue-next\": \"0.0.1\",\n \"vue-router\": \"^4.0.0\",\n \"vue-swal\": \"^1.0.0\",\n \"vue2-editor\": \"^2.10.2\",\n \"vuex\": \"^4.0.0\"\n },\n \"devDependencies\": {\n \"@vue/cli-plugin-babel\": \"~5.0.8\",\n \"@vue/cli-plugin-eslint\": \"~5.0.8\",\n \"@vue/cli-plugin-router\": \"~5.0.8\",\n \"@vue/cli-plugin-vuex\": \"~5.0.8\",\n \"@vue/cli-service\": \"~5.0.8\",\n \"@vue/eslint-config-standard\": \"^5.1.2\",\n \"babel-eslint\": \"^10.1.0\",\n \"eslint\": \"^7.5.0\",\n \"eslint-plugin-import\": \"^2.28.0\",\n \"eslint-plugin-node\": \"^11.1.0\",\n \"eslint-plugin-promise\": \"^4.2.1\",\n \"eslint-plugin-standard\": \"^4.0.0\",\n \"eslint-plugin-vue\": \"^6.2.2\",\n \"sass-loader\": \"^10.1.0\",\n \"@vue/compiler-sfc\": \"^3.3.4\"\n }\n}\n```\n\n**What I tried**\n\nWithout success:\n\n- Copy-pasting the content of the `package.json` file and `package-lock.json` before upgrade, run `npm run serve`\n\n- Deleting the `node-modules` folder and the `package-lock.json`, clear cache `npm cache clean --force` and run `npm install`\n\n- Restarting computer, turning off and turning on the computer\n\nA similar question was asked, but none of the answers works for me.\n\nMy goal is just to get the app to work again like it did before all the upgrades. Any input would be greatly appreciated. Thank you so much!\n\n========================================\n\nTop Answer:\n```\nnpm install vue@latest @vue/compiler-sfc --save\n```\n\nand run\n\n```\nnpm run serve\n```\n\n========================================\n\nCode:\n```text\nERROR  Error: @vitejs/plugin-vue requires vue (>=3.2.13) or @vue/compiler-sfc to be present in the dependency tree.\nError: @vitejs/plugin-vue requires vue (>=3.2.13) or @vue/compiler-sfc to be present in the dependency tree.\n```\n\n```text\nERROR  Error: @vitejs/plugin-vue requires vue (>=3.2.13) or @vue/compiler-sfc to be present in the dependency tree.\nError: @vitejs/plugin-vue requires vue (>=3.2.13) or @vue/compiler-sfc to be present in the dependency tree.\n    at Object.<anonymous> (-----HIDE FULL PATH DUE TO WORK RELATED FILES---\\MigratingToVue3\\client\\node_modules\\vue-loader\\dist\\compiler.js:14:15)\n    at Module._compile (internal/modules/cjs/loader.js:1015:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)\n    at Module.load (internal/modules/cjs/loader.js:879:32)\n    at Function.Module._load (internal/modules/cjs/loader.js:724:14)\n    at Module.require (internal/modules/cjs/loader.js:903:19)\n    at require (internal/modules/cjs/helpers.js:74:18)\n    at Object.<anonymous> (-----HIDE FULL PATH DUE TO WORK RELATED FILES---\\MigratingToVue3\\client\\node_modules\\vue-loader\\dist\\index.js:29:20)\n    at Module._compile (internal/modules/cjs/loader.js:1015:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)\nnpm ERR! code ELIFECYCLE\nnpm ERR! errno 1\nnpm ERR! ams-client@1.1.134 serve: `vue-cli-service serve`\nnpm ERR! Exit status 1\nnpm ERR!\nnpm ERR! Failed at the ams-client@1.1.134 serve script.\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n```\n\n```text\n{\n  \"name\": \"client\",\n  \"version\": \"1.1.134\",\n  \"private\": true,\n  \"scripts\": {\n    \"serve\": \"vue-cli-service serve\",\n    \"prebuild\": \"npm version patch\",\n    \"build\": \"vue-cli-service build\",\n    \"serve-dev\": \"vue-cli-service serve --mode dev\",\n    \"serve-prod\": \"vue-cli-service serve --mode prod\",\n    \"build-dev\": \"vue-cli-service build --mode dev\",\n    \"build-prod\": \"vue-cli-service build --mode prod\",\n    \"postbuild\": \"node configure.js\",\n    \"lint\": \"vue-cli-service lint\",\n    \"build:nobump\": \"vue-cli-service build\",\n    \"deploy-dev\": \"cli-confirm \\\"Do you really want to deploy the application on DEV?\\\" && npm run build-dev && msdeploy --verb sync --source contentPath=dist --dest contentPath=---HIDE PATH DUE TO WORK---,ComputerName=---HIDE PATH DUE TO WORK---\",\n    \"deploy-prod\": \"cli-confirm \\\"Do you really want to deploy the application on PRODUCTION?\\\" && npm run build-prod && msdeploy --verb sync --source contentPath=dist --dest contentPath=---HIDE PATH DUE TO WORK---,ComputerName=---HIDE PATH DUE TO WORK---\"\n  },\n  \"dependencies\": {\n    \"@fortawesome/fontawesome-svg-core\": \"^1.2.36\",\n    \"@fortawesome/free-solid-svg-icons\": \"^5.15.4\",\n    \"@fortawesome/vue-fontawesome\": \"^3.0.3\",\n    \"@vue/compat\": \"^3.3.4\", <------ BEFORE UPGRADE: \"^3.1.0\" ------>\n    \"axios\": \"^0.22.0\",\n    \"cli-confirm\": \"^1.0.1\",\n    \"core-js\": \"^3.32.0\",\n    \"d3\": \"^5.15.1\",\n    \"dexie\": \"^3.2.4\",\n    \"msdeploy\": \"^1.2.1\",\n    \"npm\": \"^7.24.2\",\n    \"sass\": \"^1.64.2\",\n    \"vue\": \"^3.3.4\", <------ BEFORE UPGRADE: \"^3.1.0\" ------>\n    \"vue-next\": \"0.0.1\",\n    \"vue-router\": \"^4.0.0\",\n    \"vue-swal\": \"^1.0.0\",\n    \"vue2-editor\": \"^2.10.2\",\n    \"vuex\": \"^4.0.0\"\n  },\n  \"devDependencies\": {\n    \"@vue/cli-plugin-babel\": \"~5.0.8\",\n    \"@vue/cli-plugin-eslint\": \"~5.0.8\",\n    \"@vue/cli-plugin-router\": \"~5.0.8\",\n    \"@vue/cli-plugin-vuex\": \"~5.0.8\",\n    \"@vue/cli-service\": \"~5.0.8\",\n    \"@vue/eslint-config-standard\": \"^5.1.2\",\n    \"babel-eslint\": \"^10.1.0\",\n    \"eslint\": \"^7.5.0\",\n    \"eslint-plugin-import\": \"^2.28.0\",\n    \"eslint-plugin-node\": \"^11.1.0\",\n    \"eslint-plugin-promise\": \"^4.2.1\",\n    \"eslint-plugin-standard\": \"^4.0.0\",\n    \"eslint-plugin-vue\": \"^6.2.2\",\n    \"sass-loader\": \"^10.1.0\",\n    \"@vue/compiler-sfc\": \"^3.3.4\"\n  }\n}\n```\n\n```text\nnpm run serve\n```\n\n```text\npackage.json\n```\n\n```text\nvue\n```\n\n```text\nNode v12.19.0\n```\n\n```text\nnpm v6.14.8\n```\n\n```text\npackage.json\n```\n\n```text\npackage.json\n```\n\n```text\npackage-lock.json\n```\n\n```text\nnpm run serve\n```\n\n```text\nnode-modules\n```\n\n```text\npackage-lock.json\n```\n\n```text\nnpm cache clean --force\n```\n\n```text\nnpm install\n```\n\n```text\nnpm i vue@3.2.26\n```\n\n```text\n\"devDependencies\": {\n    ...\n    \"@vue/compiler-sfc\": \"npm:@vue/compiler-sfc@^3\",\n    ...\n}\n```\n\n```text\n\"dependencies\":\n    { ... },\n\"overrides\": \n    { \"vue\": \"3\" },\n```\n\n```text\nnpm install vue@latest @vue/compiler-sfc --save\n```\n\n```text\nnpm run serve\n```\n\n========================================\n\nComments:\n- Hi, thank you for the comment! Upgrade to the latest Vue 3.3.4 does not work for me, but upgrade specifically to vue@3.2.26 works. Maybe Vue @3.3.4 is not compatible with my Node v12.","metadata":{"transformedAt":"2026-08-18T18:33:46.436Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":306,"estimatedTokens":2487}}550{"id":"stack-72497273","source":"stackoverflow","questionId":72497273,"title":"How to initialize firebase in vite and vue?","tags":["javascript","firebase","vuejs3","vite"],"text":"Title: How to initialize firebase in vite and vue?\nTags: javascript, firebase, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI am new in vite. I am trying to initialize the firebase app. but I am getting errors like below\n\nFirebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()\n\nI created a file name firebase.ts but i am not really sure where can i include this to initialize firebase globally.\n\nhttps://i.sstatic.net/lxw9V.png\n\n```\n\nimport { ref } from 'vue'\nimport { useRouter } from 'vue-router'\nimport { useHead } from '@vueuse/head'\n\nimport { isDark } from '/@src/state/darkModeState'\nimport useNotyf from '/@src/composable/useNotyf'\nimport sleep from '/@src/utils/sleep'\nimport { getAuth, signInWithEmailAndPassword } from '@firebase/auth'\n\nconst isLoading = ref(false)\nconst router = useRouter()\nconst notif = useNotyf()\n\nconst username = ref('')\nconst password = ref('')\n\nconst handleLogin = async () => {\n if (!isLoading.value) {\n isLoading.value = true\n signInWithEmailAndPassword(getAuth(), username.value, password.value)\n .then((user) => {\n isLoading.value = false\n router.push({ name: 'sidebar-dashboards-course' })\n })\n .catch((err) => {\n isLoading.value = false\n notif.error(\n 'There is no user record corresponding to this identifier. The user may be deleted'\n )\n })\n }\n}\n```\n\nAny solution appreciated!\n\n========================================\n\nCode:\n```text\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\nimport { useRouter } from 'vue-router'\nimport { useHead } from '@vueuse/head'\n\nimport { isDark } from '/@src/state/darkModeState'\nimport useNotyf from '/@src/composable/useNotyf'\nimport sleep from '/@src/utils/sleep'\nimport { getAuth, signInWithEmailAndPassword } from '@firebase/auth'\n\nconst isLoading = ref(false)\nconst router = useRouter()\nconst notif = useNotyf()\n\nconst username = ref('')\nconst password = ref('')\n\nconst handleLogin = async () => {\n  if (!isLoading.value) {\n    isLoading.value = true\n    signInWithEmailAndPassword(getAuth(), username.value, password.value)\n      .then((user) => {\n        isLoading.value = false\n        router.push({ name: 'sidebar-dashboards-course' })\n      })\n      .catch((err) => {\n        isLoading.value = false\n        notif.error(\n          'There is no user record corresponding to this identifier. The user may be deleted'\n        )\n      })\n  }\n}\n```\n\n```text\nimport { initializeApp } from \"firebase/app\";\nimport { getAuth } from \"firebase/auth\";\nimport { getFirestore } from \"firebase/firestore\";\nimport { getStorage } from \"firebase/storage\";\n\nconst firebaseConfig = {...};\n\nconst app = initializeApp(firebaseConfig);\n\nconst auth = getAuth(app);\nconst db = getFirestore(app);\nconst storage = getStorage(app);\n\nexport { auth, db, storage };\n```\n\n```text\nimport { auth } from \"../path/to/firebase.ts\" // update the path as per your dir structure\n\n// usage: instead of getAuth() here\nawait signInWithEmailAndPassword(auth, username.value, password.value)\n```\n\n```text\nfirebase.ts\n```\n\n```text\ncompat\n```\n\n```text\nfirebase.ts\n```\n\n```text\nget[Service]()\n```\n\n========================================\n\nComments:\n- Can you the any file where you are importing these? Also do ensure all the credentials are correct.\n- I don't want to initialize in every single file. I want this to be global","metadata":{"transformedAt":"2026-08-18T18:33:46.436Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":135,"estimatedTokens":827}}551{"id":"stack-72980476","source":"stackoverflow","questionId":72980476,"title":"Build separate CSS files using Tailwindcss and laravel-vite-plugin","tags":["laravel","tailwind-css","vite"],"text":"Title: Build separate CSS files using Tailwindcss and laravel-vite-plugin\nTags: laravel, tailwind-css, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to build two separate CSS files using Tailwindcss, Laravel and vite-plugin.\n\nThe two css files use different configuration, but I have no idea how specify the correct **tailwind.config.js** for each builds.\n\n- **app.css** should use **tailwind.config.js**\n\n- **mail.css** should use **tailwind-mail.config.js**\n\n**vite.config.js**\n\n```\nimport { defineConfig } from \"vite\"\nimport laravel from \"laravel-vite-plugin\"\n\nexport default defineConfig({\n plugins: [\n laravel({\n input: [\"resources/css/app.css\", \"resources/js/app.js\", \"resources/css/mail.css\"]\n refresh: true,\n })\n ]\n})\n```\n\n**postcss.config.js**\n\n```\nmodule.exports = {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n}\n```\n\n**tailwind.config.js**\n\n```\nmodule.exports = {\n content: [\n './vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php',\n './vendor/laravel/jetstream/**/*.blade.php',\n './storage/framework/views/*.php',\n './resources/views/**/*.blade.php',\n ],\n theme: {},\n plugins: [require(\"@tailwindcss/forms\"), require(\"@tailwindcss/typography\")],\n}\n```\n\n**tailwind-mail.config.js**\n\n```\nmodule.exports = {\n content: [\"./resources/views/mails/**/*.blade.php\"],\n theme: {},\n plugins: [require(\"@tailwindcss/typography\")],\n}\n```\n\n========================================\n\nCode:\n```js\nimport { defineConfig } from \"vite\"\nimport laravel from \"laravel-vite-plugin\"\n\nexport default defineConfig({\n    plugins: [\n        laravel({\n            input: [\"resources/css/app.css\", \"resources/js/app.js\", \"resources/css/mail.css\"]\n            refresh: true,\n        })\n    ]\n})\n```\n\n```js\nmodule.exports = {\n  plugins: {\n    tailwindcss: {},\n    autoprefixer: {},\n  },\n}\n```\n\n```js\nmodule.exports = {\n    content: [\n        './vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php',\n        './vendor/laravel/jetstream/**/*.blade.php',\n        './storage/framework/views/*.php',\n        './resources/views/**/*.blade.php',\n    ],\n    theme: {},\n    plugins: [require(\"@tailwindcss/forms\"), require(\"@tailwindcss/typography\")],\n}\n```\n\n```js\nmodule.exports = {\n    content: [\"./resources/views/mails/**/*.blade.php\"],\n    theme: {},\n    plugins: [require(\"@tailwindcss/typography\")],\n}\n```\n\n```css\n@config \"./tailwind.config.js\";\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n```css\n@config \"./tailwind.mail.config.js\";\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n```js\nimport { defineConfig } from \"vite\"\nimport laravel from \"laravel-vite-plugin\"\n\nexport default defineConfig({\n    plugins: [\n        laravel({\n            input: [\"resources/css/app.css\", \"resources/js/app.js\", \"resources/css/mail.css\"]\n            refresh: true,\n        })\n    ]\n})\n```\n\n```text\n@config <filename>\n```\n\n========================================\n\nComments:\n- Trying to also figure this out. Haven't been able to find anything online related to vite since the original article was for webpack. Please create an answer if you managed to figure it out.\n- @m33ts4k0z Sorry, I haven't figured this out yet.\n- @m33ts4k0z I think the release of Tailwind CSS 3.2 will solve this issue :)\n- @config \"./tailwind.mail.config.js\"; missing semicolon","metadata":{"transformedAt":"2026-08-18T18:33:46.436Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":151,"estimatedTokens":830}}552{"id":"stack-76021897","source":"stackoverflow","questionId":76021897,"title":"I am getting 'Uncaught TypeError: props.handleSelect is not a function'","tags":["reactjs","tailwind-css","vite","react-props","react-functional-component"],"text":"Title: I am getting 'Uncaught TypeError: props.handleSelect is not a function'\nTags: reactjs, tailwind-css, vite, react-props, react-functional-component\nSource: Stack Overflow\n\nQuestion:\nI am trying to create custom components using TailwindCSS and Vite. While passing a function I get the error 'Uncaught TypeError: props.handleSelect is not a function'.\n\n```\nconst Navbar = () => {\n const handleSelect = (option) => {\n option == \"Home\"\n ? console.log(option)\n : option == \"View Submissions\"\n ? console.log(option)\n : console.log(option);\n };\n\n return (\n \n {\n navigate(\"/home\");\n }}\n className={`pl-[20px] font-semibold hover:cursor-pointer`}\n >\n MICROTEK\n \n \n \n \n \n );\n};\n```\n\nFor Menu2\n\n```\nconst Menu2 = (props) => {\n const [click, setClick] = useState(false);\n\n return (\n \n {\n setClick(!click);\n }}\n onChange={props.onChange}\n className={\n `${props.className} ` +\n ` flex min-w-[100px] flex-row items-center justify-between rounded font-semibold ${\n click ? \"bg-primary-700\" : \"bg-none\"\n } border-primary-700 hover:bg-primary-700 border-[2px] pl-[10px]`\n }\n >\n {props.placeholder}\n {click == true ? (\n \n ) : (\n \n )}\n \n\n \n {props.options?.map((options) => {\n return (\n {\n props.handleSelect(options);\n }}\n >\n {options}\n \n );\n })}\n \n \n );\n};\n\nexport default Menu2;\n```\n\nI've looked at other answers and they mentioned using `props` or `{handleSelect}` both of which did not work.\n\n========================================\n\nTop Answer:\nYou're passing the `handleSelect` prop like this - `onSelect={handleSelect}`, so in the `Menu2` component you can access it like `props.onSelect(options);`.\n\n========================================\n\nCode:\n```text\nconst Navbar = () => {\n  const handleSelect = (option) => {\n    option == \"Home\"\n      ? console.log(option)\n      : option == \"View Submissions\"\n      ? console.log(option)\n      : console.log(option);\n  };\n\n  return (\n    <div\n      className={`bg-primary-700 flex min-h-[50px] min-w-[100vh] flex-row items-center justify-between p-[5px] text-white `}\n    >\n      <div\n        onClick={() => {\n          navigate(\"/home\");\n        }}\n        className={`pl-[20px] font-semibold hover:cursor-pointer`}\n      >\n        MICROTEK\n      </div>\n      <div className={`mr-[10px] flex flex-row`}>\n        <Menu2\n          placeholder=\"Navigate\"\n          options={[\"View Submissions\", \"Home\"]}\n          onSelect={handleSelect}\n        ></Menu2>\n      </div>\n    </div>\n  );\n};\n```\n\n```text\nconst Menu2 = (props) => {\n  const [click, setClick] = useState(false);\n\n  return (\n    <div>\n      <button\n        name={props.name}\n        id={props.id}\n        required={props.required}\n        value={props.value}\n        onClick={() => {\n          setClick(!click);\n        }}\n        onChange={props.onChange}\n        className={\n          `${props.className} ` +\n          ` flex min-w-[100px] flex-row items-center  justify-between rounded font-semibold ${\n            click ? \"bg-primary-700\" : \"bg-none\"\n          } border-primary-700 hover:bg-primary-700 border-[2px] pl-[10px]`\n        }\n      >\n        {props.placeholder}\n        {click == true ? (\n          <img\n            src={upIcon}\n            style={{ marginTop: \"2px\", margin: \"9px\" }}\n            height=\"10px\"\n            width=\"20px\"\n          ></img>\n        ) : (\n          <img\n            src={downIcon}\n            style={{ marginTop: \"2px\", margin: \"9px\" }}\n            height=\"10px\"\n            width=\"20px\"\n          ></img>\n        )}\n      </button>\n\n      <div\n        className={`${\n          click == true ? \"\" : \"hidden\"\n        }  animate-ease-out shadow-primary-700 absolute min-h-[40px] min-w-[100px] max-w-[200px] rounded bg-white text-black shadow-md`}\n      >\n        {props.options?.map((options) => {\n          return (\n            <div\n              className=\"hover:bg-primary-700 p-[10px] hover:text-white \"\n              key={options}\n              onClick={() => {\n                props.handleSelect(options);\n              }}\n            >\n              {options}\n            </div>\n          );\n        })}\n      </div>\n    </div>\n  );\n};\n\nexport default Menu2;\n```\n\n```text\nprops\n```\n\n```text\n{handleSelect}\n```\n\n```text\nconst Menu2 = (props) => {\n  const [click, setClick] = useState(false);\n  //this will indicate which props are getting passed\n  console.log(props);  \n\n  ...\n}\n```\n\n```text\n<div className={`mr-[10px] flex flex-row`}>\n    <Menu2\n      placeholder=\"Navigate\"\n      options={[\"View Submissions\", \"Home\"]}\n      handleSelect={(option) => handleSelect(option)}\n    ></Menu2>\n  </div>\n```\n\n```text\n{props.options?.map((options) => {\n        return (\n        <div\n          className=\"hover:bg-primary-700 p-[10px] hover:text-white \"\n          key={options}\n          onClick={() => props.handleSelect(options)}\n         >\n          {options}\n        </div>\n      );\n    })}\n```\n\n```text\nconsole.log(props)\n```\n\n```text\nMenu.js\n```\n\n```text\nhandleSelect\n```\n\n```text\nhandleSelect\n```\n\n```text\nprop\n```\n\n```text\nsame name\n```\n\n```text\noption\n```\n\n```text\nhandleSelect\n```\n\n```text\nonSelect={handleSelect}\n```\n\n```text\nMenu2\n```\n\n```text\nprops.onSelect(options);\n```\n\n========================================\n\nComments:\n- I have tried `props.onSelect(options)` it shows the same error.\n- Make sure you access the prop by the same name as you pass it. To debug, you can console.log(props) in the Menu2 component to inspect them.\n- Thanks! That worked. I should have named the prop correctly.","metadata":{"transformedAt":"2026-08-18T18:33:46.436Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":282,"estimatedTokens":1362}}553{"id":"stack-71527810","source":"stackoverflow","questionId":71527810,"title":"Vite appending assets path to image URLs","tags":["tailwind-css","vite"],"text":"Title: Vite appending assets path to image URLs\nTags: tailwind-css, vite\nSource: Stack Overflow\n\nQuestion:\nUsing Vite/React/Tailwind, I am trying to set dev/prod workflow so that images stored in 'public' directory has the correct path when deployed to gh-pages. Below is my Tailwind config starting point where 'backgroundImages' property is referencing an image file stored in 'public'.\n\n\r\n\r\n\n```\nmodule.exports = {\n mode:'jit',\n content: [\"./src/**/*.{html,jsx}\"],\n theme: {\n screens: {\n sm: '480px',\n md: '768px',\n lg: '976px',\n xl: '1440px',\n },\n colors: {\n 'splash-hex': '#6BD1D2',\n 'splash-rgba': 'rgba(107, 209, 210,1.0)',\n 'splash-hsla': 'hsla(181, 53%, 62%, 1.0)',\n },\n fontFamily: {\n sans: ['Graphik', 'sans-serif'],\n serif: ['Merriweather', 'serif'],\n },\n backgroundImages:{\n 'default':'url(\"./10475996-3x2-940x627.jpeg\")'\n },\n extend: {\n spacing: {\n '128': '32rem',\n '144': '36rem',\n },\n borderRadius: {\n '4xl': '2rem',\n }\n }\n },\n prefix: 'tw-',\n plugins: [],\n}\n```\n\n\r\n\r\n\r\n\nIn dev this works fine.\n\n`http://localhost:3000/10475996-3x2-940x627.jpeg`\n\nIn 'dist' folder, it looks correct as well when 'build' is run.\n\nhttps://i.sstatic.net/r1lHE.png\n\nWhen deployed to gh-pages, the path changes to `/assets/` and the image is no longer served from root as I expected according to Vite.\n\n`https://unevenartwork.com/assets/10475996-3x2-940x627.jpeg`\n\nIs there a configuration that would suppress the `/assets/` on deploy or another solution?\n\n========================================\n\nCode:\n```html\nmodule.exports = {\n  mode:'jit',\n  content: [\"./src/**/*.{html,jsx}\"],\n  theme: {\n    screens: {\n      sm: '480px',\n      md: '768px',\n      lg: '976px',\n      xl: '1440px',\n    },\n    colors: {\n      'splash-hex': '#6BD1D2',\n      'splash-rgba': 'rgba(107, 209, 210,1.0)',\n      'splash-hsla': 'hsla(181, 53%, 62%, 1.0)',\n    },\n    fontFamily: {\n      sans: ['Graphik', 'sans-serif'],\n      serif: ['Merriweather', 'serif'],\n    },\n    backgroundImages:{\n      'default':'url(\"./10475996-3x2-940x627.jpeg\")'\n    },\n    extend: {\n      spacing: {\n        '128': '32rem',\n        '144': '36rem',\n      },\n      borderRadius: {\n        '4xl': '2rem',\n      }\n    }\n  },\n  prefix: 'tw-',\n  plugins: [],\n}\n```\n\n```text\nhttp://localhost:3000/10475996-3x2-940x627.jpeg\n```\n\n```text\n/assets/\n```\n\n```text\nhttps://unevenartwork.com/assets/10475996-3x2-940x627.jpeg\n```\n\n```text\n/assets/\n```\n\n```text\nbuild\n```\n\n```text\ndeploy\n```\n\n```text\nsrc/img\n```\n\n```text\n../img/10475996-3x2-940x627.jpeg\n```\n\n```text\n./img/10475996-3x2-940x627.jpeg\n```\n\n```text\nimg\n```\n\n```text\nsrc\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.436Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":150,"estimatedTokens":644}}554{"id":"stack-67643893","source":"stackoverflow","questionId":67643893,"title":"Vite JS / Vue 3 / SSR: ReferenceError window is not defined","tags":["vue.js","server-side-rendering","vite"],"text":"Title: Vite JS / Vue 3 / SSR: ReferenceError window is not defined\nTags: vue.js, server-side-rendering, vite\nSource: Stack Overflow\n\nQuestion:\nI am using Vite JS with Vue 3 for a single page application with server side rendering.\n\nI know that the JS that can only execute on client side must be done on hydration, but is it possible to do so with packages?\n\nMy situation is that I want to be able to use Headless UI (for Tailwind UI) and it works fine as long as the app is launched as a Single Page App. When it is launched with SSR, this error occurs:\n\n```\n[Vue warn]: Unhandled error during execution of setup function\n\nat \nReferenceError: window is not defined\n at useWindowEvent (C:\\test\\node_modules\\.pnpm\\@headlessui+vue@1.2.0_vue@3.0.11\\node_modules\\@headlessui\\vue\\dist\\headlessui.cjs.development.js:408:3)\n at useFocusTrap (C:\\test\\node_modules\\.pnpm\\@headlessui+vue@1.2.0_vue@3.0.11\\node_modules\\@headlessui\\vue\\dist\\headlessui.cjs.development.js:486:3)\n at setup (C:\\test\\node_modules\\.pnpm\\@headlessui+vue@1.2.0_vue@3.0.11\\node_modules\\@headlessui\\vue\\dist\\headlessui.cjs.development.js:1052:5)\n at callWithErrorHandling (C:\\test\\node_modules\\.pnpm\\@vue+runtime-core@3.0.11\\node_modules\\@vue\\runtime-core\\dist\\runtime-core.cjs.js:156:22)\n at setupStatefulComponent (C:\\test\\node_modules\\.pnpm\\@vue+runtime-core@3.0.11\\node_modules\\@vue\\runtime-core\\dist\\runtime-core.cjs.js:6488:29)\n at setupComponent (C:\\test\\node_modules\\.pnpm\\@vue+runtime-core@3.0.11\\node_modules\\@vue\\runtime-core\\dist\\runtime-core.cjs.js:6449:11)\n at renderComponentVNode (C:\\test\\node_modules\\.pnpm\\@vue+server-renderer@3.0.11_vue@3.0.11\\node_modules\\@vue\\server-renderer\\dist\\server-renderer.cjs.js:160:17)\n at renderVNode (C:\\test\\node_modules\\.pnpm\\@vue+server-renderer@3.0.11_vue@3.0.11\\node_modules\\@vue\\server-renderer\\dist\\server-renderer.cjs.js:263:22)\n at renderComponentSubTree (C:\\test\\node_modules\\.pnpm\\@vue+server-renderer@3.0.11_vue@3.0.11\\node_modules\\@vue\\server-renderer\\dist\\server-renderer.cjs.js:228:13)\n at renderComponentVNode (C:\\test\\node_modules\\.pnpm\\@vue+server-renderer@3.0.11_vue@3.0.11\\node_modules\\@vue\\server-renderer\\dist\\server-renderer.cjs.js:173:16)\n```\n\nI understand the error comes for the window property not being accessible on the server side, but this is setup by the package itself.\n\nIs there anyway to tell Vite JS SSR to not execute the JS on that package unless it's on the client side?\n\nHere is the content of the vue component that causes the error (on SSR execution only, Dialog is coming from Headless UI):\n\n```\n\n \n \n \n TEST\n \n \n \n\nimport { ref } from 'vue'\nimport { Dialog, TransitionRoot } from '@headlessui/vue'\n\nexport default {\n components: {\n Dialog,\n TransitionRoot\n },\n setup() {\n const open = ref(true)\n\n return {\n open,\n }\n },\n}\n\n```\n\nPS: I used this boilerplate project if you need reference for config: https://github.com/frandiox/vitesse-ssr-template\n\n========================================\n\nTop Answer:\nI was having similar issue in Vue2\ni was actually trying to use apexchart and after build, i get `Reference error window is not defined`\nwhat i did was i installed **vue-client-only**\nthen in my entry file i added\n\n```\nif (typeof window !== 'undefined') {\n const VueApexCharts = require('vue-apexcharts')\n Vue.component('ApexChart', VueApexCharts)\n }\n```\n\nand i wrapped this with the component\n\n```\n\n \n \n \n \n \n\nimport ClientOnly from 'vue-apexcharts'\nexport default {\n components: {\nClientOnly\n}}\n\n```\n\n========================================\n\nCode:\n```text\n[Vue warn]: Unhandled error during execution of setup function\n\n\nat <Dialog as=\"div\" static=\"\" class=\"fixed z-10 inset-0 overflow-y-auto\"  ... >\nReferenceError: window is not defined\n    at useWindowEvent (C:\\test\\node_modules\\.pnpm\\@headlessui+vue@1.2.0_vue@3.0.11\\node_modules\\@headlessui\\vue\\dist\\headlessui.cjs.development.js:408:3)\n    at useFocusTrap (C:\\test\\node_modules\\.pnpm\\@headlessui+vue@1.2.0_vue@3.0.11\\node_modules\\@headlessui\\vue\\dist\\headlessui.cjs.development.js:486:3)\n    at setup (C:\\test\\node_modules\\.pnpm\\@headlessui+vue@1.2.0_vue@3.0.11\\node_modules\\@headlessui\\vue\\dist\\headlessui.cjs.development.js:1052:5)\n    at callWithErrorHandling (C:\\test\\node_modules\\.pnpm\\@vue+runtime-core@3.0.11\\node_modules\\@vue\\runtime-core\\dist\\runtime-core.cjs.js:156:22)\n    at setupStatefulComponent (C:\\test\\node_modules\\.pnpm\\@vue+runtime-core@3.0.11\\node_modules\\@vue\\runtime-core\\dist\\runtime-core.cjs.js:6488:29)\n    at setupComponent (C:\\test\\node_modules\\.pnpm\\@vue+runtime-core@3.0.11\\node_modules\\@vue\\runtime-core\\dist\\runtime-core.cjs.js:6449:11)\n    at renderComponentVNode (C:\\test\\node_modules\\.pnpm\\@vue+server-renderer@3.0.11_vue@3.0.11\\node_modules\\@vue\\server-renderer\\dist\\server-renderer.cjs.js:160:17)\n    at renderVNode (C:\\test\\node_modules\\.pnpm\\@vue+server-renderer@3.0.11_vue@3.0.11\\node_modules\\@vue\\server-renderer\\dist\\server-renderer.cjs.js:263:22)\n    at renderComponentSubTree (C:\\test\\node_modules\\.pnpm\\@vue+server-renderer@3.0.11_vue@3.0.11\\node_modules\\@vue\\server-renderer\\dist\\server-renderer.cjs.js:228:13)\n    at renderComponentVNode (C:\\test\\node_modules\\.pnpm\\@vue+server-renderer@3.0.11_vue@3.0.11\\node_modules\\@vue\\server-renderer\\dist\\server-renderer.cjs.js:173:16)\n```\n\n```text\n<template>\n  <TransitionRoot as=\"template\" :show=\"open\">\n    <Dialog as=\"div\" static class=\"fixed z-10 inset-0 overflow-y-auto\" @close=\"open = false\" :open=\"open\">\n      <div class=\"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0\">\n        TEST\n      </div>\n    </Dialog>\n  </TransitionRoot>\n</template>\n\n<script>\nimport { ref } from 'vue'\nimport { Dialog, TransitionRoot } from '@headlessui/vue'\n\nexport default {\n  components: {\n    Dialog,\n    TransitionRoot\n  },\n  setup() {\n    const open = ref(true)\n\n    return {\n      open,\n    }\n  },\n}\n</script>\n```\n\n```text\nlet headlessui\nif (process.browser) headlessui= require('@headlessui/vue')\n```\n\n```text\n<client-only>\n    <TransitionRoot as=\"template\" :show=\"open\">\n        <Dialog as=\"div\" static class=\"fixed z-10 inset-0 overflow-y-auto\" @close=\"open = false\" :open=\"open\">\n          <div class=\"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text- center sm:block sm:p-0\">\n            TEST\n          </div>\n        </Dialog>\n     </TransitionRoot>\n<client-only>\n```\n\n```text\n<client-only></client-only>\n```\n\n```text\nif (typeof window !== 'undefined') {\n    const VueApexCharts = require('vue-apexcharts')\n    Vue.component('ApexChart', VueApexCharts)\n  }\n```\n\n```text\n<template>\n    <client-only>\n                <div id=\"chart\">\n                  <apex-chart type=\"radar\" height=\"350\" :options=\"chartOptions\" :series=\"series\"></apex-chart>\n                </div>\n    </client-only>\n</template>\n<script>\nimport ClientOnly from 'vue-apexcharts'\nexport default {\n  components: {\nClientOnly\n}}\n</script>\n```\n\n```text\nReference error window is not defined\n```\n\n========================================\n\nComments:\n- But that means I wouldn't be able to use the components at all on SSR right? Like, I want them to still display on SSR, just not to execute JS unless in client?\n- you cant separate js and template of components. they work together. check which components are only executable on the client side and only put them to client-only tag. other components still can render on the server side","metadata":{"transformedAt":"2026-08-18T18:33:46.436Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":204,"estimatedTokens":1839}}555{"id":"stack-79423511","source":"stackoverflow","questionId":79423511,"title":"Integrating shadcn/ui with Tailwind CSS v4 in a Tauri Application Using Vite and React","tags":["javascript","tailwind-css","vite","tauri","shadcnui"],"text":"Title: Integrating shadcn/ui with Tailwind CSS v4 in a Tauri Application Using Vite and React\nTags: javascript, tailwind-css, vite, tauri, shadcnui\nSource: Stack Overflow\n\nQuestion:\nI'm developing a Tauri application with Vite and React and aim to integrate shadcn/ui using Tailwind CSS version 4. However, I'm encountering the following error during setup:\n\ncommand used:\n\n```\npnpm dlx shadcn@latest init\n```\n\n```\nProgress: resolved 168, reused 96, downloaded 72, added 168, done\n✔ Preflight checks.\n✔ Verifying framework. Found Vite.\n✖ Validating Tailwind CSS.\n✖ Validating import alias.\n```\n\nCurrent Configuration:\n\ntsconfig.json:\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"ES2020\",\n \"useDefineForClassFields\": true,\n \"lib\": [\"ES2020\", \"DOM\", \"DOM.Iterable\"],\n \"module\": \"ESNext\",\n \"skipLibCheck\": true,\n \"moduleResolution\": \"bundler\",\n \"allowImportingTsExtensions\": true,\n \"resolveJsonModule\": true,\n \"isolatedModules\": true,\n \"noEmit\": true,\n \"jsx\": \"react-jsx\",\n \"strict\": true,\n \"noUnusedLocals\": true,\n \"noUnusedParameters\": true,\n \"noFallthroughCasesInSwitch\": true\n },\n \"include\": [\"src\"],\n \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\ntsconfig.node.json:\n\n```\n{\n \"compilerOptions\": {\n \"composite\": true,\n \"skipLibCheck\": true,\n \"module\": \"ESNext\",\n \"moduleResolution\": \"bundler\",\n \"allowSyntheticDefaultImports\": true,\n \"baseUrl\": \".\",\n \"paths\": {\n \"@/*\": [\"./src/*\"]\n }\n },\n \"include\": [\"vite.config.ts\"]\n}\n```\n\nvite.config.ts:\n\n```\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport tailwindcss from \"@tailwindcss/vite\";\nimport path from \"path\";\n\nconst host = process.env.TAURI_DEV_HOST;\n\nexport default defineConfig(async () => ({\n plugins: [react(), tailwindcss()],\n resolve: {\n alias: {\n \"@\": path.resolve(__dirname, \"./src\"),\n },\n },\n clearScreen: false,\n server: {\n port: 1420,\n strictPort: true,\n host: host || false,\n hmr: host\n ? {\n protocol: \"ws\",\n host,\n port: 1421,\n }\n : undefined,\n watch: {\n ignored: [\"**/src-tauri/**\"],\n },\n },\n}));\n```\n\n**Assumptions and Issues:**\n\n**Tailwind CSS Configuration:**\n\nI assumed that with Tailwind CSS version 4, a separate `tailwind.config.js` file might not be necessary. However, the error suggests that the absence of this configuration is causing issues.\n\n**Import Alias:**\n\nThe shadcn/ui installation guide mentions setting an import alias. Despite configuring aliases in `tsconfig.json` and `tsconfig.node.json`, the validation fails, indicating that the alias might not be recognized.\n\n**Request for Assistance:**\n\nCould someone provide guidance on the following:\n\n**Is a `tailwind.config.js` file required with Tailwind CSS version 4?**\n\nIf so, what should it include to ensure proper configuration?\n\n**How can I correctly set up the import alias to be compatible with shadcn/ui?**\n\nAre there specific configurations needed in the `tsconfig` files or elsewhere?\n\n**Are there additional steps or configurations necessary to integrate shadcn/ui with a Tauri application using Vite and React?**\n\nAny insights, examples, or resources would be greatly appreciated.\n\n========================================\n\nCode:\n```text\npnpm dlx shadcn@latest init\n```\n\n```text\nProgress: resolved 168, reused 96, downloaded 72, added 168, done\n✔ Preflight checks.\n✔ Verifying framework. Found Vite.\n✖ Validating Tailwind CSS.\n✖ Validating import alias.\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"target\": \"ES2020\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"ES2020\", \"DOM\", \"DOM.Iterable\"],\n    \"module\": \"ESNext\",\n    \"skipLibCheck\": true,\n    \"moduleResolution\": \"bundler\",\n    \"allowImportingTsExtensions\": true,\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\",\n    \"strict\": true,\n    \"noUnusedLocals\": true,\n    \"noUnusedParameters\": true,\n    \"noFallthroughCasesInSwitch\": true\n  },\n  \"include\": [\"src\"],\n  \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"skipLibCheck\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"bundler\",\n    \"allowSyntheticDefaultImports\": true,\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@/*\": [\"./src/*\"]\n    }\n  },\n  \"include\": [\"vite.config.ts\"]\n}\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport tailwindcss from \"@tailwindcss/vite\";\nimport path from \"path\";\n\nconst host = process.env.TAURI_DEV_HOST;\n\nexport default defineConfig(async () => ({\n  plugins: [react(), tailwindcss()],\n  resolve: {\n    alias: {\n      \"@\": path.resolve(__dirname, \"./src\"),\n    },\n  },\n  clearScreen: false,\n  server: {\n    port: 1420,\n    strictPort: true,\n    host: host || false,\n    hmr: host\n      ? {\n          protocol: \"ws\",\n          host,\n          port: 1421,\n        }\n      : undefined,\n    watch: {\n      ignored: [\"**/src-tauri/**\"],\n    },\n  },\n}));\n```\n\n```text\ntailwind.config.js\n```\n\n```text\ntsconfig.json\n```\n\n```text\ntsconfig.node.json\n```\n\n```text\ntailwind.config.js\n```\n\n```text\ntsconfig\n```\n\n```text\nnpm install -D tailwindcss@3\n```\n\n```text\nshadcn-ui/ui\n```\n\n```text\nnpm install tailwindcss\n```\n\n```text\nnpm install tailwindcss@3\n```\n\n```text\nnpx tailwindcss\n```\n\n```text\nnpx @tailwindcss/cli\n```\n\n```text\nnpx tailwindcss init\n```\n\n```text\ntailwind.config.js\n```\n\n```text\n@config\n```\n\n```text\nnpm i tailwindcss\n```\n\n```text\nshadcn/app-tailwind-v4\n```\n\n```text\nshadcn/ui\n```\n\n```text\nnpm install tailwindcss@3\n```\n\n```text\nshadcn-ui/ui\n```\n\n```text\nshadcn-ui/ui\n```\n\n```text\nshadcn-ui/ui\n```\n\n========================================\n\nComments:\n- A few days ago, Shadcn officially started supporting TailwindCSS v4; See: `shadcn-ui&#47;ui` #6427 and Shadcn UI with TailwindCSS v4\n- Thanks man , that will save me some time","metadata":{"transformedAt":"2026-08-18T18:33:46.436Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":26,"totalLines":309,"estimatedTokens":1436}}556{"id":"stack-78993512","source":"stackoverflow","questionId":78993512,"title":"Creating a Typescript Library Using Vite, leads to import errror: \"TypeError: au.release is not a function\" in the project","tags":["node.js","typescript","vite","npm-package"],"text":"Title: Creating a Typescript Library Using Vite, leads to import errror: \"TypeError: au.release is not a function\" in the project\nTags: node.js, typescript, vite, npm-package\nSource: Stack Overflow\n\nQuestion:\n**Questions:**.\nWhere does the error come from?\nAnd why it appears if additional imports happen in the library?\nHow can I export my custom library in other project without breaking the project - possibility to run?\nPlease note this is my first library which I am creating so lot of unknowns. I believe issue lies in my configuration in either *ts, vite or pck* is incorrect, though if that is the case, not sure which part.\n\n**Issue description:** When I import a custom made library, code does not compile and gives an error message. When looking in the compiled code, this appears to be shown when `.release().split(\".\")` is being performed (6 instanses) or `au.release().toLowerCase().includes(\"microsoft\")` (1 instanse).\n\n`\"TypeError: au.release is not a function\"`\n\n```\nif (process.platform === \"win32\") {\n var Au = au.release().split(\".\");\n return Number(process.versions.node.split(\".\")[0]) >= 8 && Number(Au[0]) >= 10 && Number(Au[2]) >= 10586 ? Number(Au[2]) >= 14931 ? 3 : 2 : 1;\n}\n```\n\nIt is seen in the project, where it is imported. ***From what it looks it only appears when the library has a function which uses an import statement from other 3rd party libraries***.\n\nIn the below code block, if I export this function from the vite\nlibrary I will for sure get this error (mentioned previously), though\nthe library itself will compile and build without issues. I cannot see\nwhat is wrong with it.\n\n```\nimport axios from \"axios\";\n\nexport async function dosAttack(\n url: string,\n qty: number,\n ms: number\n): Promise {\n const result: { err: number; pass: number }[] = [];\n\n for (let time = 0; time pass++)\n .catch(() => err++)\n );\n }\n\n await Promise.all(requests);\n console.log({ err, pass });\n result.push({ err, pass });\n await new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n return result;\n}\n```\n\nIssue in VS Code:\nhttps://i.sstatic.net/it6DKOlj.png\n\nI have tried multiple settings, though not sure if there were any which actually made sense. The below function do work without any issues, though they don't have any 3rd dependencies installed in them.\n]2\n\nConfiguration in package.json, vite.config.ts, tsconfig.json:\n\n**vite.config.ts**\n\n```\n// vite.config.js\nimport { resolve } from \"path\";\nimport { defineConfig } from \"vite\";\nimport dts from \"vite-plugin-dts\";\nimport viteTsconfigPaths from \"vite-tsconfig-paths\";\n\nconst packageName = \"qa-library\";\n\nexport default defineConfig({\n base: \"\",\n plugins: [\n viteTsconfigPaths(),\n dts({\n insertTypesEntry: true,\n }),\n ],\n build: {\n lib: {\n entry: resolve(__dirname, \"src/index.ts\"),\n name: packageName,\n fileName: \"index\",\n formats: [\"es\", \"cjs\"],\n },\n emptyOutDir: false,\n },\n resolve: {\n alias: {\n lib: \"/src\",\n enums: \"/src/enums\",\n interface: \"/src/interface\",\n service: \"/src/service\",\n },\n },\n});\n```\n\n**tsconfig.json**\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"ESNext\",\n \"lib\": [\"ESNext\"],\n \"types\": [\"vite/client\", \"node\"],\n // \"allowJs\": false,\n \"skipLibCheck\": true,\n // \"esModuleInterop\": false,\n \"allowSyntheticDefaultImports\": true,\n \"strict\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"module\": \"CommonJS\",\n \"moduleResolution\": \"Node\",\n \"resolveJsonModule\": true,\n // \"isolatedModules\": true,\n \"noEmit\": true,\n \"baseUrl\": \"./\",\n \"paths\": {\n \"@/*\": [\"./src/*\"],\n \"lib/*\": [\"./src/*\"],\n \"enums/*\": [\"./src/enums/*\"],\n \"interface/*\": [\"./src/interface/*\"],\n \"service/*\": [\"./src/service/*\"]\n }\n },\n \"include\": [\"./src\"],\n \"exclude\": [\"node_modules\"]\n}\n```\n\n**package.json**\n\n```\n{\n \"name\": \"qa-library\",\n \"private\": false,\n \"version\": \"0.1.303\",\n \"type\": \"module\",\n \"exports\": {\n \".\": {\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\",\n \"types\": \"./dist/index.d.ts\"\n }\n },\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"typings\": \"./dist/index.d.ts\",\n \"files\": [\n \"/dist/*\"\n ],\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"tsc && vite build\",\n \"preview\": \"vite preview\"\n },\n \"devDependencies\": {\n \"@rollup/plugin-typescript\": \"^8.5.0\",\n \"@types/node\": \"^18.18.5\",\n \"prettier\": \"2.6.2\",\n \"rollup-plugin-typescript-paths\": \"^1.5.0\",\n \"tslib\": \"^2.7.0\",\n \"typescript\": \"^5.5.3\",\n \"vite\": \"^5.4.1\"\n },\n \"dependencies\": {\n \"@faker-js/faker\": \"^8.4.1\",\n \"@playwright/test\": \"^1.47.0\",\n \"@standardsdigital/qa-library\": \"^0.1.302\",\n \"axios\": \"^1.7.7\",\n \"moment\": \"^2.30.1\",\n \"vite-plugin-dts\": \"^4.2.1\",\n \"vite-tsconfig-paths\": \"^4.2.3\"\n }\n}\n```\n\n========================================\n\nCode:\n```text\nif (process.platform === \"win32\") {\n  var Au = au.release().split(\".\");\n  return Number(process.versions.node.split(\".\")[0]) >= 8 && Number(Au[0]) >= 10 && Number(Au[2]) >= 10586 ? Number(Au[2]) >= 14931 ? 3 : 2 : 1;\n}\n```\n\n```text\nimport axios from \"axios\";\n\nexport async function dosAttack(\n  url: string,\n  qty: number,\n  ms: number\n): Promise<{ err: number; pass: number }[]> {\n  const result: { err: number; pass: number }[] = [];\n\n  for (let time = 0; time < qty; time++) {\n    const requests = [];\n    let err = 0;\n    let pass = 0;\n\n    for (let attack = 0; attack < qty; attack++) {\n      requests.push(\n        axios\n          .get(url)\n          .then(() => pass++)\n          .catch(() => err++)\n      );\n    }\n\n    await Promise.all(requests);\n    console.log({ err, pass });\n    result.push({ err, pass });\n    await new Promise((resolve) => setTimeout(resolve, ms));\n  }\n\n  return result;\n}\n```\n\n```text\n// vite.config.js\nimport { resolve } from \"path\";\nimport { defineConfig } from \"vite\";\nimport dts from \"vite-plugin-dts\";\nimport viteTsconfigPaths from \"vite-tsconfig-paths\";\n\nconst packageName = \"qa-library\";\n\nexport default defineConfig({\n  base: \"\",\n  plugins: [\n    viteTsconfigPaths(),\n    dts({\n      insertTypesEntry: true,\n    }),\n  ],\n  build: {\n    lib: {\n      entry: resolve(__dirname, \"src/index.ts\"),\n      name: packageName,\n      fileName: \"index\",\n      formats: [\"es\", \"cjs\"],\n    },\n    emptyOutDir: false,\n  },\n  resolve: {\n    alias: {\n      lib: \"/src\",\n      enums: \"/src/enums\",\n      interface: \"/src/interface\",\n      service: \"/src/service\",\n    },\n  },\n});\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"lib\": [\"ESNext\"],\n    \"types\": [\"vite/client\", \"node\"],\n    // \"allowJs\": false,\n    \"skipLibCheck\": true,\n    // \"esModuleInterop\": false,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"CommonJS\",\n    \"moduleResolution\": \"Node\",\n    \"resolveJsonModule\": true,\n    // \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"baseUrl\": \"./\",\n    \"paths\": {\n      \"@/*\": [\"./src/*\"],\n      \"lib/*\": [\"./src/*\"],\n      \"enums/*\": [\"./src/enums/*\"],\n      \"interface/*\": [\"./src/interface/*\"],\n      \"service/*\": [\"./src/service/*\"]\n    }\n  },\n  \"include\": [\"./src\"],\n  \"exclude\": [\"node_modules\"]\n}\n```\n\n```text\n{\n  \"name\": \"qa-library\",\n  \"private\": false,\n  \"version\": \"0.1.303\",\n  \"type\": \"module\",\n  \"exports\": {\n    \".\": {\n      \"import\": \"./dist/index.js\",\n      \"require\": \"./dist/index.cjs\",\n      \"types\": \"./dist/index.d.ts\"\n    }\n  },\n  \"main\": \"./dist/index.cjs\",\n  \"module\": \"./dist/index.js\",\n  \"typings\": \"./dist/index.d.ts\",\n  \"files\": [\n    \"/dist/*\"\n  ],\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"tsc && vite build\",\n    \"preview\": \"vite preview\"\n  },\n  \"devDependencies\": {\n    \"@rollup/plugin-typescript\": \"^8.5.0\",\n    \"@types/node\": \"^18.18.5\",\n    \"prettier\": \"2.6.2\",\n    \"rollup-plugin-typescript-paths\": \"^1.5.0\",\n    \"tslib\": \"^2.7.0\",\n    \"typescript\": \"^5.5.3\",\n    \"vite\": \"^5.4.1\"\n  },\n  \"dependencies\": {\n    \"@faker-js/faker\": \"^8.4.1\",\n    \"@playwright/test\": \"^1.47.0\",\n    \"@standardsdigital/qa-library\": \"^0.1.302\",\n    \"axios\": \"^1.7.7\",\n    \"moment\": \"^2.30.1\",\n    \"vite-plugin-dts\": \"^4.2.1\",\n    \"vite-tsconfig-paths\": \"^4.2.3\"\n  }\n}\n```\n\n```text\n<tag>.release().split(\".\")\n```\n\n```text\nau.release().toLowerCase().includes(\"microsoft\")\n```\n\n```text\n\"TypeError: au.release is not a function\"\n```\n\n```text\nrollupOptions: {\n   external: [\"@playwright/test\", \"axios\"],\n },\n```\n\n========================================\n\nComments:\n- Please convert your images into code so that it is easier to help you\n- @BoshraJaber Sorry, my bad, have not done this for a while. :). Changed where applicable.","metadata":{"transformedAt":"2026-08-18T18:33:46.436Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":361,"estimatedTokens":2098}}557{"id":"stack-68735460","source":"stackoverflow","questionId":68735460,"title":"How do Vite MPAs using the Vue plugin work?","tags":["javascript","vue.js","vite"],"text":"Title: How do Vite MPAs using the Vue plugin work?\nTags: javascript, vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI have a Vite app created and I need it to have multiple pages. I read the docs and found how to do this (can be found here), however when I run the server I get a blank page.\n\nMy `vite.config.js` file:\n\n```\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\nconst { resolve } = require('path')\n\nmodule.exports = {\n build: {\n rollupOptions: {\n input: {\n home: resolve(__dirname, 'src/Home/index.html')\n }\n }\n }\n}\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [vue()]\n})\n```\n\nHere's what my file structure looks like:\n\n**Edit:** I have changed the config to what tony posted below, but it is still showing a blank page.\n\n**Edit 2:** I found out that you don't need to use the vite.config.js routing, there's an easier way\nCreate a copy of your main.js, App.vue, and index.html file and rename them to something different. After you rename them change the `` to your new JS file, and change the `.vue` file import in your new main.js to your new `.vue` file. Here's my new structure:\n\nhttps://i.sstatic.net/3qbAF.png\n\nAll I did was copy the files and change the names and imports, and it worked!\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\n\nconst { resolve } = require('path')\n\nmodule.exports = {\n  build: {\n    rollupOptions: {\n      input: {\n        home: resolve(__dirname, 'src/Home/index.html')\n      }\n    }\n  }\n}\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue()]\n})\n```\n\n```text\nvite.config.js\n```\n\n```text\n<script type=\"module\" src=\"index.js\"></script>\n```\n\n```text\n.vue\n```\n\n```text\n.vue\n```\n\n```js\nmodule.exports = { 1️⃣\n  //...\n}\n\nexport default defineConfig({ 2️⃣\n  //...\n})\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport { resolve } from 'path'\n\nexport default defineConfig({\n  plugins: [vue()],\n  build: {\n    rollupOptions: {\n      input: {\n        home: resolve(__dirname, 'src/Home/index.html')\n      }\n    }\n  }\n})\n```\n\n```text\nvite.config.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.436Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":113,"estimatedTokens":547}}558{"id":"stack-78304170","source":"stackoverflow","questionId":78304170,"title":"How to Resolve Browser Cache Invalidation Issue in Vite-React Project Deployment?","tags":["vite","browser-cache","cache-control"],"text":"Title: How to Resolve Browser Cache Invalidation Issue in Vite-React Project Deployment?\nTags: vite, browser-cache, cache-control\nSource: Stack Overflow\n\nQuestion:\n**Problem:**\nI'm encountering a persistent issue with my Vite-React project deployment. Whenever I deploy a new version, the changes are not immediately reflected on the production URL. Instead, they only appear after performing a hard reload. This seems to be a cache-related problem.\n\n**Details:**\nI have a Vite-React project deployed in a production environment. However, whenever I push updates and redeploy the application, users visiting the site often don't see the latest changes until they perform a hard reload (Ctrl + Shift + R or Cmd + Shift + R). This indicates that there's a caching issue preventing the new version from being fetched and displayed immediately.\n\n**Steps Taken:**\nI've tried various methods to tackle this problem, including:\n\n- Adding cache-control headers in the server configuration.\n\n- Attempting to bust cache by changing the version data of package.json.\n\n**Expected Outcome:**\nI expect that whenever I deploy a new version of my Vite-React project, the changes should be immediately visible to users without requiring them to perform a hard reload. The deployment process should handle cache invalidation effectively to ensure seamless updates.\n\n**Seeking Solution:**\nI'm looking for insights and recommendations on how to effectively manage browser cache invalidation in my Vite-React project deployment. Specifically, I need guidance on configuring Vite or implementing strategies to ensure that new versions are fetched and displayed automatically without relying on users to perform manual cache clearing.\n\n========================================\n\nTop Answer:\nYou can use service worker capabilities on caching. The basic flow would allow you to hop callback that would be triggered upon new build files arriving. There you can choose to either force refresh the page / prompt user to refresh for a new version / etc\n\n\r\n\r\n\n```\nimport {Workbox} from 'workbox-window';\n\nexport default function registerSW() {\n //! running SW in dev mode can cause several problems due to\n //! caching on every update, so use this commented out code\n // if (process.env.NODE_ENV !== 'production') {\n // return;\n // }\n\n if ('serviceWorker' in navigator) {\n const wb = new Workbox('sw.js');\n\n wb.addEventListener('installed', (e) => {\n if (e.isUpdate && confirm('New app update is available, click to update')) {\n window.location.reload();\n }\n });\n\n wb.register();\n }\n}\n```\n\n\r\n\r\n\r\n\n\r\n\r\n\n```\nimport {clientsClaim} from 'workbox-core';\nimport {precacheAndRoute} from 'workbox-precaching';\n\nclientsClaim();\n\nself.skipWaiting();\n\nprecacheAndRoute(self.__WB_MANIFEST);\n```\n\n\r\n\r\n\r\n\nand ofcource registering it in the index file.\n\nNote that this is just an example that I did like 2 years ago so the flow on the newer versions on workbox libraries may vary\n\n========================================\n\nCode:\n```js\nimport {Workbox} from 'workbox-window';\n\nexport default function registerSW() {\n    //! running SW in dev mode can cause several problems due to\n    //! caching on every update, so use this commented out code\n    // if (process.env.NODE_ENV !== 'production') {\n    //  return;\n    // }\n\n    if ('serviceWorker' in navigator) {\n        const wb = new Workbox('sw.js');\n\n        wb.addEventListener('installed', (e) => {\n            if (e.isUpdate && confirm('New app update is available, click to update')) {\n                window.location.reload();\n            }\n        });\n\n        wb.register();\n    }\n}\n```\n\n```js\nimport {clientsClaim} from 'workbox-core';\nimport {precacheAndRoute} from 'workbox-precaching';\n\nclientsClaim();\n\nself.skipWaiting();\n\nprecacheAndRoute(self.__WB_MANIFEST);\n```\n\n========================================\n\nComments:\n- Did you find solution to this?\n- The root of my issue was that the `index.html` file was being cached, which prevented the new css and js files from being downloaded despite having unique hashes. I added `Cache-Control \"max-age=0, must-revalidate\"` and the issue when away","metadata":{"transformedAt":"2026-08-18T18:33:46.436Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":125,"estimatedTokens":1029}}559{"id":"stack-78443502","source":"stackoverflow","questionId":78443502,"title":"Updating from vue-cli to Vite: TypeError: Cannot read properties of null (reading 'nextSibling')","tags":["vue.js","vite","vue-cli","hot-reload"],"text":"Title: Updating from vue-cli to Vite: TypeError: Cannot read properties of null (reading 'nextSibling')\nTags: vue.js, vite, vue-cli, hot-reload\nSource: Stack Overflow\n\nQuestion:\nI have updated my Vue 3 project to use Vite following these tutorials:\n\n- Vue School: How to Migrate from Vue CLI to Vite\n\n- Medium: Vue-cli -> Vite migration\n\nThe project is working and running with Vite. The problem I am having is that when I change a component and then save the file I get this error in the browser console:\n\n```\nUncaught (in promise) TypeError: Cannot read properties of null (reading 'nextSibling')\n```\n\nAlso the page goes completly blank.\n\nHowever after a reload the error goes away and the page is displayed with the change.\n\nI am using multiple packages but I don't know if (or which) they are the cause. This is my `package.json`:\n\n```\n{\n \"name\": \"vue-project\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\",\n \"format\": \"prettier . --write\"\n },\n \"dependencies\": {\n \"@fortawesome/fontawesome-free\": \"^6.5.1\",\n \"@vitejs/plugin-vue\": \"^5.0.4\",\n \"@vueuse/core\": \"^10.9.0\",\n \"chart.js\": \"^4.4.2\",\n \"dayjs\": \"^1.11.10\",\n \"firebase\": \"^10.9.0\",\n \"firebase-admin\": \"^12.1.0\",\n \"pinia\": \"^2.1.7\",\n \"primeicons\": \"^6.0.1\",\n \"primevue\": \"^3.50.0\",\n \"register-service-worker\": \"^1.7.2\",\n \"vite\": \"^5.2.11\",\n \"vue\": \"^3.2.39\",\n \"vue-chartjs\": \"^5.3.1\",\n \"vue-router\": \"^4.0.3\"\n },\n \"devDependencies\": {\n \"autoprefixer\": \"^10.4.18\",\n \"postcss\": \"^8.4.37\",\n \"prettier\": \"^2.8.8\",\n \"tailwindcss\": \"^3.4.1\"\n }\n}\n```\n\nAnd this is my `vite.config.mjs`:\n\n```\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\";\nimport { fileURLToPath } from \"url\";\nimport path from \"path\";\n\nconst filename = fileURLToPath(import.meta.url);\nconst pathSegments = path.dirname(filename);\n\nexport default defineConfig({\n resolve: {\n alias: {\n \"@\": path.resolve(pathSegments, \"./src\")\n },\n extensions: [\".mjs\", \".js\", \".ts\", \".jsx\", \".tsx\", \".json\"]\n },\n plugins: [vue()]\n});\n```\n\nHow can I fix this?\n\n========================================\n\nTop Answer:\nIn my case I had `` in template, variable `myComponent` changed and if it was `undefined` then this error appeared\n\n========================================\n\nCode:\n```text\nUncaught (in promise) TypeError: Cannot read properties of null (reading 'nextSibling')\n```\n\n```json\n{\n    \"name\": \"vue-project\",\n    \"version\": \"0.1.0\",\n    \"private\": true,\n    \"scripts\": {\n        \"dev\": \"vite\",\n        \"build\": \"vite build\",\n        \"preview\": \"vite preview\",\n        \"format\": \"prettier . --write\"\n    },\n    \"dependencies\": {\n        \"@fortawesome/fontawesome-free\": \"^6.5.1\",\n        \"@vitejs/plugin-vue\": \"^5.0.4\",\n        \"@vueuse/core\": \"^10.9.0\",\n        \"chart.js\": \"^4.4.2\",\n        \"dayjs\": \"^1.11.10\",\n        \"firebase\": \"^10.9.0\",\n        \"firebase-admin\": \"^12.1.0\",\n        \"pinia\": \"^2.1.7\",\n        \"primeicons\": \"^6.0.1\",\n        \"primevue\": \"^3.50.0\",\n        \"register-service-worker\": \"^1.7.2\",\n        \"vite\": \"^5.2.11\",\n        \"vue\": \"^3.2.39\",\n        \"vue-chartjs\": \"^5.3.1\",\n        \"vue-router\": \"^4.0.3\"\n    },\n    \"devDependencies\": {\n        \"autoprefixer\": \"^10.4.18\",\n        \"postcss\": \"^8.4.37\",\n        \"prettier\": \"^2.8.8\",\n        \"tailwindcss\": \"^3.4.1\"\n    }\n}\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\";\nimport { fileURLToPath } from \"url\";\nimport path from \"path\";\n\nconst filename = fileURLToPath(import.meta.url);\nconst pathSegments = path.dirname(filename);\n\nexport default defineConfig({\n    resolve: {\n        alias: {\n            \"@\": path.resolve(pathSegments, \"./src\")\n        },\n        extensions: [\".mjs\", \".js\", \".ts\", \".jsx\", \".tsx\", \".json\"]\n    },\n    plugins: [vue()]\n});\n```\n\n```text\npackage.json\n```\n\n```text\nvite.config.mjs\n```\n\n```html\n<!doctype html>\n<html lang=\"en\">\n    <head>\n        <meta charset=\"UTF-8\" />\n        <link\n            rel=\"icon\"\n            href=\"/favicon.ico\"\n        />\n        <meta\n            name=\"viewport\"\n            content=\"width=device-width, initial-scale=1.0\"\n        />\n        <title>Vue project</title>\n    </head>\n    <body>\n        <div id=\"app\"></div>\n        <script\n            type=\"module\"\n            src=\"/src/main.js\"\n        ></script>\n    </body>\n</html>\n```\n\n```js\ndocument.addEventListener(\"DOMContentLoaded\", async () => {\n    app.use(createPinia());\n\n    const userStore = useAuthStore();\n    await userStore.init();\n\n    app.use(router);\n\n    app.use(PrimeVue, {\n        unstyled: true,\n        pt: lara\n    });\n    app.use(ToastService);\n    app.use(ConfirmationService);\n\n    // Often used PrimeVue components\n    app.component(\"Divider\", Divider);\n    app.component(\"Button\", Button);\n\n    app.mount(\"#app\");\n});\n```\n\n```text\nscript\n```\n\n```text\nindex.html\n```\n\n```text\nindex.html\n```\n\n```text\nmain.js\n```\n\n```text\napp.use()\n```\n\n```text\napp.mount()\n```\n\n```text\n<component :is=\"{myComponent}\">\n```\n\n```text\nmyComponent\n```\n\n```text\nundefined\n```\n\n```text\n<div>\n    <AppHeader />\n    <router-view v-slot=\"{ Component }\">\n        <transition name=\"page-fade\" mode=\"out-in\">\n            <component :is=\"Component\" />\n        </transition>\n    </router-view>\n</div>\n```\n\n========================================\n\nComments:\n- Looks like it's a common issue with no easy straightforward solution. Might be a small detail in the config files. Maybe try to build a fresh Vue3 project and migrate the stuff from your current one? That way you could have make a difference between the 2 and report the solution to the community! At least your code look like is buggy only on the HMR side of things.\n- Nice! I was meant to be a small detail yes. Please accept your own answer.\n- I want to but can't: You can accept your own answer in 2 days\n- Ohhhh, maybe yes. If you post it straight you can or if it's someone's answer but otherwise not, quite eh. Enjoy your answer then!","metadata":{"transformedAt":"2026-08-18T18:33:46.436Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":264,"estimatedTokens":1484}}560{"id":"stack-70811770","source":"stackoverflow","questionId":70811770,"title":"Incorrect images path in production build - Vue.js","tags":["vue.js","vuejs3","vite"],"text":"Title: Incorrect images path in production build - Vue.js\nTags: vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI'm building my project with Vue.js 3, Vite.js.\nThe app works fine when in dev mode (when using the dev server). Once I do launch the build command, Vite creates for me the /dist directory containing the build for my app. If I run the preview command (vite preview) it starts with no problem the preview of my build.\n\nThe problem is with some images which are coming from Vue components. All the images of my project are in the src/assets directory.\n\n```\n.\n├── Attribution.txt\n├── README.md\n├── index.html\n├── package-lock.json\n├── package.json\n├── postcss.config.js\n├── public\n│   └── favicon.ico\n├── src\n│   ├── App.vue\n│   ├── assets\n│   │   ├── Temp.png\n│   │   ├── bridge.png\n│   │   ├── city-security.png\n│   │   ├── credit-card.png\n│   │   ├── deforestation.png\n│   │   ├── eagle.png\n│   │   ├── favicon\n│   │   │   ├── android-chrome-192x192.png\n│   │   │   ├── android-chrome-512x512.png\n│   │   │   ├── apple-touch-icon.png\n│   │   │   ├── favicon-16x16.png\n│   │   │   ├── favicon-32x32.png\n│   │   │   └── favicon.ico\n│   │   ├── global-goals.png\n│   │   ├── hall.png\n│   │   ├── italian-flag.png\n│   │   ├── machine-learning.png\n│   │   ├── modern-architecture.png\n│   │   ├── moon-festival.png\n│   │   ├── people.png\n│   │   ├── planet-earth.png\n│   │   ├── police.png\n│   │   ├── teamwork.png\n│   │   ├── uk-flag.png\n│   │   └── virtual.png\n│   ├── components\n│   │   ├── Button.vue\n│   │   ├── Card.vue\n│   │   ├── Column.vue\n│   │   ├── Footer.vue\n│   │   ├── MainContent.vue\n│   │   ├── Navbar.vue\n│   │   └── components-it\n│   │   ├── Card-it.vue\n│   │   ├── Footer-it.vue\n│   │   └── Navbar-it.vue\n│   ├── main.js\n│   ├── router\n│   │   └── index.js\n│   ├── tailwind.css\n│   └── views\n│   ├── CitySecurity.vue\n│   ├── Contribute.vue\n│   ├── Credits.vue\n│   ├── Goals.vue\n│   ├── Home.vue\n│   ├── It\n│   │   ├── CitySecurity-it.vue\n│   │   ├── Contribute-it.vue\n│   │   ├── Credits-it.vue\n│   │   ├── Goals-it.vue\n│   │   ├── Home-it.vue\n│   │   └── Municipality-it.vue\n│   └── Municipality.vue\n├── tailwind.config.js\n└── vite.config.js\n```\n\nThe images in the views have the correct path and are displayed correctly in the build. But the images in the components folder have a problem: the path doesn't change in the build file.\n\ni.e.\n\n```\n\n \n \n \n\n### A new way to live the City\n\n \n \n To improve the municipality livings being we tought about some ideas, that\n are somehow able to improve the qol(Quality of life). One of the most\n reliable problem that requires to be solved is the minimization of\n burocracy, tryna to make things digital any sort of procedure. One of ours\n ideas is to improve the mechanism of shifting around the city, by giving\n cityzens public and shareble veichles to reduce pollution and the waste of\n fuel.\n \n\n \n \n \n\n### Digitalization\n\n \n \n Burocracy is so annoying, so we tought about how we can semplify it.\n The Answer is... DIGITALIZATION! Everything's simpler when digital, so\n our city is going to have a system for all of them.\n \n\n \n \n \n\n### Infrastructures Upgrading\n\n \n \n To make our city better, our city is going to invest in\n infrastructures to let cityzens live their life much better. Better\n \"bridges\" makes better people.\n \n\n \n \n \n\n### Innovative Learning\n\n \n \n Our city is going to offer a learning system to make everyone learn\n about technologies and new innovation. The mind of a man is the most\n precious part of him.\n \n\n \n \n \n \n\nimport Navbar from \"../components/Navbar.vue\";\nimport Footer from \"../components/Footer.vue\";\nimport Button from \"../components/Button.vue\";\nexport default {\n name: \"Municipality\",\n components: {\n Navbar,\n Footer,\n Button,\n },\n};\n\n```\n\nThis is one of my views. In the build, all the img tags will have the correct path (Ex: /assets/imgName.randomNumbersAndString.png).\n\nBut this doesn't happen in the components.\n\ni.e. - Card.vue component\n\n```\n\n \n \n \n \n {{ text }}\n\n \n\nexport default {\n name: \"Card\",\n props: {\n link: String,\n imgClass: String,\n imgName: String,\n imgAlt: String,\n text: String,\n },\n};\n\n```\n\nCredits.vue view\n\n```\n\n \n \n Images and Icons attributions\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\nimport Card from \"../components/Card.vue\";\nimport Navbar from \"../components/Navbar.vue\";\nimport Footer from \"../components/Footer.vue\";\nimport Button from \"../components/Button.vue\";\n\nexport default {\n name: \"Credits\",\n components: {\n Navbar,\n Footer,\n Button,\n Card,\n },\n};\n\n```\n\nIn this case, when I pass the **imgName** to the Card component, in the build file the path of the image is ./src/assets/name.png.\n\nHow can I fix?\n\n========================================\n\nTop Answer:\nInstead of using relative path `(..)` to the assets folder, you can use `@/assets` from any of the vue components to refer to files in the assets folder.\n\nE.g this should work, no matter how deep the Vue component is nested.\n\n```\n\n```\n\n**EDIT:**\n\nAs pointed out by `@flydev`, you'll have to configure vite config like this: https://stackoverflow.com/a/66046200/3565182 for this to work.\n\n========================================\n\nCode:\n```text\n.\n├── Attribution.txt\n├── README.md\n├── index.html\n├── package-lock.json\n├── package.json\n├── postcss.config.js\n├── public\n│   └── favicon.ico\n├── src\n│   ├── App.vue\n│   ├── assets\n│   │   ├── Temp.png\n│   │   ├── bridge.png\n│   │   ├── city-security.png\n│   │   ├── credit-card.png\n│   │   ├── deforestation.png\n│   │   ├── eagle.png\n│   │   ├── favicon\n│   │   │   ├── android-chrome-192x192.png\n│   │   │   ├── android-chrome-512x512.png\n│   │   │   ├── apple-touch-icon.png\n│   │   │   ├── favicon-16x16.png\n│   │   │   ├── favicon-32x32.png\n│   │   │   └── favicon.ico\n│   │   ├── global-goals.png\n│   │   ├── hall.png\n│   │   ├── italian-flag.png\n│   │   ├── machine-learning.png\n│   │   ├── modern-architecture.png\n│   │   ├── moon-festival.png\n│   │   ├── people.png\n│   │   ├── planet-earth.png\n│   │   ├── police.png\n│   │   ├── teamwork.png\n│   │   ├── uk-flag.png\n│   │   └── virtual.png\n│   ├── components\n│   │   ├── Button.vue\n│   │   ├── Card.vue\n│   │   ├── Column.vue\n│   │   ├── Footer.vue\n│   │   ├── MainContent.vue\n│   │   ├── Navbar.vue\n│   │   └── components-it\n│   │       ├── Card-it.vue\n│   │       ├── Footer-it.vue\n│   │       └── Navbar-it.vue\n│   ├── main.js\n│   ├── router\n│   │   └── index.js\n│   ├── tailwind.css\n│   └── views\n│       ├── CitySecurity.vue\n│       ├── Contribute.vue\n│       ├── Credits.vue\n│       ├── Goals.vue\n│       ├── Home.vue\n│       ├── It\n│       │   ├── CitySecurity-it.vue\n│       │   ├── Contribute-it.vue\n│       │   ├── Credits-it.vue\n│       │   ├── Goals-it.vue\n│       │   ├── Home-it.vue\n│       │   └── Municipality-it.vue\n│       └── Municipality.vue\n├── tailwind.config.js\n└── vite.config.js\n```\n\n```html\n<template>\n  <Navbar />\n  <div class=\"container flex flex-col items-center py-20 font-bold mx-auto\">\n    <h1 class=\"uppercase text-3xl\">A new way to live the City</h1>\n    <img src=\"../assets/hall.png\" alt=\"Town Hall\" width=\"250\" class=\"py-10\" />\n    <p class=\"lg:w-1/2 text-justify leading-relaxed\">\n      To improve the municipality livings being we tought about some ideas, that\n      are somehow able to improve the qol(Quality of life). One of the most\n      reliable problem that requires to be solved is the minimization of\n      burocracy, tryna to make things digital any sort of procedure. One of ours\n      ideas is to improve the mechanism of shifting around the city, by giving\n      cityzens public and shareble veichles to reduce pollution and the waste of\n      fuel.\n    </p>\n    <div class=\"grid lg:grid-cols-3 lg:gap-0 gap-10 place-items-center pt-20\">\n      <div class=\"card container flex flex-col items-center justify-center\">\n        <h1 class=\"uppercase text-xl\">Digitalization</h1>\n        <img\n          class=\"py-5\"\n          src=\"../assets/virtual.png\"\n          alt=\"Digitalization\"\n          width=\"100\"\n        />\n        <p class=\"lg:w-full text-justify lg:w-3/5 lg:leading-relaxed w-3/4\">\n          Burocracy is so annoying, so we tought about how we can semplify it.\n          The Answer is... DIGITALIZATION! Everything's simpler when digital, so\n          our city is going to have a system for all of them.\n        </p>\n      </div>\n      <div class=\"card container flex flex-col items-center justify-center\">\n        <h1 class=\"uppercase text-xl\">Infrastructures Upgrading</h1>\n        <img\n          class=\"py-5\"\n          src=\"../assets/bridge.png\"\n          alt=\"Digitalization\"\n          width=\"100\"\n        />\n        <p class=\"lg:w-full text-justify lg:w-3/5 lg:leading-relaxed w-3/4\">\n          To make our city better, our city is going to invest in\n          infrastructures to let cityzens live their life much better. Better\n          \"bridges\" makes better people.\n        </p>\n      </div>\n      <div class=\"card container flex flex-col items-center justify-center\">\n        <h1 class=\"uppercase text-xl\">Innovative Learning</h1>\n        <img\n          class=\"py-5\"\n          src=\"../assets/Machine-Learning.png\"\n          alt=\"Digitalization\"\n          width=\"100\"\n        />\n        <p class=\"lg:w-full text-justify lg:w-3/5 lg:leading-relaxed w-3/4\">\n          Our city is going to offer a learning system to make everyone learn\n          about technologies and new innovation. The mind of a man is the most\n          precious part of him.\n        </p>\n      </div>\n    </div>\n  </div>\n  <Footer />\n</template>\n\n<script>\nimport Navbar from \"../components/Navbar.vue\";\nimport Footer from \"../components/Footer.vue\";\nimport Button from \"../components/Button.vue\";\nexport default {\n  name: \"Municipality\",\n  components: {\n    Navbar,\n    Footer,\n    Button,\n  },\n};\n</script>\n\n<style></style>\n```\n\n```html\n<template>\n  <div\n    class=\"card container flex flex-col items-center justify-center pt-20 pb-20\"\n  >\n    <a :href=\"`${link}`\">\n      <img\n        :class=\"`${imgClass || 'py-5'}`\"\n        :src=\"`./src/assets/${imgName}`\"\n        :alt=\"`${imgAlt}`\"\n        width=\"100\"\n      />\n    </a>\n    <p class=\"lg:w-full lg:w-3/5 lg:leading-relaxed w-3/4\">{{ text }}</p>\n  </div>\n</template>\n\n<script>\nexport default {\n  name: \"Card\",\n  props: {\n    link: String,\n    imgClass: String,\n    imgName: String,\n    imgAlt: String,\n    text: String,\n  },\n};\n</script>\n\n<style scoped></style>\n```\n\n```html\n<template>\n  <Navbar />\n  <h1 class=\"uppercase lg:text-5xl text-2xl mx-auto text-center pt-20\">\n    Images and Icons attributions\n  </h1>\n  <div class=\"grid lg:grid-cols-3 place-items-center lg:pb-10 mx-auto\">\n    <Card\n      link=\"Hall icons created by Smashicons - Flaticon\"\n      text=\"Hall icons created by Smashicons - Flaticon\"\n      imgAlt=\"Hall vector representation\"\n      imgName=\"hall.png\"\n    />\n    <Card\n      link=\"https://www.flaticon.com/free-icons/moon-festival\"\n      text=\"Pokemon icons created by Roundicons Freebies - Flaticon\"\n      imgAlt=\"Temp logo\"\n      imgName=\"Temp.png\"\n    />\n    <Card\n      link=\"https://www.flaticon.com/free-icons/moon-festival\"\n      text=\"Moon festival icons created by Flat Icons - Flaticon\"\n      imgAlt=\"Moon vector representation\"\n      imgName=\"moon-festival.png\"\n    />\n    <Card\n      link=\"https://www.flaticon.com/free-icons/digital\"\n      text=\"Digital icons created by Freepik - Flaticon\"\n      imgAlt=\"Digital vector representation\"\n      imgName=\"virtual.png\"\n    />\n    <Card\n      link=\"https://www.flaticon.com/free-icons/tower-bridge\"\n      text=\"Tower bridge icons created by Freepik - Flaticon\"\n      imgAlt=\"Bridge vector representation\"\n      imgName=\"bridge.png\"\n    />\n    <Card\n      link=\"https://www.flaticon.com/free-icons/machine-learning\"\n      text=\"Machine learning icons created by Flat Icons - Flaticon\"\n      imgAlt=\"Machine learning vector representation\"\n      imgName=\"machine-learning.png\"\n    />\n    <Card \n      link=\"https://www.flaticon.com/free-icons/business-and-finance\"\n      text=\"Business and finance icons created by Freepik - Flaticon\"\n      imgAlt=\"City security vector\"\n      imgName=\"city-security.png\"\n    />\n    <Card \n      link=\"https://www.flaticon.com/free-icons/credit-card\"\n      text=\"Credit card icons created by Freepik - Flaticon\"\n      imgAlt=\"Credit card vector\"\n      imgName=\"credit-card.png\"\n    />\n    <Card \n      link=\"https://www.flaticon.com/free-icons/deforestation\"\n      text=\"Deforestation icons created by Freepik - Flaticon\"\n      imgAlt=\"Deforestation vector representation\"\n      imgName=\"deforestation.png\"\n    />\n    <Card \n      link=\"https://www.flaticon.com/free-icons/eagle\"\n      text=\"Eagle icons created by Freepik - Flaticon\"\n      imgAlt=\"Eagle vector\"\n      imgName=\"eagle.png\"\n    />\n    <Card \n      link=\"https://www.flaticon.com/free-icons/modern-architecture\"\n      text=\"Modern architecture icons created by Freepik - Flaticon\"\n      imgAlt=\"Modern architecture vector\"\n      imgName=\"modern-architecture.png\"\n    />\n    <Card \n      link=\"https://www.flaticon.com/free-icons/environment\"\n      text=\"Environment icons created by Freepik - Flaticon\"\n      imgAlt=\"Earth planet vector\"\n      imgName=\"planet-earth.png\"\n    />\n  </div>\n  <div class=\"container mx-auto flex flex-row items-center justify-center text-center\">\n    <Card \n      link=\"https://www.flaticon.com/free-icons/police\"\n      text=\"Police icons created by Freepik - Flaticon\"\n      imgAlt=\"Police officer vector\"\n      imgName=\"police.png\"\n    />\n    <Card \n      link=\"https://www.flaticon.com/free-icons/collaboration\"\n      text=\"Collaboration icons created by Freepik - Flaticon\"\n      imgAlt=\"Community vector\"\n      imgName=\"teamwork.png\"\n    />\n  </div>\n  <Footer />\n</template>\n\n<script>\nimport Card from \"../components/Card.vue\";\nimport Navbar from \"../components/Navbar.vue\";\nimport Footer from \"../components/Footer.vue\";\nimport Button from \"../components/Button.vue\";\n\nexport default {\n  name: \"Credits\",\n  components: {\n    Navbar,\n    Footer,\n    Button,\n    Card,\n  },\n};\n</script>\n\n<style scoped></style>\n```\n\n```text\n<template>\n  <Card :image=\"Teamwork\" />\n</template>\n\n<script>\nimport Teamwork from '../../assets/teamwork.png';\n\nexport default {\n  setup: () => {\n    return { Teamwork };\n  }\n};\n</script>\n```\n\n```text\ndata\n```\n\n```text\ncomputed\n```\n\n```text\n<img src=\"@/assets/images/name.png\"/>\n```\n\n```text\n(..)\n```\n\n```text\n@/assets\n```\n\n```text\n@flydev\n```\n\n========================================\n\nComments:\n- The **alias** need to be defined in vite config. It doesn't work out of the box.\n- Oh! Yes. It's pre-defined in Vue2 + Webpack though.","metadata":{"transformedAt":"2026-08-18T18:33:46.437Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":604,"estimatedTokens":3642}}561{"id":"stack-77451464","source":"stackoverflow","questionId":77451464,"title":"Absolute imports: React + TypeScript + Vite","tags":["reactjs","typescript","vite","tsconfig","absolute-path"],"text":"Title: Absolute imports: React + TypeScript + Vite\nTags: reactjs, typescript, vite, tsconfig, absolute-path\nSource: Stack Overflow\n\nQuestion:\n### **Issue**\n\nI have an react app built by `yarn create vite`\n\nI wanted to use absolute imports instead of `\"../../..\"` in my files, but it doesn't work in my React + Vite app.\nAnd everything works fine in IDE. It defines my imports and redirects to my files.\n\nHere is my import in the file.\n\n```\nimport HomePage from '@/pages/HomePage/HomePage.tsx';\n```\n\nBut I've got an error directly at compilation time.\n\n```\n[plugin:vite:import-analysis] Failed to resolve import \"@/pages/HomePage/HomePage.tsx\" from \"src\\routes\\Routes.tsx\". Does the file exist?\n```\n\n### **What I tried**\n\nI configured my tsconfig.json and specified `\"baseUrl\"`, `\"paths\"` and `\"include\"` fields.\n\ntsconfig.json:\n\n```\n{\n \"ts-node\": {\n \"files\": true\n },\n \"compilerOptions\": {\n \"target\": \"ES2020\",\n \"useDefineForClassFields\": true,\n \"lib\": [\"ES2020\", \"DOM\", \"DOM.Iterable\"],\n \"module\": \"ESNext\",\n \"esModuleInterop\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"outDir\": \"dist\",\n \"declaration\": true,\n \"strictNullChecks\": true,\n \"sourceMap\": true,\n \"strict\": true,\n \"skipLibCheck\": true,\n \"jsx\": \"react\",\n \"declarationDir\": \"types\",\n \"moduleResolution\": \"node\",\n \"allowSyntheticDefaultImports\": true,\n \"allowImportingTsExtensions\": true,\n \"emitDeclarationOnly\": true,\n \"baseUrl\": \"src\",\n \"paths\": {\n \"@/*\": [\n \"*\"\n ]\n }\n },\n \"include\": [\n \"src\"\n ],\n \"references\": [{ \"path\": \"./tsconfig.node.json\"}]\n}\n```\n\nvite.config.ts:\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport reactRefresh from '@vitejs/plugin-react-refresh'\nimport path from 'path'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react(), reactRefresh()],\n resolve: {\n alias: {\n '/@': path.resolve(__dirname, 'src'),\n },\n },\n css: {\n modules: {\n localsConvention: 'camelCaseOnly',\n },\n },\n})\n```\n\nIn **WebStorm -> Preferences -> Editor -> Code Style -> JavaScript -> Imports** I checked **Use paths relative to the project, resource or source roots**.\n\nMeanwhile ESLint and WebStorm give no errors.\n\n========================================\n\nCode:\n```text\nimport HomePage from '@/pages/HomePage/HomePage.tsx';\n```\n\n```text\n[plugin:vite:import-analysis] Failed to resolve import \"@/pages/HomePage/HomePage.tsx\" from \"src\\routes\\Routes.tsx\". Does the file exist?\n```\n\n```text\n{\n  \"ts-node\": {\n    \"files\": true\n  },\n  \"compilerOptions\": {\n    \"target\": \"ES2020\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"ES2020\", \"DOM\", \"DOM.Iterable\"],\n    \"module\": \"ESNext\",\n    \"esModuleInterop\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"outDir\": \"dist\",\n    \"declaration\": true,\n    \"strictNullChecks\": true,\n    \"sourceMap\": true,\n    \"strict\": true,\n    \"skipLibCheck\": true,\n    \"jsx\": \"react\",\n    \"declarationDir\": \"types\",\n    \"moduleResolution\": \"node\",\n    \"allowSyntheticDefaultImports\": true,\n    \"allowImportingTsExtensions\": true,\n    \"emitDeclarationOnly\": true,\n    \"baseUrl\": \"src\",\n    \"paths\": {\n      \"@/*\": [\n        \"*\"\n      ]\n    }\n  },\n  \"include\": [\n    \"src\"\n  ],\n  \"references\": [{ \"path\": \"./tsconfig.node.json\"}]\n}\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport reactRefresh from '@vitejs/plugin-react-refresh'\nimport path from 'path'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react(), reactRefresh()],\n  resolve: {\n    alias: {\n      '/@': path.resolve(__dirname, 'src'),\n    },\n  },\n  css: {\n    modules: {\n      localsConvention: 'camelCaseOnly',\n    },\n  },\n})\n```\n\n```text\nyarn create vite\n```\n\n```text\n\"../../..\"\n```\n\n```text\n\"baseUrl\"\n```\n\n```text\n\"paths\"\n```\n\n```text\n\"include\"\n```\n\n```text\nalias: {\n  '/@': path.resolve(__dirname, 'src'),\n},\n```\n\n```text\nalias: {\n  '@': path.resolve(__dirname, 'src'),\n},\n```\n\n========================================\n\nComments:\n- Please read How to Ask, especially the section titled \"Write a title that summarizes the problem\". The current title reads more like the tag list.","metadata":{"transformedAt":"2026-08-18T18:33:46.437Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":203,"estimatedTokens":1022}}562{"id":"stack-78288324","source":"stackoverflow","questionId":78288324,"title":"Failed to resolve component: google-pay-button","tags":["javascript","vue.js","vue-component","vite","google-pay"],"text":"Title: Failed to resolve component: google-pay-button\nTags: javascript, vue.js, vue-component, vite, google-pay\nSource: Stack Overflow\n\nQuestion:\nI am trying to payment integration via GooglePay in Vue.js using google-pay-button. But i am getting warning:\n\nFailed to resolve component: google-pay-button\n\n```\n\nimport \"@google-pay/button-element\";\nexport default {\n ...\n}\n\n```\n\nI am expecting there should be show Google Pay button, but it's showing warning.\n\n========================================\n\nCode:\n```html\n<google-pay-button\n  environment=\"TEST\"\n  v-bind:button-type=\"buttonType\"\n  v-bind:button-color=\"buttonColor\"\n  v-bind:existing-payment-method-required=\"existingPaymentMethodRequired\"\n  v-bind:paymentRequest.prop=\"{\n    apiVersion: paymentRequest.apiVersion,\n    apiVersionMinor: paymentRequest.apiVersionMinor,\n    allowedPaymentMethods: paymentRequest.allowedPaymentMethods,\n    merchantInfo: paymentRequest.merchantInfo,\n    transactionInfo: transactionInfo,\n    callbackIntents: callbackIntents,\n  }\"\n  v-on:loadpaymentdata=\"onLoadPaymentData\"\n  v-on:error=\"onError\"\n  v-bind:onPaymentAuthorized.prop=\"onPaymentDataAuthorized\">\n</google-pay-button>\n\n<script>\nimport \"@google-pay/button-element\";\nexport default {\n  ...\n}\n</script>\n```\n\n```js\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\";\n\nconst customElements = ['google-pay-button'];\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    vue({\n      template: {\n        compilerOptions: {\n          // consider any tag with a dash as a custom element\n          isCustomElement: (tag) => customElements.includes(tag), // can write any condition here, the key is to cover all your custom components, even if it's as simple as tag.startsWith(\"google-pay-\") or any other\n        },\n      },\n    }),\n  ],\n});\n```\n\n```text\n@google-pay/button-element\n```\n\n```text\n<google-pay-button>\n```\n\n```text\n<google-pay-button>\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.437Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":82,"estimatedTokens":484}}563{"id":"stack-76846334","source":"stackoverflow","questionId":76846334,"title":"Automatically import image from relative path in Vuetify3's v-img component","tags":["vuejs3","vite","vuetifyjs3"],"text":"Title: Automatically import image from relative path in Vuetify3's v-img component\nTags: vuejs3, vite, vuetifyjs3\nSource: Stack Overflow\n\nQuestion:\nI am trying to display an image using Vuetify3's `v-img` component. The component works correctly if I pass it an absolute path or a complete url. The problem occurs when I try to use a local image using a relative path.\n\nIf I use the `img` tag directly it works.\n\n**This works:**\n\n```\n \n```\n\n**This also works:**\n\n```\n\n```\n\n**This doesn't:**\n\n```\n \n```\n\nHow do I get the third example to work?\n\n========================================\n\nCode:\n```html\n<v-img src=\"https://some-route/my-remote-image.jpg\"> </v-img>\n```\n\n```html\n<img src=\"@/images/my-local-img.jpg\" />\n```\n\n```html\n<v-img src=\"@/images/my-local-img.jpg\"> </v-img>\n```\n\n```text\nv-img\n```\n\n```text\nimg\n```\n\n```text\n// vite.config.js\nimport vuetify, { transformAssetUrls } from 'vite-plugin-vuetify'\n\nexport default {\n  plugins: [\n    vue({ \n      template: { transformAssetUrls }\n    }),\n    vuetify(),\n  ],\n}\n```\n\n```js\nexport default defineConfig({\n  plugins: [\n    vue({\n      template: {\n        transformAssetUrls: {\n          tags: {\n            'v-img': ['src']  //<----- add v-img\n            // default values will be overridden if not repeated:\n            video: [\"src\", \"poster\"],\n            source: [\"src\"],\n            img: [\"src\"],\n            image: [\"xlink:href\", \"href\"],\n            use: [\"xlink:href\", \"href\"],\n          }\n        }\n      }\n    }),\n    ...\n```\n\n```text\ntemplate.transformAssetUrls\n```\n\n```text\nv-img\n```\n\n```text\nscr\n```\n\n```text\nvite.config.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.437Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":102,"estimatedTokens":400}}564{"id":"stack-74955984","source":"stackoverflow","questionId":74955984,"title":"Vite Build + React 18 - Blank Screen (empty console logs)","tags":["reactjs","typescript","google-chrome","vite"],"text":"Title: Vite Build + React 18 - Blank Screen (empty console logs)\nTags: reactjs, typescript, google-chrome, vite\nSource: Stack Overflow\n\nQuestion:\nI'm working on a Vite/React app. There's a CI process in place that runs the following and pushes the dist bundle to an S3 bucket.\n\n```\nvite build --mode production\n```\n\nI noticed recently that a commit I did caused the application to \"white screen\". React is not rendering the \"App\" component (in main.tsx for instance):\n\n```\nconst container = document.getElementById('root');\nconst root = createRoot(container!);\nroot.render(\n }>\n \n \n \n \n \n ...\n```\n\nWhen looking at the blank page, opening up the console logs and I don't see any stack traces. React dev tools clearly sees React running with a production build. I've tried adding error boundaries to no luck. I'm not sure how to debug which error is causing the component to not render.\n\nI'm able to reproduce this locally. If I run the build command above and then the following:\n\n```\nvite preview\n```\n\nI can see the white page on **localhost:4173**. The odd thing is if I run the following command:\n\n```\nvite dev\n```\n\nI'm able to run the app perfectly fine on **localhost:5173**.\n\nThe dependencies from package.json\n\n```\n{\n\"react\": \"^18.2.0\",\n\"vite\": \"^4.0.3\",\n\"@vitejs/plugin-react\": \"^3.0.0\",\n}\n```\n\nMy Vite config:\n\n```\nimport {defineConfig} from \"vite\";\nimport react from '@vitejs/plugin-react'\n\nexport default ({mode}) => {\n return defineConfig({\n plugins: [\n react(),\n ],\n base: './',\n build: {\n target: 'esnext',\n },\n });\n};\n```\n\nIf in the above code (from main.tsx) I replace\n\n``\n\nwith\n\n`\n\n### it works\n\n`\n\nthis renders perfectly fine on ports 4173 and 5173. Issue is trying to find diagnostic information as to why the App component is not being rendered.\n\n========================================\n\nTop Answer:\nIf there is any error on a console, like any dependencies are undefined,\n\nTry this:\n\nAdd:\n\n```\nimport vue from '@vitejs/plugin-vue'\n```\n\n```\nplugins: [react(), viteTsconfigPaths(), svgrPlugin(), vue()],\n resolve: {\n alias: {\n process: \"process/browser\",\n stream: \"stream-browserify\",\n zlib: \"browserify-zlib\",\n util: 'util',\n '@': path.resolve(__dirname, \"./src\")\n },\n },\n```\n\nThis in the `vite.config.ts` file and install all dependencies which are shown in that error message. Like if `blob-stream` shows an error add this in the alias in `vite.config.ts` and install `blob-stream`\n\n```\nblobStream: \"blob-stream\",\n```\n\n========================================\n\nCode:\n```text\nvite build --mode production\n```\n\n```text\nconst container = document.getElementById('root');\nconst root = createRoot(container!);\nroot.render(\n    <React.Suspense fallback={<></>}>\n        <React.StrictMode>\n            <ProSidebarProvider>\n                <BrowserRouter>\n                    <App/>\n                </BrowserRouter>\n                ...\n```\n\n```text\nvite preview\n```\n\n```text\nvite dev\n```\n\n```text\n{\n\"react\": \"^18.2.0\",\n\"vite\": \"^4.0.3\",\n\"@vitejs/plugin-react\": \"^3.0.0\",\n}\n```\n\n```text\nimport {defineConfig} from \"vite\";\nimport react from '@vitejs/plugin-react'\n\nexport default ({mode}) => {\n    return defineConfig({\n        plugins: [\n            react(),\n        ],\n        base: './',\n        build: {\n            target: 'esnext',\n        },\n    });\n};\n```\n\n```text\n<App />\n```\n\n```text\n<h1>it works</h1>\n```\n\n```text\nconst Searchbar = lazy(() => import(\"../../components/Searchbar/Searchbar\"));\n```\n\n```text\nawait Searchbar.preload();\n```\n\n```text\nSearchbar.preload();\n```\n\n```js\nimport vue from '@vitejs/plugin-vue'\n```\n\n```js\nplugins: [react(), viteTsconfigPaths(), svgrPlugin(), vue()],\n    resolve: {\n        alias: {\n            process: \"process/browser\",\n            stream: \"stream-browserify\",\n            zlib: \"browserify-zlib\",\n            util: 'util',\n            '@': path.resolve(__dirname, \"./src\")\n        },\n    },\n```\n\n```js\nblobStream: \"blob-stream\",\n```\n\n```text\nvite.config.ts\n```\n\n```text\nblob-stream\n```\n\n```text\nvite.config.ts\n```\n\n```text\nblob-stream\n```\n\n========================================\n\nComments:\n- Is the app in a subdirectory on the S3 server? i.e. `https:&#47;&#47;....com&#47;myapp`\n- I'm using Jenkins to push the dist to the S3 bucket behind the Cloudfront distribution. There's no subdirectory, the root domain points to the S3 bucket directly.\n- if it is deployed, how about providing the URL?\n- It may be as simple as setting `index.html` as the default path for all requests if you have not done that on the S3 instance. It sounds like it could be a `react-router` issue too. Make sure you have set package.json `homepage` prop to the deployed URL, the `basepath` attribute on the `` as described in deployment docs for `react-router`.\n- I see a login prompt - it is not blank. Open a different browser or open it in incognito mode.\n- How did you figure this out? I am facing the same kind of issue but I am not using the react-lazy-with-preload package.","metadata":{"transformedAt":"2026-08-18T18:33:46.437Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":236,"estimatedTokens":1231}}565{"id":"stack-74287431","source":"stackoverflow","questionId":74287431,"title":"How to Mount Correctly an In-DOM Root Component Template","tags":["javascript","vue.js","vue-component","vite"],"text":"Title: How to Mount Correctly an In-DOM Root Component Template\nTags: javascript, vue.js, vue-component, vite\nSource: Stack Overflow\n\nQuestion:\nI have obviously a misconception of how the vue3 \"In-DOM Root Component Template\"-mechanism is working. Any hints appreciated!\n\nI modified an example vite project to use \"In-DOM Root Component Template\".\n\nindex.html\n\n```\n\n \n \n \n \n \n \n \n \n \n \n```\n\nmain.js\n\n```\nimport { createApp } from 'vue'\nimport './style.css'\nimport HelloWorld from './components/HelloWorld.vue'\n\nconst app = createApp({})\n\napp.component('HelloWorld',HelloWorld)\n\napp.mount('#app')\n```\n\nHelloWorld is the default example component, installed by vite install.\n\nResult: The rendered output is empty, the div#app-innerHtml is not used as Template as expected.\n\n========================================\n\nCode:\n```text\n<body>\n        <div id=\"app\">\n            <div>\n                <a href=\"https://vitejs.dev\" target=\"_blank\">\n                    <img src=\"/vite.svg\" class=\"logo\" alt=\"Vite logo\" />\n                </a>\n            </div>\n            <hello-world msg=\"Vite + Vue\"></hello-world>\n        </div>\n        <script type=\"module\" src=\"/src/main.js\"></script>\n    </body>\n```\n\n```text\nimport { createApp } from 'vue'\nimport './style.css'\nimport HelloWorld from './components/HelloWorld.vue'\n\nconst app = createApp({})\n\napp.component('HelloWorld',HelloWorld)\n\napp.mount('#app')\n```\n\n```text\nconst app = createApp({})\n```\n\n```text\nconst app = createApp()\n```\n\n```text\nHelloWorld\n```\n\n```text\n<hello-world>\n```\n\n========================================\n\nComments:\n- Consider providing a way to reproduce the problem.\n- Sure, these are the steps to reproduce the problem: 1. npm create vite@latest vitetest -- --template vue 2. cd vitetest 3. npm install 4. edit index.html (as shown above) 5. edit main.js (as shown above) 6. delete App.vue 7. npm run dev\n- Thank you very much for the hints and especially for the explanation - the playground is working with the suggested modifications - unexplainably there is no effect in my vite-setup. The rendered output is still empty. I edited the above code with your suggestions.\n- Then please check your logs and the browser console log for errors.\n- You can also try to replace the code in your setup with the code from sandbox. I guess the Sandbox is also running on Vite. I have also deleted the style.css import, since there is no such file.\n- There were never errors in the console - but rechecking I turned on the warnings also and voila: [Vue warn]: Component provided template option but runtime compilation is not supported in this build of Vue. Configure your bundler to alias \"vue\" to \"vue/dist/vue.esm-bundler.js\". I'll try this one, everthing else should be fixed thanks to your answer!\n- Been ~10 hours struggling with this issue until I found this post. No errors in console nor compilation issues. Changing `import { defineComponent, ...} from 'vue'` to `import { defineComponent, ...} from 'vue&#47;dist&#47;vue.esm-bundler.js'` also worked for me. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:46.437Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":98,"estimatedTokens":760}}566{"id":"stack-74001152","source":"stackoverflow","questionId":74001152,"title":"Vite only importing some of the files in a folder","tags":["laravel","vite","laravel-vite"],"text":"Title: Vite only importing some of the files in a folder\nTags: laravel, vite, laravel-vite\nSource: Stack Overflow\n\nQuestion:\nI'm migrating my Laravel app to Vite, and one of the things I wanted to do is copy over my images assets to the public folder. Following the Laravel doc https://laravel.com/docs/9.x/vite#blade-processing-static-assets I added `import.meta.glob('../images/**');` to my app.js file, and ran the build command.\n\nhttps://i.sstatic.net/gE14d.png\n\nAs you can see there are seven images in the folder. But the command outputted only 3 of them as imported, and sure enough when reloading one of the not imported images was missing : `Unable to locate file in Vite manifest: images/local_icon.png.`\n\ndid I miss something?\n\n========================================\n\nTop Answer:\nAt the first time I also thought that it was a bug from vite. but when I read their documentation I found this is a feature for Vite. If an asset file like (images) whose size is less than 4kb(Default size for vite) is marked as an inline element. and convert it into base64 format so that It loads without sending a request.\n\nSo when we use vite with Laravel we have to override this size. So simply we need this configuration.\n\n```\nexport default defineConfig({\n build: {\n assetsInlineLimit: \"2048\", // 2kb, set as your minimum file size or set 0 to disable the inline limit.\n },\n})\n```\n\nDocumentation link: https://vitejs.dev/config/build-options.html#build-assetsinlinelimit\n\n========================================\n\nCode:\n```text\nimport.meta.glob('../images/**');\n```\n\n```text\nUnable to locate file in Vite manifest: images/local_icon.png.\n```\n\n```text\n\"cpimages\" : \"rm -rf ./public/assets/images; cp -r ./resources/images ./public/assets\"\n```\n\n```text\n\"build\": \"npm run cpimages; vite build\"\n```\n\n```js\nexport default defineConfig({\n    build: {\n        assetsInlineLimit: \"2048\", // 2kb, set as your minimum file size or set 0 to disable the inline limit.\n    },\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.437Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":56,"estimatedTokens":493}}567{"id":"stack-74618188","source":"stackoverflow","questionId":74618188,"title":"Vue 3, Bootstrap 5 cannot reading properties of undefined 'backdrop'","tags":["javascript","vue.js","bootstrap-5","vite","bootstrap5-modal"],"text":"Title: Vue 3, Bootstrap 5 cannot reading properties of undefined 'backdrop'\nTags: javascript, vue.js, bootstrap-5, vite, bootstrap5-modal\nSource: Stack Overflow\n\nQuestion:\nI am trying to use Vue3 (Vite) and Bootstrap 5 to create a modal that is called by code. However, when opening the modal from its parent, an error is thrown.\n\nI have bootstrap installed and included:\n\n`import bootstrap` (main.js)\n\n`import bootstrap/dist/js/bootstrap` does not change anything.\n\nI have created a simple modal that listens for a prop and then opens the modal.\n\nWhen I open it, the error appears:\n`Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'backdrop')`\n\n```\n\n \n \n \n \n \n\n### Error {{ this.occurred }}\n\n \n \n \n {{ this.error_message }}\n\n \n \n OK\n \n \n \n \n\nimport { Modal } from \"bootstrap\"\nexport default {\n props: {\n occurred: String,\n error_message: String,\n show: Boolean,\n },\n components: {\n myModal: null\n },\n data() {\n return {\n }\n },\n methods: {\n },\n mounted() {\n this.myModal = new Modal(document.getElementById('errModal'))\n },\n watch: {\n show: function (newVal, oldVal) { // watch it\n this.cam_prop = newVal.properties\n },\n }\n};\n\n```\n\nCalling from Parent:\n\n```\n\n \n```\n\nCreating the Modal with `new bootstrap.Modal` does not work (bootstrap not defined)\n\nI think the error is importing, but the styling works, could it be Vite?\n\n========================================\n\nCode:\n```text\n<template>\n    <div class=\"modal\" tabindex=\"-1\" id=\"errModal\" aria-labelledby=\"ErrorModalLabel\" aria-hidden=\"true\">\n        <div class=\"modal-dialog\">\n            <div class=\"modal-content\">\n                <div class=\"modal-header\">\n                    <h5 class=\"modal-title\">Error {{ this.occurred }}</h5>\n                    <button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"\n                        aria-label=\"ErrorModalLabel\"></button>\n                </div>\n                <div class=\"modal-body\">\n                    <p>{{ this.error_message }}</p>\n                </div>\n                <div class=\"modal-footer\">\n                    <button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">OK</button>\n                </div>\n            </div>\n        </div>\n    </div>\n</template>\n\n<script>\nimport { Modal } from \"bootstrap\"\nexport default {\n    props: {\n        occurred: String,\n        error_message: String,\n        show: Boolean,\n    },\n    components: {\n        myModal: null\n    },\n    data() {\n        return {\n        }\n    },\n    methods: {\n    },\n    mounted() {\n        this.myModal = new Modal(document.getElementById('errModal'))\n    },\n    watch: {\n        show: function (newVal, oldVal) { // watch it\n            this.cam_prop = newVal.properties\n        },\n    }\n};\n</script>\n```\n\n```text\n<RegIdentErrorModalVue id=\"#ErrModal\" :show=\"this.error\" :occurred=\"'Identification'\" :error_message=\"this.error_text\">\n        </RegIdentErrorModalVue>\n```\n\n```text\nimport bootstrap\n```\n\n```text\nimport bootstrap/dist/js/bootstrap\n```\n\n```text\nUncaught (in promise) TypeError: Cannot read properties of undefined (reading 'backdrop')\n```\n\n```text\nnew bootstrap.Modal\n```\n\n```text\nParent Component\n<template>\n    ...\n    <RegIdentErrorModalVue v-if=\"isMountedComponent\" id=\"#ErrModal\" :show=\"this.error\" :occurred=\"'Identification'\" :error_message=\"this.error_text\" />\n    ...\n</template>\n\n<script>\nexport default {\n    data() {\n        return {\n            isMountedComponent: false,\n        }\n    },\n    mounted() {\n        this.isMountedComponent = true;\n    },\n}\n</script>\n```\n\n========================================\n\nComments:\n- import your library on your component","metadata":{"transformedAt":"2026-08-18T18:33:46.437Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":180,"estimatedTokens":908}}568{"id":"stack-75185245","source":"stackoverflow","questionId":75185245,"title":"Three JS GLTF Loader Not Working with Nuxt 3","tags":["three.js","vuejs3","vite","nuxt3.js","gltf"],"text":"Title: Three JS GLTF Loader Not Working with Nuxt 3\nTags: three.js, vuejs3, vite, nuxt3.js, gltf\nSource: Stack Overflow\n\nQuestion:\nI'm facing an error when implementing three JS Gltf Loader with nuxt 3.\nError message :\n\" Uncaught (in promise) TypeError: Class constructor Loader cannot be invoked without 'new' .. \"\n\nversions:\n\n\"three\": \"^0.148.0\",\n\"three-gltf-loader\": \"^1.111.0\"\n\n```\n\n \n\nimport { ref, onMounted } from \"vue\";\nimport * as THREE from \"three\";\nimport GLTFLoader from \"three-gltf-loader\";\n\nexport default {\n setup() {\n const container = ref(null);\n const scene = ref(new THREE.Scene());\n const renderer = ref(new THREE.WebGLRenderer({ antialias: true }));\n const width = 700;\n const height = 700;\n const camera = ref(\n new THREE.PerspectiveCamera(75, width / height, 0.1, 1000)\n );\n const loader = ref(new GLTFLoader());\n onMounted(async () => {\n renderer.value.setSize(\n container.value.clientWidth,\n container.value.clientHeight\n );\n container.value.appendChild(renderer.value.domElement);\n camera.value.position.z = 5;\n const response = await fetch(\"logo.gltf\");\n const gltf = await response.json();\n loader.value.parse(\n gltf,\n \"\",\n (gltf) => {\n scene.value.add(gltf.scene);\n renderer.value.render(scene.value, camera.value);\n },\n undefined,\n (error) => {\n console.error(error);\n }\n );\n });\n\n return { container };\n },\n};\n\n```\n\n========================================\n\nTop Answer:\n\"three\": \"^0.148.0\", \"three-gltf-loader\": \"^1.111.0\"\n\nThis kind of setup isn't recommended since you can import the latest `GLTFLoader` module from the `three` repository. Try it again with these imports:\n\n```\nimport * as THREE from \"three\";\nimport { GLTFLoader } from \"three/addons/loaders/GLTFLoader.js\";\n```\n\n========================================\n\nCode:\n```text\n<template>\n  <div ref=\"container\"></div>\n</template>\n\n<script>\nimport { ref, onMounted } from \"vue\";\nimport * as THREE from \"three\";\nimport GLTFLoader from \"three-gltf-loader\";\n\nexport default {\n  setup() {\n    const container = ref(null);\n    const scene = ref(new THREE.Scene());\n    const renderer = ref(new THREE.WebGLRenderer({ antialias: true }));\n    const width = 700;\n    const height = 700;\n    const camera = ref(\n      new THREE.PerspectiveCamera(75, width / height, 0.1, 1000)\n    );\n    const loader = ref(new GLTFLoader());\n    onMounted(async () => {\n      renderer.value.setSize(\n        container.value.clientWidth,\n        container.value.clientHeight\n      );\n      container.value.appendChild(renderer.value.domElement);\n      camera.value.position.z = 5;\n      const response = await fetch(\"logo.gltf\");\n      const gltf = await response.json();\n      loader.value.parse(\n        gltf,\n        \"\",\n        (gltf) => {\n          scene.value.add(gltf.scene);\n          renderer.value.render(scene.value, camera.value);\n        },\n        undefined,\n        (error) => {\n          console.error(error);\n        }\n      );\n    });\n\n    return { container };\n  },\n};\n</script>\n```\n\n```text\n<script lang=\"ts\">\nimport { defineComponent, ref, onMounted } from \"vue\";\nimport {\n  Renderer,\n  Scene,\n  Camera,\n  PointLight,\n  AmbientLight,\n  GltfModel,\n} from \"troisjs\";\nexport default defineComponent({\n  components: {\n    Renderer,\n    Scene,\n    Camera,\n    PointLight,\n    AmbientLight,\n    GltfModel,\n  },\n  setup() {\n    const renderer = ref(null);\n    const model = ref(null);\n\n    function onReady(model) {\n      console.log(\"Ready\", model);\n    }\n\n    onMounted(() => {\n      renderer?.value?.onBeforeRender(() => {\n        model.value.rotation.x += 0.01;\n      });\n    });\n\n    return {\n      renderer,\n      model,\n      onReady,\n    };\n  },\n});\n</script>\n\n<template>\n  <div>\n    <Renderer ref=\"renderer\" antialias orbit-ctrl resize=\"window\">\n      <Camera :position=\"{ x: -10, z: 20 }\" />\n      <Scene background=\"#fff\">\n        <AmbientLight />\n        <PointLight\n          color=\"white\"\n          :position=\"{ x: 100, y: 1000, z: 40 }\"\n          :intensity=\"1\"\n        />\n        <GltfModel ref=\"model\" src=\"/Models/logo.gltf\" @load=\"onReady\" />\n      </Scene>\n    </Renderer>\n  </div>\n</template>\n```\n\n```text\nimport * as THREE from \"three\";\nimport { GLTFLoader } from \"three/addons/loaders/GLTFLoader.js\";\n```\n\n```text\nGLTFLoader\n```\n\n```text\nthree\n```\n\n```text\nimport { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'\n```\n\n```text\nconst loader = new GLTFLoader()\n```\n\n========================================\n\nComments:\n- I had a similar error when placing a custom JS class (plain js file) into Nuxt's `\\plugins` folder. Living there, it gets processed by whatever Nuxt does, thus triggering the error (probably to do with Typescript config's ES5 vs ES6 support). In any case, simply moving the offending custom script to folder `&#47;assets&#47;js` was all that was needed. Essentially, plain JS scripts shouldn't live in Nuxt `&#47;plugins` unless you intend for it to actually be a Nuxt plugin =).\n- Not work, the only solution is with TroisJS","metadata":{"transformedAt":"2026-08-18T18:33:46.437Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":214,"estimatedTokens":1240}}569{"id":"stack-76019081","source":"stackoverflow","questionId":76019081,"title":"Mocking Vue RouterView/RouterLink in Vitest (Composition API)","tags":["vue.js","testing","vuejs3","vite","vitest"],"text":"Title: Mocking Vue RouterView/RouterLink in Vitest (Composition API)\nTags: vue.js, testing, vuejs3, vite, vitest\nSource: Stack Overflow\n\nQuestion:\nAs per the title, is this possible at all?\n\nI'm trying to test a simple component of a Vue App, which contains a heading and a button that directs user to the next page. I want the test that once the buttons is clicked an event/message is sent to the router, and check that the destination route is correct.\n\nThe structure of the app is:\n\n**App.Vue** - the entry component\n\n```\n\nimport { RouterView } from \"vue-router\";\nimport Wrapper from \"@/components/Wrapper.vue\";\nimport Container from \"@/components/Container.vue\";\nimport HomeView from \"@/views/HomeView.vue\";\n\n \n \n \n \n \n\n body{\n @apply bg-slate-50 text-slate-800 dark:bg-slate-800 dark:text-slate-50;\n }\n\n```\n\n**router/index.ts** - Vue Router config file\n\n```\nimport {createRouter, createWebHistory} from \"vue-router\";\nimport HomeView from \"@/views/HomeView.vue\";\n\nexport enum RouteNames {\n HOME = \"home\",\n GAME = \"game\",\n}\n\nconst routes = [\n {\n path: \"/\",\n name: RouteNames.HOME,\n component: HomeView,\n alias: \"/home\"\n },\n {\n path: \"/game\",\n name: RouteNames.GAME,\n component: () => import(\"@/views/GameView.vue\"),\n },\n];\n\nconst router = createRouter({\n history: createWebHistory(import.meta.env.BASE_URL),\n routes\n});\n\nexport default router;\n```\n\n**HomeView.Vue** - the entry view for the RouterView in the App component\n\n```\n\n \n \n\n import Header from \"@/components/Header.vue\";\n import ButtonRouterLink from \"@/components/ButtonRouterLink.vue\";\n import {RouteNames} from \"@/router/\";\n\n```\n\n**ButtonRouterLink.vue**\n\n```\n\n {{ text }}\n\nimport { RouterLink } from \"vue-router\";\n\nconst props = defineProps({\n to: String,\n text: String\n})\n\n```\n\n**Considering it's using CompositionAPI, TypeScript, is there any way to mock the router in Vitest tests?**\n\nHere's an example of the test file structure (**HomeView.spec.ts**):\n\n```\nimport {shallowMount} from \"@vue/test-utils\";\nimport { describe, test, vi, expect } from \"vitest\";\nimport { RouteNames } from \"@/router\";\nimport HomeView from \"../../views/HomeView.vue\";\n\ndescribe(\"Home\", () => {\n test ('navigates to game route', async () => {\n // Check if the button navigates to the game route\n\n const wrapper = shallowMount(HomeView);\n\n await wrapper.find('.btn-game').trigger('click');\n\n expect(MOCK_ROUTER.push).toHaveBeenCalledWith({ name: RouteNames.GAME });\n });\n});\n```\n\nI've tried multiple ways: vi.mock('vue-router'), vi.spyOn(useRoute,'push'), vue-router-mock library and I haven't been able to get the tests to run, always seems like the router just isn't there.\n\n### Update (15/04/23)\n\nFollowing @tao 's advice, I realised that testing the click in HomeView is not a very good test (testing libraries rather than my app), so I added a test for **ButtonRouterLink** to see if it renders a Vue RouterLink correctly, using the *to* param:\n\n```\nimport {mount, shallowMount} from \"@vue/test-utils\";\nimport { describe, test, vi, expect } from \"vitest\";\nimport { RouteNames } from \"@/router\";\nimport ButtonRouterLink from \"../ButtonRouterLink.vue\";\n\nvi.mock('vue-router');\n\ndescribe(\"ButtonRouterLink\", () => {\n test (`correctly transforms 'to' param into a router-link prop`, async () => {\n \n const wrapper = mount(ButtonRouterLink, {\n props: {\n to: RouteNames.GAME\n }\n });\n\n expect(wrapper.html()).toMatchSnapshot();\n });\n});\n```\n\nWhich renders an empty HTML string `\"\"`\n\n```\nexports[`ButtonRouterLink > correctly transforms 'to' param into a router-link prop 1`] = `\"\"`;\n```\n\naccompanied by a rather unhelpful Vue warning (no expected types specified) :\n\n```\n[Vue warn]: Invalid prop: type check failed for prop \"to\". Expected , got Object \n at \n at \n at \n[Vue warn]: Invalid prop: type check failed for prop \"ariaCurrentValue\". Expected , got String with value \"page\". \n at \n at \n at \n[Vue warn]: Component is missing template or render function. \n at \n at \n at \n```\n\n========================================\n\nCode:\n```js\n<script setup lang=\"ts\">\nimport { RouterView } from \"vue-router\";\nimport Wrapper from \"@/components/Wrapper.vue\";\nimport Container from \"@/components/Container.vue\";\nimport HomeView from \"@/views/HomeView.vue\";\n</script>\n\n<template>\n  <Wrapper>\n    <Container>\n      <RouterView/>\n    </Container>\n  </Wrapper>\n</template>\n\n<style>\n\n  body{\n    @apply bg-slate-50 text-slate-800 dark:bg-slate-800 dark:text-slate-50;\n  }\n\n</style>\n```\n\n```js\nimport {createRouter, createWebHistory} from \"vue-router\";\nimport HomeView from \"@/views/HomeView.vue\";\n\nexport enum RouteNames {\n    HOME = \"home\",\n    GAME = \"game\",\n}\n\nconst routes = [\n    {\n      path: \"/\",\n      name: RouteNames.HOME,\n      component: HomeView,\n      alias: \"/home\"\n    },\n    {\n      path: \"/game\",\n      name: RouteNames.GAME,\n      component: () => import(\"@/views/GameView.vue\"),\n    },\n];\n\nconst router = createRouter({\n  history: createWebHistory(import.meta.env.BASE_URL),\n  routes\n});\n\nexport default router;\n```\n\n```js\n<template>\n  <Header title=\"My App\"/>\n  <ButtonRouterLink :to=\"RouteNames.GAME\" text=\"Start\" class=\"btn-game\"/>\n</template>\n\n<script setup>\n  import Header from \"@/components/Header.vue\";\n  import ButtonRouterLink from \"@/components/ButtonRouterLink.vue\";\n  import {RouteNames} from \"@/router/\";\n</script>\n```\n\n```js\n<template>\n<RouterLink v-bind:to=\"{name: to}\" class=\"btn\">\n  {{ text }}\n</RouterLink>\n</template>\n\n<script setup>\nimport { RouterLink } from \"vue-router\";\n\nconst props = defineProps({\n  to: String,\n  text: String\n})\n</script>\n```\n\n```js\nimport {shallowMount} from \"@vue/test-utils\";\nimport { describe, test, vi, expect } from \"vitest\";\nimport { RouteNames } from \"@/router\";\nimport HomeView from \"../../views/HomeView.vue\";\n\ndescribe(\"Home\", () => {\n    test ('navigates to game route', async () => {\n        // Check if the button navigates to the game route\n\n        const wrapper = shallowMount(HomeView);\n\n        await wrapper.find('.btn-game').trigger('click');\n\n        expect(MOCK_ROUTER.push).toHaveBeenCalledWith({ name: RouteNames.GAME });\n    });\n});\n```\n\n```js\nimport {mount, shallowMount} from \"@vue/test-utils\";\nimport { describe, test, vi, expect } from \"vitest\";\nimport { RouteNames } from \"@/router\";\nimport ButtonRouterLink from \"../ButtonRouterLink.vue\";\n\nvi.mock('vue-router');\n\ndescribe(\"ButtonRouterLink\", () => {\n    test (`correctly transforms 'to' param into a router-link prop`, async () => {\n       \n        const wrapper = mount(ButtonRouterLink, {\n            props: {\n                to: RouteNames.GAME\n            }\n        });\n\n        expect(wrapper.html()).toMatchSnapshot();\n    });\n});\n```\n\n```js\nexports[`ButtonRouterLink > correctly transforms 'to' param into a router-link prop 1`] = `\"\"`;\n```\n\n```text\n[Vue warn]: Invalid prop: type check failed for prop \"to\". Expected , got Object  \n  at <RouterLink to= { name: 'game' } class=\"btn btn-blue\" > \n  at <ButtonRouterLink to=\"game\" ref=\"VTU_COMPONENT\" > \n  at <VTUROOT>\n[Vue warn]: Invalid prop: type check failed for prop \"ariaCurrentValue\". Expected , got String with value \"page\". \n  at <RouterLink to= { name: 'game' } class=\"btn btn-blue\" > \n  at <ButtonRouterLink to=\"game\" ref=\"VTU_COMPONENT\" > \n  at <VTUROOT>\n[Vue warn]: Component is missing template or render function. \n  at <RouterLink to= { name: 'game' } class=\"btn btn-blue\" > \n  at <ButtonRouterLink to=\"game\" ref=\"VTU_COMPONENT\" > \n  at <VTUROOT>\n```\n\n```text\n\"\"\n```\n\n```js\nimport { RouterLinkStub } from '@vue/test-utils'\n\nconst wrapper = shallowMount(YourComp, {\n  stubs: {\n    RouterLink: RouterLinkStub\n  }\n})\n\nexpect(wrapper.findComponent(RouterLinkStub).props('to')).toEqual({\n  name: RouterNames.GAME\n})\n```\n\n```html\n<span>\n    <RouterLink ... />\n  </span>\n```\n\n```text\nimport { shallowMount } from '@vue/test-utils'\nimport { describe, it, expect } from 'vitest'\nimport ButtonRouterLink from '../src/ButtonRouterLink.vue'\nimport { RouterLinkStub } from '@vue/test-utils'\nimport { RouterLink } from 'vue-router'\n\nconst TEST_STRING = 'this is a test string'\n\ndescribe('ButtonRouterLink', () => {\n  it(`should transform 'to' into '{ name: to }'`, () => {\n    const wrapper = shallowMount(ButtonRouterLink, {\n      props: {\n        to: TEST_STRING\n      },\n      stubs: {\n        RouterLink: RouterLinkStub\n      }\n    })\n\n    expect(wrapper.findComponent(RouterLink).props('to')).toEqual({\n      name: TEST_STRING\n    })\n  })\n})\n```\n\n```text\nRouterLink\n```\n\n```text\nrouter.push\n```\n\n```text\nshallowMount\n```\n\n```text\nButtonRouterLink\n```\n\n```text\nRouterLink\n```\n\n```text\nmount\n```\n\n```text\nshallowMount\n```\n\n```text\nButtonRouterLink\n```\n\n```text\n:to\n```\n\n```text\n{ name: to }\n```\n\n```text\n:to\n```\n\n```text\n<ButtonRouterLink />\n```\n\n```text\n:to\n```\n\n```text\n{ name: RouterNames.GAME }\n```\n\n```text\n'game'\n```\n\n```text\nButtonRouterLink\n```\n\n```text\nvalue\n```\n\n```text\n{ name: value }\n```\n\n```text\n<RouterLink />\n```\n\n```text\n<BottomRouterLink>\n```\n\n```text\n<RouterLinkStub>\n```\n\n```text\n:to\n```\n\n```text\nRouterLink\n```\n\n```text\nvue-router\n```\n\n```text\nRouterLinkStub\n```\n\n```text\n@vue/test-utils\n```\n\n```text\n.findComponent()\n```\n\n```text\nButtonRouterLink\n```\n\n```text\n:to\n```\n\n```text\nRouterLink\n```\n\n========================================\n\nComments:\n- Thank you for such a comprehensive answer, especially the advice with snapshots vs console.log(), it's helpful to understand what's actually being rendered. Also, I see that there isn't much point in testing HomeView button trigger, as I'm not testing any custom behaviours there. I tried testing ButtonRouterLink as you suggested, I used **mount** on the component, passed a test route name as *to* parameter and took a snapshot to see what renders, but it rendered an empty string \"\", accompanied by rather unhelpful Vue warning (updated question with the test and the warning message).\n- @h0nter, I had to spin a project for a couple of hours until I got to the bottom of it, going through docs and making console bleed to death. See the update to the answer.\n- @Pipetus, do you consider i would have been nicer if I didn't give you the advice? Because I believe the opposite. The main difference between our definitions of being nice is that you consider the person's feelings on a very short time scale, whereas I have a longer one in mind. The funny thing is that you're remembered by how people felt in the moment, not by how you make them feel in the future, if you manage to change them for the better. But I guess that's my problem. Thanks for being nice and honest with me. Happy coding!\n- That's some really impressive debugging work, thank you so much for your help with this. Now it all makes sense why it wouldn't match the object correctly, so it answers my question. There are two things in your answer, I wanted to check, first, wrapping the ButtonRouterLink in doesn't seem to have any effect as the test errors with: `Error: Cannot call props on an empty VueWrapper.` as the `wrapper.findComponent(RouterLinkStub)` is a null object. Second, in your final answer, I think we don't need to specify the RouterLink stub, as shallowMount will handle it automatically\n- I'm surprised it doesn't work when it's not root element, it doesn't make sense. `RouterLinkStub` should ***never*** have a `:to` equal to the string value, it should always be an object, except when it replaces an element with a string `:to`. I might look into it later, but it definitely won't be today.\n- Thanks and don't worry, it's not really much of a problem any more since you've answered my question and I have a working test. It's just my curiosity now, why it doesn't work in a consistent way.","metadata":{"transformedAt":"2026-08-18T18:33:46.437Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":42,"totalLines":496,"estimatedTokens":2898}}570{"id":"stack-73699951","source":"stackoverflow","questionId":73699951,"title":"Vite: ?inline not working as expected when loading css for TinyMCE","tags":["laravel","tinymce","vite"],"text":"Title: Vite: ?inline not working as expected when loading css for TinyMCE\nTags: laravel, tinymce, vite\nSource: Stack Overflow\n\nQuestion:\nI am implementing self hosted TinyMCE in my application.\n\nI am referring this link for the implementation. Here is my code\n\n```\n/* TinyMCE scripts loading here. All good! */\nimport contentUiCss from 'tinymce/skins/ui/oxide/content.css?inline';\nimport contentCss from 'tinymce/skins/content/default/content.css?inline';\n\ntinymce.init({\n selector: '#my_text_area',\n inline: true,\n menubar: false,\n toolbar: 'undo redo | bold italic underline | alignleft aligncenter alignright',\n placeholder: 'Write your text here',\n skin: false, // skin is loaded manually above as an import\n content_css: false, // loaded manually directly below\n content_style: [contentCss, contentUiCss].join('\\n'),\n});\n```\n\nThe contents from `content.css` and `contentUiCss` are also getting injected in my `` section which is causing the css conflicts.\n\nAs per the fix of Vite, it should not happen this way. Where am I getting wrong?\n\n**Vite version: 3.1.0**\n\nPS: Tried with `?raw` as well but no luck!\n\n========================================\n\nCode:\n```text\n/* TinyMCE scripts loading here. All good! */\nimport contentUiCss from 'tinymce/skins/ui/oxide/content.css?inline';\nimport contentCss from 'tinymce/skins/content/default/content.css?inline';\n\ntinymce.init({\n    selector: '#my_text_area',\n    inline: true,\n    menubar: false,\n    toolbar: 'undo redo | bold italic underline | alignleft aligncenter alignright',\n    placeholder: 'Write your text here',\n    skin: false, // skin is loaded manually above as an import\n    content_css: false, // loaded manually directly below\n    content_style: [contentCss, contentUiCss].join('\\n'),\n});\n```\n\n```text\ncontent.css\n```\n\n```text\ncontentUiCss\n```\n\n```text\n<head>\n```\n\n```text\n?raw\n```\n\n```text\nimport contentUiCss from 'tinymce/skins/ui/oxide/content.inline.css?inline';\n\ntinymce.init({\n    selector: '#my_text_area',\n    inline: true,\n    menubar: false,\n    toolbar: 'undo redo | bold italic underline | alignleft aligncenter alignright',\n    placeholder: 'Write your text here',\n    skin: false, // skin is loaded manually above as an import\n    content_css: false, // loaded manually directly below\n    content_style: contentUiCss,\n});\n```\n\n```text\ntinymce/skins/content/default/content.css\n```\n\n```text\ntinymce/skins/ui/oxide/content.inline.css\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.437Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":92,"estimatedTokens":604}}571{"id":"stack-73509437","source":"stackoverflow","questionId":73509437,"title":"Vite 3.0.9 not compiling scss files with Laravel v9.26.1","tags":["sass","node-modules","vite","laravel-9"],"text":"Title: Vite 3.0.9 not compiling scss files with Laravel v9.26.1\nTags: sass, node-modules, vite, laravel-9\nSource: Stack Overflow\n\nQuestion:\nbasically having a slight compilation issue with Vite.js. The following code is my vite config:\n\n```\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\n\nexport default defineConfig({\n plugins: [\n laravel({\n input: [\n 'resources/scss/app.scss',\n 'resources/js/app.js',\n ],\n refresh: true,\n }),\n ],\n});\n```\n\nFor some reason the `~` in the app.scss does not work. I think this comes from the sass loader originally but not 100% sure on how to get this to work. My `app.scss` looks like:\n\n```\n// Variables\n@import 'variables';\n\n// ADMINLTE\n@import '~admin-lte/build/scss/adminlte';\n```\n\nIf I remove the `~` it still compiles but the sub package AdminLTE has many `~` references within the package and the error is:\n\n```\nError: Can't find stylesheet to import.\n ╷\n 10 │ @import \"~bootstrap/scss/functions\";\n │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n```\n\nwhich is inside the adminlte.scss (inside node_modules).\n\nI have looked at a couple of fixes, but from the docs it says to use `npm add -D sass` which I have installed. Not sure if I need to revert to Laravel Mix as this does it out of the box, or is there a fix I haven't found like importing and using `sass-loader`?\n\nAny support would be very greatful.\n\n========================================\n\nTop Answer:\nchange\n\n```\n@vite(['resources/css/app.css']);\n```\n\nto\n\n```\n@vite(['resources/sass/app.scss'])\n```\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite';\nimport laravel from 'laravel-vite-plugin';\n\nexport default defineConfig({\n    plugins: [\n        laravel({\n            input: [\n                'resources/scss/app.scss',\n                'resources/js/app.js',\n            ],\n            refresh: true,\n        }),\n    ],\n});\n```\n\n```text\n// Variables\n@import 'variables';\n\n// ADMINLTE\n@import '~admin-lte/build/scss/adminlte';\n```\n\n```text\nError: Can't find stylesheet to import.\n     ╷\n  10 │ @import \"~bootstrap/scss/functions\";\n     │         ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n```\n\n```text\n~\n```\n\n```text\napp.scss\n```\n\n```text\n~\n```\n\n```text\n~\n```\n\n```text\nnpm add -D sass\n```\n\n```text\nsass-loader\n```\n\n```text\n@import \"~bootstrap/scss/functions\";\n```\n\n```text\n@import \"bootstrap/scss/functions\";\n```\n\n```text\n@vite(['resources/css/app.css']);\n```\n\n```text\n@vite(['resources/sass/app.scss'])\n```\n\n========================================\n\nComments:\n- stackoverflow.com/a/76139847/14344959\n- Thanks, It would be nice if there was a standard way to load packages... Seems like each build tool does it differently.\n- OP clearly says `@import \"~bootstrap&#47;scss&#47;functions\";` is within a package. Why is this marked as a solution?","metadata":{"transformedAt":"2026-08-18T18:33:46.437Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":145,"estimatedTokens":697}}572{"id":"stack-71810121","source":"stackoverflow","questionId":71810121,"title":"Unable to update fonts on html using vite and custom local fonts","tags":["css","reactjs","fonts","vite"],"text":"Title: Unable to update fonts on html using vite and custom local fonts\nTags: css, reactjs, fonts, vite\nSource: Stack Overflow\n\nQuestion:\nI using Vite as a builder in my ReactJS project and trying to add custom fonts to my website. However, I do not see any change in the browser view after adding the required code.\n\nHere's my code:\n\n```\n/* fonts.scss */\n@font-face {\n font-family: 'sohne';\n src: url('../../fonts/sohne/Sohne-Extraleicht.otf') format('otf');\n font-weight: 200;\n font-style: normal;\n}\n\n@font-face {\n font-family: 'sohne';\n src: url('../../fonts/sohne/Sohne-ExtraleichtKursiv.otf') format('otf');\n font-weight: 200;\n font-style: italic;\n}\n\n/* ...and a few other styles */\n```\n\nI have included this in vite.config.js and used the vite-plugin-fonts\n\n```\nimport ViteFonts from 'vite-plugin-fonts';\n\nexport default defineConfig({\n plugins: [\n ViteFonts({\n custom: {\n families: {\n 'sohne': './src/assets/fonts/sohne/Sohne*.otf'\n }\n }\n })\n ]\n})\n```\n\nthis is how I am using it in my CSS styling:\n\n```\n.some-class {\n font-family: 'sohne';\n}\n```\n\n========================================\n\nCode:\n```css\n/* fonts.scss */\n@font-face {\n    font-family: 'sohne';\n    src: url('../../fonts/sohne/Sohne-Extraleicht.otf') format('otf');\n    font-weight: 200;\n    font-style: normal;\n}\n\n@font-face {\n    font-family: 'sohne';\n    src: url('../../fonts/sohne/Sohne-ExtraleichtKursiv.otf') format('otf');\n    font-weight: 200;\n    font-style: italic;\n}\n\n/* ...and a few other styles */\n```\n\n```js\nimport ViteFonts from 'vite-plugin-fonts';\n\nexport default defineConfig({\n    plugins: [\n        ViteFonts({\n            custom: {\n                families: {\n                    'sohne': './src/assets/fonts/sohne/Sohne*.otf'\n                }\n            }\n        })\n    ]\n})\n```\n\n```css\n.some-class {\n  font-family: 'sohne';\n}\n```\n\n```css\n@font-face {\n  font-family: 'Roboto';\n  font-style: normal;\n  font-weight: 300;\n  src: url('/fonts/roboto-300.woff2') format('woff2'),\n    url('/fonts/roboto-300.woff') format('woff'),\n    url('/fonts/roboto-300.ttf') format('truetype');\n}\n```\n\n```text\nurl('/fonts/...\n```\n\n```text\npublic\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.437Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":116,"estimatedTokens":532}}573{"id":"stack-70530986","source":"stackoverflow","questionId":70530986,"title":"Invalid value for prop `css` when using @emotion/react with Vite","tags":["reactjs","storybook","vite","emotion"],"text":"Title: Invalid value for prop `css` when using @emotion/react with Vite\nTags: reactjs, storybook, vite, emotion\nSource: Stack Overflow\n\nQuestion:\nI couldn't find any information on how to make @emotion/react work in Storybook when using Vite as a bundler in a React application.\n\nI'm getting errors like `Invalid value for prop 'css' in tag` in almost every story.\nEven though, @emotion/react is working fine for the webapp itself.\n\nHere's my `vite.config.js` configuration:\n\n```\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\n\nexport default defineConfig({\n esbuild: {\n jsxFactory: 'jsx',\n jsxInject: `import { jsx } from '@emotion/react'`,\n },\n plugins: [\n react({\n jsxImportSource: '@emotion/react',\n babel: {\n plugins: ['@emotion/babel-plugin'],\n },\n }),\n ],\n});\n```\n\nAnd here's my `main.js` for Storybook:\n\n```\nconst svgrPlugin = require('vite-plugin-svgr');\n\nmodule.exports = {\n core: {\n builder: 'storybook-builder-vite',\n },\n stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],\n addons: ['@storybook/addon-links', '@storybook/addon-essentials'],\n viteFinal: (config, { configType }) => {\n config.define = {\n 'window.process': {\n env: {\n NODE_ENV: configType.toLowerCase(),\n },\n },\n };\n return {\n ...config,\n plugins: [\n ...config.plugins,\n svgrPlugin({\n svgrOptions: {\n icon: true,\n },\n }),\n ],\n };\n },\n};\n```\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\n\nexport default defineConfig({\n  esbuild: {\n    jsxFactory: 'jsx',\n    jsxInject: `import { jsx } from '@emotion/react'`,\n  },\n  plugins: [\n    react({\n      jsxImportSource: '@emotion/react',\n      babel: {\n        plugins: ['@emotion/babel-plugin'],\n      },\n    }),\n  ],\n});\n```\n\n```text\nconst svgrPlugin = require('vite-plugin-svgr');\n\nmodule.exports = {\n  core: {\n    builder: 'storybook-builder-vite',\n  },\n  stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],\n  addons: ['@storybook/addon-links', '@storybook/addon-essentials'],\n  viteFinal: (config, { configType }) => {\n    config.define = {\n      'window.process': {\n        env: {\n          NODE_ENV: configType.toLowerCase(),\n        },\n      },\n    };\n    return {\n      ...config,\n      plugins: [\n        ...config.plugins,\n        svgrPlugin({\n          svgrOptions: {\n            icon: true,\n          },\n        }),\n      ],\n    };\n  },\n};\n```\n\n```text\nInvalid value for prop 'css' in <div> tag\n```\n\n```text\nvite.config.js\n```\n\n```text\nmain.js\n```\n\n========================================\n\nComments:\n- While the answer might address the question, posting only links is not encouraged because the target page might cease to exist in the future. While links are allowed, always consider to include at least the relevant content to your question.","metadata":{"transformedAt":"2026-08-18T18:33:46.437Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":137,"estimatedTokens":713}}574{"id":"stack-72359734","source":"stackoverflow","questionId":72359734,"title":"vite - Subpage with relative asset path","tags":["vue.js","relative-path","vite"],"text":"Title: vite - Subpage with relative asset path\nTags: vue.js, relative-path, vite\nSource: Stack Overflow\n\nQuestion:\nI have a Vue project with multiple pages where I use `rollupOptions.input` to specify them as entry points:\n\n```\nrollupOptions: {\n input: {\n main: resolve(__dirname, \"index.html\"),\n subpage1: resolve(__dirname, \"subpage1/index.html\"),\n subpage2: resolve(__dirname, \"subpage2/index.html\")\n }\n},\n```\n\nThe final dist folder will be deployed at a subdirectory in a server,\nso I then set a `base` attribute as `base: \"\",` to make the assets work for the main `index.html` . This turns all the paths into something relative like this: ``. Works for the root `index.html` but for the subpages, the links look identical. This however doesn't work, because the folder structure is something like:\n\n```\n├── index.html\n├── assets\n ├── main.35431485.css\n └── ...\n└── subpage1\n └── index.html\n```\n\nAs such, `subpage1/assets/main.35431485.css` will simply not work.\nIs there a way to tell vite to relatively path its way to the asset folder, even for subpages?\nIdeally not using a static parent directory (like with `base: \"/some/dir/\"`), but keeping it all relative?\n\n========================================\n\nCode:\n```js\nrollupOptions: {\n    input: {\n        main: resolve(__dirname, \"index.html\"),\n        subpage1: resolve(__dirname, \"subpage1/index.html\"),\n        subpage2: resolve(__dirname, \"subpage2/index.html\")\n    }\n},\n```\n\n```text\n├── index.html\n├── assets\n    ├── main.35431485.css\n    └── ...\n└── subpage1\n    └── index.html\n```\n\n```text\nrollupOptions.input\n```\n\n```text\nbase\n```\n\n```text\nbase: \"\",\n```\n\n```text\nindex.html\n```\n\n```text\n<link rel=\"stylesheet\" href=\"assets/main.35431485.css\">\n```\n\n```text\nindex.html\n```\n\n```text\nsubpage1/assets/main.35431485.css\n```\n\n```text\nbase: \"/some/dir/\"\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.437Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":86,"estimatedTokens":454}}575{"id":"stack-72426211","source":"stackoverflow","questionId":72426211,"title":"Vue3: injection \"Symbol(pinia)\" not found","tags":["javascript","vue.js","vite","quasar-framework","pinia"],"text":"Title: Vue3: injection \"Symbol(pinia)\" not found\nTags: javascript, vue.js, vite, quasar-framework, pinia\nSource: Stack Overflow\n\nQuestion:\nI am using Vue 3 + Vite plugin for Quasar + Pinia for Store management. I followed all official documentation (Quasar, Pinia). But I am getting this error.\n\n```\n[Vue warn]: injection \"Symbol(pinia)\" not found. \n ...\n runtime-core.esm-bundler.js:38 [Vue warn]: Unhandled error during execution of setup function \n at ref=Ref > \n...\n runtime-core.esm-bundler.js:38 [Vue warn]: Unhandled error during execution of scheduler flush. This is likely a Vue internals bug. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/core \n \n pinia.esm-browser.js:1638 Uncaught (in promise) Error: [🍍]: getActivePinia was called with no active Pinia. Did you forget to install pinia?\n const pinia = createPinia()\n app.use(pinia)\n This will fail in production.\n at useStore (pinia.esm-browser.js:1638:19)\n \n js:185:25)\n```\n\nmain.js\n\n```\nimport {createApp} from 'vue'\nimport {Notify, Quasar} from 'quasar'\n\n// Import icon libraries\nimport '@quasar/extras/roboto-font-latin-ext/roboto-font-latin-ext.css'\nimport '@quasar/extras/material-icons-round/material-icons-round.css'\n\n// A few examples for animations from Animate.css:\n// import @quasar/extras/animate/fadeIn.css\n// import @quasar/extras/animate/fadeOut.css\n// Import Quasar css\nimport 'quasar/src/css/index.sass'\n\n// Import icon libraries\nimport '@quasar/extras/material-icons/material-icons.css'\nimport '@quasar/extras/material-icons-sharp/material-icons-sharp.css'\n\n// Assumes your root component is App.vue\n// and placed in same folder as main.js\nimport App from './App.vue'\nimport router from \"./router/router\";\nimport i18n from \"./i18n/i18n\"\nimport {createPinia} from \"pinia/dist/pinia\";\nimport {useLoginStore} from \"./stores/login\";\n\nconst app = createApp(App)\n\n// app.config.globalProperties.loginStore = useLoginStore();\napp.use(Quasar, {\n plugins: {\n Notify,\n }, // import Quasar plugins and add here\n})\napp.use(router)\n\napp.use(i18n)\napp.use(createPinia())\n// Assumes you have a in your router.html\napp.mount('#app')\n```\n\n**And I am recieving this error after adding 'const store = useLoginStore()' to the component's code.**\n\n```\n\nimport {ref} from 'vue'\nimport {storeToRefs} from 'pinia'\nimport {useLoginStore} from '../../stores/login'\nimport {useQuasar} from 'quasar'\n\nconst $q = useQuasar()\n\nconst email = ref(null)\nconst password = ref(null)\n\nconst store = useLoginStore()\nconst {loginEmail} = storeToRefs(store)\n\n```\n\nWhat is the problem and how to fix it?\n\n========================================\n\nTop Answer:\nFor me it was :\n`import { isTemplateNode } from '@vue/compiler-core'`\n\nCut and reload the server works fine\n\n========================================\n\nCode:\n```text\n[Vue warn]: injection \"Symbol(pinia)\" not found. \n    ...\n    runtime-core.esm-bundler.js:38 [Vue warn]: Unhandled error during execution of setup function \n      at <ViewLogin onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > \n...\n    runtime-core.esm-bundler.js:38 [Vue warn]: Unhandled error during execution of scheduler flush. This is likely a Vue internals bug. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/core \n      \n    pinia.esm-browser.js:1638 Uncaught (in promise) Error: [🍍]: getActivePinia was called with no active Pinia. Did you forget to install pinia?\n        const pinia = createPinia()\n        app.use(pinia)\n    This will fail in production.\n        at useStore (pinia.esm-browser.js:1638:19)\n       \n    js:185:25)\n```\n\n```text\nimport {createApp} from 'vue'\nimport {Notify, Quasar} from 'quasar'\n\n\n// Import icon libraries\nimport '@quasar/extras/roboto-font-latin-ext/roboto-font-latin-ext.css'\nimport '@quasar/extras/material-icons-round/material-icons-round.css'\n\n// A few examples for animations from Animate.css:\n// import @quasar/extras/animate/fadeIn.css\n// import @quasar/extras/animate/fadeOut.css\n// Import Quasar css\nimport 'quasar/src/css/index.sass'\n\n// Import icon libraries\nimport '@quasar/extras/material-icons/material-icons.css'\nimport '@quasar/extras/material-icons-sharp/material-icons-sharp.css'\n\n// Assumes your root component is App.vue\n// and placed in same folder as main.js\nimport App from './App.vue'\nimport router from \"./router/router\";\nimport i18n from \"./i18n/i18n\"\nimport {createPinia} from \"pinia/dist/pinia\";\nimport {useLoginStore} from \"./stores/login\";\n\nconst app = createApp(App)\n\n// app.config.globalProperties.loginStore = useLoginStore();\napp.use(Quasar, {\n    plugins: {\n        Notify,\n    }, // import Quasar plugins and add here\n})\napp.use(router)\n\napp.use(i18n)\napp.use(createPinia())\n// Assumes you have a <div id=\"app\"></div> in your router.html\napp.mount('#app')\n```\n\n```text\n<script setup>\nimport {ref} from 'vue'\nimport {storeToRefs} from 'pinia'\nimport {useLoginStore} from '../../stores/login'\nimport {useQuasar} from 'quasar'\n\nconst $q = useQuasar()\n\nconst email = ref(null)\nconst password = ref(null)\n\nconst store = useLoginStore()\nconst {loginEmail} = storeToRefs(store)\n\n\n</script>\n```\n\n```text\nimport {createPinia} from \"pinia/dist/pinia\";\n```\n\n```text\nimport {createPinia} from 'pinia'\n```\n\n```text\nimport { isTemplateNode } from '@vue/compiler-core'\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.438Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":190,"estimatedTokens":1313}}576{"id":"stack-77913723","source":"stackoverflow","questionId":77913723,"title":"Angular 17 ng serve --host Vite invalid URL error","tags":["angular","compiler-errors","vite"],"text":"Title: Angular 17 ng serve --host Vite invalid URL error\nTags: angular, compiler-errors, vite\nSource: Stack Overflow\n\nQuestion:\nWhile I was trying to serve my application with host option, I've got this error.\n\n```\n[vite] Internal server error: Invalid URL\n at new URL (node:internal/url:775:36)\n at /home/user/Works/2024/node_modules/@angular-devkit/build-angular/src/builders/dev-server/vite-server.js:510:44\n at /home/user/Works/2024/node_modules/@angular-devkit/build-angular/src/builders/dev-server/vite-server.js:551:55\n at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n```\n\nBefore Vite is used in Angular build system, there was no problem with internal or external static IPs. I didn't find any solution to fix it. Thanks in advance for any solution.\n\nI've tried `--disable-host-check` but this issue is still on.\nAlso necessary ports are open and IPv4 connected with static local IP.\nServing at localhost is fine. Checked XAMPP to test IP health to serve, fine too.\n\n```\n\"scripts\": {\n \"ng\": \"ng\",\n \"start\": \"ng serve\",\n \"build\": \"ng build\",\n \"watch\": \"ng build --watch --configuration development\",\n \"test\": \"ng test\",\n \"serve:ssr:2024\": \"node dist/2024/server/server.mjs\"\n },\n \"private\": true,\n \"dependencies\": {\n \"@angular/animations\": \"^17.0.0\",\n \"@angular/common\": \"^17.0.0\",\n \"@angular/compiler\": \"^17.0.0\",\n \"@angular/core\": \"^17.0.0\",\n \"@angular/forms\": \"^17.0.0\",\n \"@angular/platform-browser\": \"^17.0.0\",\n \"@angular/platform-browser-dynamic\": \"^17.0.0\",\n \"@angular/platform-server\": \"^17.0.0\",\n \"@angular/router\": \"^17.0.0\",\n \"@angular/ssr\": \"^17.0.10\",\n \"bootstrap\": \"^5.3.2\",\n \"express\": \"^4.18.2\",\n \"rxjs\": \"~7.8.0\",\n \"tslib\": \"^2.3.0\",\n \"xlsx\": \"^0.18.5\",\n \"zone.js\": \"~0.14.2\"\n },\n \"devDependencies\": {\n \"@angular-devkit/build-angular\": \"^17.0.10\",\n \"@angular/cli\": \"^17.0.10\",\n \"@angular/compiler-cli\": \"^17.0.0\",\n \"@types/express\": \"^4.17.17\",\n \"@types/jasmine\": \"~5.1.0\",\n \"@types/node\": \"^18.18.0\",\n \"jasmine-core\": \"~5.1.0\",\n \"karma\": \"~6.4.0\",\n \"karma-chrome-launcher\": \"~3.2.0\",\n \"karma-coverage\": \"~2.2.0\",\n \"karma-jasmine\": \"~5.1.0\",\n \"karma-jasmine-html-reporter\": \"~2.1.0\",\n \"typescript\": \"~5.2.2\"\n }\n```\n\n========================================\n\nCode:\n```text\n[vite] Internal server error: Invalid URL\n      at new URL (node:internal/url:775:36)\n      at /home/user/Works/2024/node_modules/@angular-devkit/build-angular/src/builders/dev-server/vite-server.js:510:44\n      at /home/user/Works/2024/node_modules/@angular-devkit/build-angular/src/builders/dev-server/vite-server.js:551:55\n      at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n```\n\n```text\n\"scripts\": {\n    \"ng\": \"ng\",\n    \"start\": \"ng serve\",\n    \"build\": \"ng build\",\n    \"watch\": \"ng build --watch --configuration development\",\n    \"test\": \"ng test\",\n    \"serve:ssr:2024\": \"node dist/2024/server/server.mjs\"\n  },\n  \"private\": true,\n  \"dependencies\": {\n    \"@angular/animations\": \"^17.0.0\",\n    \"@angular/common\": \"^17.0.0\",\n    \"@angular/compiler\": \"^17.0.0\",\n    \"@angular/core\": \"^17.0.0\",\n    \"@angular/forms\": \"^17.0.0\",\n    \"@angular/platform-browser\": \"^17.0.0\",\n    \"@angular/platform-browser-dynamic\": \"^17.0.0\",\n    \"@angular/platform-server\": \"^17.0.0\",\n    \"@angular/router\": \"^17.0.0\",\n    \"@angular/ssr\": \"^17.0.10\",\n    \"bootstrap\": \"^5.3.2\",\n    \"express\": \"^4.18.2\",\n    \"rxjs\": \"~7.8.0\",\n    \"tslib\": \"^2.3.0\",\n    \"xlsx\": \"^0.18.5\",\n    \"zone.js\": \"~0.14.2\"\n  },\n  \"devDependencies\": {\n    \"@angular-devkit/build-angular\": \"^17.0.10\",\n    \"@angular/cli\": \"^17.0.10\",\n    \"@angular/compiler-cli\": \"^17.0.0\",\n    \"@types/express\": \"^4.17.17\",\n    \"@types/jasmine\": \"~5.1.0\",\n    \"@types/node\": \"^18.18.0\",\n    \"jasmine-core\": \"~5.1.0\",\n    \"karma\": \"~6.4.0\",\n    \"karma-chrome-launcher\": \"~3.2.0\",\n    \"karma-coverage\": \"~2.2.0\",\n    \"karma-jasmine\": \"~5.1.0\",\n    \"karma-jasmine-html-reporter\": \"~2.1.0\",\n    \"typescript\": \"~5.2.2\"\n  }\n```\n\n```text\n--disable-host-check\n```\n\n```text\ntransformIndexHtmlAndAddHeaders(req.url, rawHtml, res, next, async (html) => {\n                        const { content } = await (0, render_page_1.renderPage)({\n                            document: html,\n                            route: new URL(req.originalUrl ?? '/', server.resolvedUrls?.local[0]).toString(),\n                            serverContext: 'ssr',\n                            loadBundle: (uri) => \n                            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                            server.ssrLoadModule(uri.slice(1)),\n                            // Files here are only needed for critical CSS inlining.\n                            outputFiles: {},\n                            // TODO: add support for critical css inlining.\n                            inlineCriticalCss: false,\n                        });\n                        return indexHtmlTransformer && content ? await indexHtmlTransformer(content) : content;\n                    });\n```\n\n```text\ntransformIndexHtmlAndAddHeaders(req.url, rawHtml, res, next, async (html) => {\n                    const resolvedUrls = server.resolvedUrls;\n                    const baseUrl = resolvedUrls?.local[0] ?? resolvedUrls?.network[0];\n                    \n                    const { content } = await (0, render_page_1.renderPage)({\n                        document: html,\n                        route: new URL(req.originalUrl ?? '/', baseUrl).toString(),\n                        serverContext: 'ssr',\n                        loadBundle: (uri) => \n                        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                        server.ssrLoadModule(uri.slice(1)),\n                        // Files here are only needed for critical CSS inlining.\n                        outputFiles: {},\n                        // TODO: add support for critical css inlining.\n                        inlineCriticalCss: false,\n                    });\n                    return indexHtmlTransformer && content ? await indexHtmlTransformer(content) : content;\n                });\n```\n\n```text\nng serve --host xxx.xxx.x.\n```\n\n========================================\n\nComments:\n- I'm also having the same problem. Did you manage to solve it?\n- I'm also facing same problem. have you find the solution?\n- I reported this `bug` see this github.com/angular/angular-cli/issues/27327#issue-2199422954 . see this pull request github.com/angular/angular-cli/pull/27330\n- I posted an answer how to fix.","metadata":{"transformedAt":"2026-08-18T18:33:46.438Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":176,"estimatedTokens":1617}}577{"id":"stack-73082293","source":"stackoverflow","questionId":73082293,"title":"@vite directive in dev mode inserts invalid path","tags":["laravel","vite"],"text":"Title: @vite directive in dev mode inserts invalid path\nTags: laravel, vite\nSource: Stack Overflow\n\nQuestion:\nGood day.\n\n- fresh installation of laravel\n\n- correct address in .env APP_URL\n\n- @vite(['resources/css/app.css']) is written in the blade template\n\n- running npm run dev works fine\n\nWhen I go to the local address of the site in html, I see the following:\n\n```\n\n \n```\n\nStyles are not loaded, changing styles does not automatically reload the page.\n\nWhat could be the problem?\n\n========================================\n\nCode:\n```text\n<script type=\"module\" src=\"http://::1:5174/@vite/client\"></script>\n    <link rel=\"stylesheet\" href=\"http://::1:5174/resources/css/app.css\">\n```\n\n```text\nexport default defineConfig({\n    server: {\n        host: '0.0.0.0'\n    },\n});\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.438Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":41,"estimatedTokens":195}}578{"id":"stack-72631935","source":"stackoverflow","questionId":72631935,"title":"Vue3 + Vite => 'default' is not exported by xxx","tags":["vue.js","vuejs3","vite"],"text":"Title: Vue3 + Vite => 'default' is not exported by xxx\nTags: vue.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nNot a question but a solution so it may help others nor futur self !\n\nI've spent 3 days trying to migrate/build a Vue3 project with Vite and having this error:\n\n```\n'default' is not exported by XXX\n```\n\nI'm importing assets dynamically as explained here:\nhttps://vitejs.dev/guide/assets.html#new-url-url-import-meta-url\n\n```\nnew URL(`/src/${path}`, import.meta.url).href;\n```\n\n`path` being the path to my asset, for example \"`assets/icons/xxx.svg`\".\n\nProblem is, if the new URL() base path targets the `src` folder, Vite will try to resolve the `.vue` and `.ts` files within it which generates the error above.\n\nTo solve it, just add the \"assets\" folder on the base path of the URL resolving, like so:\n\n```\nnew URL(`/src/assets/${path}`, import.meta.url).href;\n```\n\nYou're welcome futur me!\n\n========================================\n\nCode:\n```text\n'default' is not exported by XXX\n```\n\n```text\nnew URL(`/src/${path}`, import.meta.url).href;\n```\n\n```text\nnew URL(`/src/assets/${path}`, import.meta.url).href;\n```\n\n```text\npath\n```\n\n```text\nassets/icons/xxx.svg\n```\n\n```text\nsrc\n```\n\n```text\n.vue\n```\n\n```text\n.ts\n```\n\n```text\nsrc\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.438Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":70,"estimatedTokens":312}}579{"id":"stack-75920317","source":"stackoverflow","questionId":75920317,"title":"Configure base URL in Vite","tags":["node.js","vuejs3","vite"],"text":"Title: Configure base URL in Vite\nTags: node.js, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI have a Vue 3 application that I am building with Vite. Given the config file below, how do I tell Vite where to load my files from? On the server, the root path of the app is `/app/` but Vite is assuming it's in the root path so lazy-loaded Vue views are being loaded from `/` instead of `/app/GeneratedFileName.js`\n\nMy server for both dev and production is a .NET Core based application. I am not using the Node-based dev server at all.\n\n```\nimport { fileURLToPath, URL } from 'node:url'\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue' \n\nconst path = require('path');\n// https://vitejs.dev/config/\nexport default defineConfig({\n\n plugins: [vue()],\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url)),\n '~bootstrap': path.resolve(__dirname, 'node_modules/bootstrap'), \n }\n }, \n build: {\n outDir:'../wwwroot/app',\n manifest:true,\n \n rollupOptions: {\n external: [ \n '/img/icons/icons.svg',\n 'bootstrap' \n ], \n input: { \n cards: fileURLToPath(new URL('./src/pages/cards/cards.ts', import.meta.url)), \n output: { \n entryFileNames: `[name].js`,\n chunkFileNames: `chunks/[name].js`,\n assetFileNames: `assets/[name].[ext]`\n } \n },\n sourcemap: true,\n assetsDir: 'assets', \n emptyOutDir: true,\n }, \n})\n```\n\n========================================\n\nCode:\n```text\nimport { fileURLToPath, URL } from 'node:url'\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue' \n\nconst path = require('path');\n// https://vitejs.dev/config/\nexport default defineConfig({\n\n  plugins: [vue()],\n  resolve: {\n    alias: {\n      '@': fileURLToPath(new URL('./src', import.meta.url)),\n      '~bootstrap': path.resolve(__dirname, 'node_modules/bootstrap'),      \n    }\n  }, \n  build: {\n    outDir:'../wwwroot/app',\n    manifest:true,\n    \n    rollupOptions: {\n      external: [            \n        '/img/icons/icons.svg',\n        'bootstrap' \n      ],      \n      input: { \n      cards: fileURLToPath(new URL('./src/pages/cards/cards.ts', import.meta.url)), \n      output: { \n        entryFileNames: `[name].js`,\n        chunkFileNames: `chunks/[name].js`,\n        assetFileNames: `assets/[name].[ext]`\n      }      \n    },\n    sourcemap: true,\n    assetsDir: 'assets', \n    emptyOutDir: true,\n  },  \n})\n```\n\n```text\n/app/\n```\n\n```text\n/\n```\n\n```text\n/app/GeneratedFileName.js\n```\n\n```text\nimport { defineAsyncComponent } from 'vue'\npublic glyph =() => defineAsyncComponent(()=> import('./GlyphCard.vue'))\n```\n\n```text\npublic glyph = () => import('./GlyphCard.vue')\n```\n\n========================================\n\nComments:\n- Could you please clarify your question? Is the problem at runtime, when you run the app, and the page doesn't serve properly the scripts, or is it at build time? I also work with .Net and I am having a hard time figuring out how all these pieces fit together with the .Net Core stuff - I am also using a layout page and so on. it might help to show some directory structure.\n- One of the problems at runtime is that the references to the js files in the dist index.html file begin with `&#47;`, while when you use cshtml pages, you can reference them with `~&#47;`. Imo, you should always use your own cshtml files and ignore the generated html files. But it means you have to make the names of the generated js/css files predictable (you did this according to the vite.config.js above) and add the cache buster in the cshtml. I used in the past an app version number.\n- Could this help: vitejs.dev/config/shared-options.html#base, and specify a relative path? Or this: vitejs.dev/guide/build.html#advanced-base-options\n- If you set `base: '.&#47;'` under `build:{` the url generated is: `` as an example.\n- I've updated the question and also answered it below. It was related to async SFCs that are loaded at runtime needing to be wrapped in defineAsyncComponent.","metadata":{"transformedAt":"2026-08-18T18:33:46.438Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":121,"estimatedTokens":981}}580{"id":"stack-74846556","source":"stackoverflow","questionId":74846556,"title":"'fileURLToPath' is not exported by __vite-browser-external","tags":["vue.js","nuxt.js","vite","rollupjs","nuxt3.js"],"text":"Title: 'fileURLToPath' is not exported by __vite-browser-external\nTags: vue.js, nuxt.js, vite, rollupjs, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm getting this build error with Nuxt3.0 stable.\n\n`nuxi dev` works fine.\n\nI get the following error when I run `nuxi build`.\n\n```\nERROR 'fileURLToPath' is not exported by __vite-browser-external, imported by node_modules/local-pkg/dist/shared.mjs 13:57:26\nfile: /node_modules/local-pkg/dist/shared.mjs:41:9\n39: import path from \"path\";\n40: import fs, { promises as fsPromises } from \"fs\";\n41: import { fileURLToPath } from \"url\";\n ^\n42: \n43: // node_modules/.pnpm/yocto-queue@1.0.0/node_modules/yocto-queue/index.js\n\n ERROR 'fileURLToPath' is not exported by __vite-browser-external, imported by node_modules/local-pkg/dist/shared.mjs 13:57:26\n\n at error (node_modules/rollup/dist/es/shared/rollup.js:1858:30)\n at Module.error (node_modules/rollup/dist/es/shared/rollup.js:12429:16)\n at Module.traceVariable (node_modules/rollup/dist/es/shared/rollup.js:12788:29)\n at ModuleScope.findVariable (node_modules/rollup/dist/es/shared/rollup.js:11440:39)\n```\n\nThis is my `nuxt.config.ts`\n\n```\nexport default defineNuxtConfig({\n modules: ['@pinia/nuxt'],\n runtimeConfig: {\n },\n hooks: {\n 'components:dirs'(dirs: any) {\n dirs.push({\n path: '~/components',\n })\n },\n },\n components: {\n global: true,\n },\n nitro: {\n preset: 'aws-lambda',\n serveStatic: true,\n },\n app: {\n baseURL: '/',\n },\n build: {\n transpile: ['chart.js'],\n },\n typescript: {\n shim: false,\n strict: true,\n },\n vite: {\n resolve: {\n alias: {\n './runtimeConfig': './runtimeConfig.browser',\n },\n },\n },\n})\n```\n\nI tried these but build still doesn't work.\n\nPolyfill node os module with vite/rollup.js\n\nhttps://github.com/aws-amplify/amplify-js/issues/9639#issuecomment-1315152038\n\n========================================\n\nCode:\n```text\nERROR  'fileURLToPath' is not exported by __vite-browser-external, imported by node_modules/local-pkg/dist/shared.mjs                                                                                     13:57:26\nfile: /node_modules/local-pkg/dist/shared.mjs:41:9\n39: import path from \"path\";\n40: import fs, { promises as fsPromises } from \"fs\";\n41: import { fileURLToPath } from \"url\";\n             ^\n42: \n43: // node_modules/.pnpm/yocto-queue@1.0.0/node_modules/yocto-queue/index.js\n\n\n ERROR  'fileURLToPath' is not exported by __vite-browser-external, imported by node_modules/local-pkg/dist/shared.mjs                                                                                     13:57:26\n\n  at error (node_modules/rollup/dist/es/shared/rollup.js:1858:30)\n  at Module.error (node_modules/rollup/dist/es/shared/rollup.js:12429:16)\n  at Module.traceVariable (node_modules/rollup/dist/es/shared/rollup.js:12788:29)\n  at ModuleScope.findVariable (node_modules/rollup/dist/es/shared/rollup.js:11440:39)\n```\n\n```js\nexport default defineNuxtConfig({\n  modules: ['@pinia/nuxt'],\n  runtimeConfig: {\n  },\n  hooks: {\n    'components:dirs'(dirs: any) {\n      dirs.push({\n        path: '~/components',\n      })\n    },\n  },\n  components: {\n    global: true,\n  },\n  nitro: {\n    preset: 'aws-lambda',\n    serveStatic: true,\n  },\n  app: {\n    baseURL: '/',\n  },\n  build: {\n    transpile: ['chart.js'],\n  },\n  typescript: {\n    shim: false,\n    strict: true,\n  },\n  vite: {\n    resolve: {\n      alias: {\n        './runtimeConfig': './runtimeConfig.browser',\n      },\n    },\n  },\n})\n```\n\n```text\nnuxi dev\n```\n\n```text\nnuxi build\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\n**/*.test.*\n```\n\n```text\n.nuxtignore\n```\n\n========================================\n\nComments:\n- I got the issue when building my project with vite, i.e. running `vite build`","metadata":{"transformedAt":"2026-08-18T18:33:46.438Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":161,"estimatedTokens":918}}581{"id":"stack-77096087","source":"stackoverflow","questionId":77096087,"title":"Vite not working well with React-Router-Dom on deployed build","tags":["javascript","reactjs","react-router-dom","vite","netlify"],"text":"Title: Vite not working well with React-Router-Dom on deployed build\nTags: javascript, reactjs, react-router-dom, vite, netlify\nSource: Stack Overflow\n\nQuestion:\n```\nimport { Route, Routes, BrowserRouter as Router } from \"react-router-dom\";\nimport { SnackbarProvider } from \"notistack\";\nimport { useState, useEffect } from \"react\";\nimport { useDispatch, useSelector } from \"react-redux\";\n\nimport { auth, fTeacher, sTeacher, student, admin } from \"./features/selectors\";\nimport { routes } from \"./constants\";\n\nimport UserHeader from \"./components/UserHeader\";\nimport Sidebar from \"./components/Sidebar\";\nimport Loader from \"./components/Loader\";\n\nimport Admin from \"./pages/Admin/Admin\";\nimport Auth from \"./pages/Auth/Auth\";\nimport FormTeacher from \"./pages/FormTeacher/FormTeacher\";\nimport SubTeacher from \"./pages/SubjectTeacher/SubTeacher\";\nimport Student from \"./pages/Student/Student\";\n\nimport { Container } from \"reactstrap\";\n\nfunction App() {\n const [isLoading, setIsLoading] = useState(false);\n\n const { isAuthLoading } = useSelector(auth);\n const { isAdminLoading } = useSelector(admin);\n const { isStudentLoading } = useSelector(student);\n const { isFTeacherLoading } = useSelector(fTeacher);\n const { isSTeacherLoading } = useSelector(sTeacher);\n\n return (\n <>\n \n {isAuthLoading ||\n isLoading ||\n isAdminLoading ||\n isStudentLoading ||\n isFTeacherLoading ||\n isSTeacherLoading ? (\n \n ) : (\n \"\"\n )}\n\n \n } />\n \n \n \n \n \n \n \n \n \n }\n />\n \n \n \n \n \n \n \n \n \n }\n />\n \n \n \n \n \n \n \n \n \n }\n />\n \n \n \n \n \n \n \n \n \n }\n />\n \n \n \n \n );\n}\n\nexport default App;\n```\n\nI have this app and everything works well on `\"localhost:5173\"`\nIf I directly go to a url like `\"http://localhost:5173/admin/result\"`, it goes directly to the specific component. But when I deploy the build version of the application and go to the new url `\"https://smsystem.netlify.app/admin/result\"`, Netlify throws a 404 not found error. If I navigate within the app it works well, I just can't go to the url directly.\n\n========================================\n\nCode:\n```text\nimport { Route, Routes, BrowserRouter as Router } from \"react-router-dom\";\nimport { SnackbarProvider } from \"notistack\";\nimport { useState, useEffect } from \"react\";\nimport { useDispatch, useSelector } from \"react-redux\";\n\nimport { auth, fTeacher, sTeacher, student, admin } from \"./features/selectors\";\nimport { routes } from \"./constants\";\n\nimport UserHeader from \"./components/UserHeader\";\nimport Sidebar from \"./components/Sidebar\";\nimport Loader from \"./components/Loader\";\n\nimport Admin from \"./pages/Admin/Admin\";\nimport Auth from \"./pages/Auth/Auth\";\nimport FormTeacher from \"./pages/FormTeacher/FormTeacher\";\nimport SubTeacher from \"./pages/SubjectTeacher/SubTeacher\";\nimport Student from \"./pages/Student/Student\";\n\nimport { Container } from \"reactstrap\";\n\nfunction App() {\n  const [isLoading, setIsLoading] = useState(false);\n\n  const { isAuthLoading } = useSelector(auth);\n  const { isAdminLoading } = useSelector(admin);\n  const { isStudentLoading } = useSelector(student);\n  const { isFTeacherLoading } = useSelector(fTeacher);\n  const { isSTeacherLoading } = useSelector(sTeacher);\n\n  return (\n    <>\n      <Router>\n        {isAuthLoading ||\n        isLoading ||\n        isAdminLoading ||\n        isStudentLoading ||\n        isFTeacherLoading ||\n        isSTeacherLoading ? (\n          <Loader />\n        ) : (\n          \"\"\n        )}\n\n        <Routes>\n          <Route path=\"/\" element={<Auth />} />\n          <Route\n            path=\"/admin/*\"\n            element={\n              <div>\n                <Sidebar />\n                <div className=\"main-content\">\n                  <UserHeader />\n                  <Container>\n                    <Admin setIsLoading={setIsLoading} />\n                  </Container>\n                </div>\n              </div>\n            }\n          />\n          <Route\n            path=\"/form-teacher/*\"\n            element={\n              <div>\n                <Sidebar />\n                <div className=\"main-content\">\n                  <UserHeader />\n                  <Container>\n                    <FormTeacher setIsLoading={setIsLoading} />\n                  </Container>\n                </div>\n              </div>\n            }\n          />\n          <Route\n            path=\"/sub-teacher/*\"\n            element={\n              <div>\n                <Sidebar />\n                <div className=\"main-content\">\n                  <UserHeader />\n                  <Container>\n                    <SubTeacher setIsLoading={setIsLoading} />\n                  </Container>\n                </div>\n              </div>\n            }\n          />\n          <Route\n            path=\"/student/*\"\n            element={\n              <div>\n                <Sidebar />\n                <div className=\"main-content\">\n                  <UserHeader />\n                  <Container>\n                    <Student setIsLoading={setIsLoading} />\n                  </Container>\n                </div>\n              </div>\n            }\n          />\n        </Routes>\n      </Router>\n      <SnackbarProvider\n        anchorOrigin={{ horizontal: \"center\", vertical: \"bottom\" }}\n      />\n    </>\n  );\n}\n\nexport default App;\n```\n\n```text\n\"localhost:5173\"\n```\n\n```text\n\"http://localhost:5173/admin/result\"\n```\n\n```text\n\"https://smsystem.netlify.app/admin/result\"\n```\n\n```none\n/*  /index.html  200\n```\n\n```text\npublic/_redirects\n```\n\n```text\n\"/public\"\n```\n\n========================================\n\nComments:\n- this is not a problem with vite nor your routing system. if you are using nginx make sure to add a fallback to `index.html` for not found routes. I don't really know the flow of netlify deployment but there must be an option to do this.\n- But the route in question is actually a working route, but it throws a 404","metadata":{"transformedAt":"2026-08-18T18:33:46.438Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":254,"estimatedTokens":1448}}582{"id":"stack-73379626","source":"stackoverflow","questionId":73379626,"title":"Can't run tests on vitest with json-big","tags":["typescript","vue.js","npm","vite","vitest"],"text":"Title: Can't run tests on vitest with json-big\nTags: typescript, vue.js, npm, vite, vitest\nSource: Stack Overflow\n\nQuestion:\nFor some reason my typescript/vue with vite setup runs fine but trying to run tests just won't work. Here's the (i think) relevant files:\n\npackage.json\n\n```\n{\n \"name\": \"vite-vue-typescript-starter\",\n \"version\": \"0.1.4\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vue-tsc --noEmit && vite build --base /smgreenhousemanager\",\n \"test\": \"vitest run --coverage\",\n \"format\": \"prettier --write .\",\n \"typecheck\": \"vue-tsc --noEmit\"\n },\n \"dependencies\": {\n \"@pixi/math-extras\": \"^6.4.2\",\n \"axios\": \"0.25.0\",\n \"json-big\": \"^1.0.2\",\n \"lodash\": \"^4.17.21\",\n \"mitt\": \"^3.0.0\",\n \"pinia\": \"^2.0.13\",\n \"pixi-viewport\": \"^4.34.4\",\n \"pixi.js\": \"^6.4.2\",\n \"pixi.js-keyboard\": \"^1.1.6\",\n \"pixi.js-mouse\": \"^1.1.6\",\n \"ts-toolbelt\": \"^9.6.0\",\n \"uuid\": \"^8.3.2\",\n \"vue\": \"^3.2.26\"\n },\n \"devDependencies\": {\n \"@types/lodash\": \"^4.14.182\",\n \"@types/node\": \"^18.6.2\",\n \"@types/uuid\": \"^8.3.4\",\n \"@vitejs/plugin-vue\": \"^2.2.0\",\n \"@vitest/coverage-c8\": \"^0.22.0\",\n \"@vue/compiler-sfc\": \"^3.2.23\",\n \"happy-dom\": \"^6.0.4\",\n \"jsdom\": \"^20.0.0\",\n \"typescript\": \"^4.5.4\",\n \"vite\": \"^2.8.0\",\n \"vitest\": \"^0.22.0\",\n \"vue-tsc\": \"^0.29.8\"\n }\n}\n```\n\nvite.config.ts\n\n```\n// https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html#-reference-types-\n/// \n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport process from \"process\"\n\nconst httpPort: string = process.env.HTTP_PORT || '8069' // This parallels our backend declaration in service.py.\nconst backendUrl: string = process.env.BACKEND_URL || `localhost:${httpPort}`\n\nexport default defineConfig({\n plugins: [vue()],\n define: {\n 'BACKEND_URL': `\"${backendUrl}\"`\n },\n build: {\n target: 'esnext'\n },\n test: {\n environment : \"happy-dom\"\n }\n})\n```\n\nutils.test.ts\n\n```\nimport { expect, test } from 'vitest'\nimport {Rectangle} from \"pixi.js\";\nimport {normaliseRectangleShape} from \"../lib/utils\";\n\ntest('normalised rectangle nominal', () => {\n const rect = new Rectangle(0, 0, 50, 50)\n const normalised = normaliseRectangleShape(rect)\n\n expect(normalised.x).toBe(0)\n // expect(normalised).toHaveProperty('y', 0)\n // expect(normalised).toHaveProperty('width', 50)\n // expect(normalised).toHaveProperty('height', 50)\n})\n```\n\nImporting `normaliseRectangleShape` eventually end up importing json-big because of other utils function in its file. I have this output with `vitest run`:\n\n```\n/usr/local/bin/npm test\n\n> vite-vue-typescript-starter@0.1.4 test\n> vitest run\n\n RUN v0.22.0 /home/chuck/PyCharm/smgreenhousemanager\n\n ❯ frontend/src/tests/utils.test.ts (0)\n\n⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Failed Suites 1 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯\n\n FAIL frontend/src/tests/utils.test.ts [ frontend/src/tests/utils.test.ts ]\nError: Failed to resolve entry for package \"json-big\". The package may have incorrect main/module/exports specified in its package.json: Failed to resolve entry for package \"json-big\". The package may have incorrect main/module/exports specified in its package.json.\n ❯ packageEntryFailure node_modules/vite/dist/node/chunks/dep-689425f3.js:40970:11\n ❯ resolvePackageEntry node_modules/vite/dist/node/chunks/dep-689425f3.js:40966:9\n ❯ tryNodeResolve node_modules/vite/dist/node/chunks/dep-689425f3.js:40773:20\n ❯ Context.resolveId node_modules/vite/dist/node/chunks/dep-689425f3.js:40581:28\n ❯ Object.resolveId node_modules/vite/dist/node/chunks/dep-689425f3.js:39254:55\n ❯ TransformContext.resolve node_modules/vite/dist/node/chunks/dep-689425f3.js:39028:23\n ❯ normalizeUrl node_modules/vite/dist/node/chunks/dep-689425f3.js:58354:34\n ❯ TransformContext.transform node_modules/vite/dist/node/chunks/dep-689425f3.js:58509:57\n ❯ Object.transform node_modules/vite/dist/node/chunks/dep-689425f3.js:39317:30\n\n⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯\n\nTest Files 1 failed (1)\n Tests no tests\n Start at 15:52:06\n Duration 1.11s (setup 0ms, collect 0ms, tests 0ms)\n\nProcess finished with exit code 1\n```\n\n- I tried fiddleing with the vite config with the deps options from vitest\n\n- I tried deleting node modules and reinstalling\n\n- I'm running node v16.16.0 and npm v8.17.0 on Linux Mint (Vanessa)\n\n========================================\n\nCode:\n```json\n{\n  \"name\": \"vite-vue-typescript-starter\",\n  \"version\": \"0.1.4\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vue-tsc --noEmit && vite build --base /smgreenhousemanager\",\n    \"test\": \"vitest run --coverage\",\n    \"format\": \"prettier --write .\",\n    \"typecheck\": \"vue-tsc --noEmit\"\n  },\n  \"dependencies\": {\n    \"@pixi/math-extras\": \"^6.4.2\",\n    \"axios\": \"0.25.0\",\n    \"json-big\": \"^1.0.2\",\n    \"lodash\": \"^4.17.21\",\n    \"mitt\": \"^3.0.0\",\n    \"pinia\": \"^2.0.13\",\n    \"pixi-viewport\": \"^4.34.4\",\n    \"pixi.js\": \"^6.4.2\",\n    \"pixi.js-keyboard\": \"^1.1.6\",\n    \"pixi.js-mouse\": \"^1.1.6\",\n    \"ts-toolbelt\": \"^9.6.0\",\n    \"uuid\": \"^8.3.2\",\n    \"vue\": \"^3.2.26\"\n  },\n  \"devDependencies\": {\n    \"@types/lodash\": \"^4.14.182\",\n    \"@types/node\": \"^18.6.2\",\n    \"@types/uuid\": \"^8.3.4\",\n    \"@vitejs/plugin-vue\": \"^2.2.0\",\n    \"@vitest/coverage-c8\": \"^0.22.0\",\n    \"@vue/compiler-sfc\": \"^3.2.23\",\n    \"happy-dom\": \"^6.0.4\",\n    \"jsdom\": \"^20.0.0\",\n    \"typescript\": \"^4.5.4\",\n    \"vite\": \"^2.8.0\",\n    \"vitest\": \"^0.22.0\",\n    \"vue-tsc\": \"^0.29.8\"\n  }\n}\n```\n\n```js\n// https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html#-reference-types-\n/// <reference types=\"vitest\" />\n\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport process from \"process\"\n\nconst httpPort: string = process.env.HTTP_PORT || '8069' // This parallels our backend declaration in service.py.\nconst backendUrl: string = process.env.BACKEND_URL || `localhost:${httpPort}`\n\nexport default defineConfig({\n    plugins: [vue()],\n    define: {\n        'BACKEND_URL': `\"${backendUrl}\"`\n    },\n    build: {\n        target: 'esnext'\n    },\n    test: {\n        environment : \"happy-dom\"\n    }\n})\n```\n\n```js\nimport { expect, test } from 'vitest'\nimport {Rectangle} from \"pixi.js\";\nimport {normaliseRectangleShape} from \"../lib/utils\";\n\ntest('normalised rectangle nominal', () => {\n    const rect = new Rectangle(0, 0, 50, 50)\n    const normalised = normaliseRectangleShape(rect)\n\n    expect(normalised.x).toBe(0)\n    // expect(normalised).toHaveProperty('y', 0)\n    // expect(normalised).toHaveProperty('width', 50)\n    // expect(normalised).toHaveProperty('height', 50)\n})\n```\n\n```text\n/usr/local/bin/npm test\n\n> vite-vue-typescript-starter@0.1.4 test\n> vitest run\n\n\n RUN  v0.22.0 /home/chuck/PyCharm/smgreenhousemanager\n\n ❯ frontend/src/tests/utils.test.ts (0)\n\n⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Failed Suites 1 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯\n\n FAIL  frontend/src/tests/utils.test.ts [ frontend/src/tests/utils.test.ts ]\nError: Failed to resolve entry for package \"json-big\". The package may have incorrect main/module/exports specified in its package.json: Failed to resolve entry for package \"json-big\". The package may have incorrect main/module/exports specified in its package.json.\n ❯ packageEntryFailure node_modules/vite/dist/node/chunks/dep-689425f3.js:40970:11\n ❯ resolvePackageEntry node_modules/vite/dist/node/chunks/dep-689425f3.js:40966:9\n ❯ tryNodeResolve node_modules/vite/dist/node/chunks/dep-689425f3.js:40773:20\n ❯ Context.resolveId node_modules/vite/dist/node/chunks/dep-689425f3.js:40581:28\n ❯ Object.resolveId node_modules/vite/dist/node/chunks/dep-689425f3.js:39254:55\n ❯ TransformContext.resolve node_modules/vite/dist/node/chunks/dep-689425f3.js:39028:23\n ❯ normalizeUrl node_modules/vite/dist/node/chunks/dep-689425f3.js:58354:34\n ❯ TransformContext.transform node_modules/vite/dist/node/chunks/dep-689425f3.js:58509:57\n ❯ Object.transform node_modules/vite/dist/node/chunks/dep-689425f3.js:39317:30\n\n⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯\n\nTest Files  1 failed (1)\n     Tests  no tests\n  Start at  15:52:06\n  Duration  1.11s (setup 0ms, collect 0ms, tests 0ms)\n\n\nProcess finished with exit code 1\n```\n\n```text\nnormaliseRectangleShape\n```\n\n```text\nvitest run\n```\n\n```js\nimport {beforeAll} from 'vitest'\n\nbeforeAll(() => {\n  require('json-bigint-patch')  // Ensures all tests have the patched JSON\n})\n```\n\n```text\njson-bigint-patch\n```\n\n========================================\n\nComments:\n- Can you post the relevant code that imports `json-big` from `..&#47;lib&#47;utils`? The issue should be with import with `json-big`.","metadata":{"transformedAt":"2026-08-18T18:33:46.438Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":286,"estimatedTokens":2269}}583{"id":"stack-77090461","source":"stackoverflow","questionId":77090461,"title":"\"Vite manifest not found\" due to traffic, during deployment","tags":["laravel","vite","manifest.json"],"text":"Title: \"Vite manifest not found\" due to traffic, during deployment\nTags: laravel, vite, manifest.json\nSource: Stack Overflow\n\nQuestion:\nFirst of all, I've read all the other questions suggested by SO, but none of them solve the situation I'm in, or if they come close, they don't provide an adequate answer.\n\nFor context, I'm working on a Laravel 8 project initially using Mix, but recently migrated to Vite.\n\nWe do not commit the `/public/build` folder to Github.\n\nInstead, we placed the command `npm run prod` (which map to `vite build` in the `package.json`) in the Forge deployment script, and everything goes well.\n\nThe problem is that when there is traffic on the site, if a page is called during the fraction of seconds that the `manifest.json` file is regenerated, this error pops-up in the logs and in Sentry :\n\n```\nVite manifest not found at: /home/forge//public/build/manifest.json\n```\n\nFor the user, it results in an `Error 500`, which is very annoying.\n\nHow can we fix this ?\n\n========================================\n\nTop Answer:\nI finally manage to get rid of this of this error by using the `reportable` method in the `register` function of `/app/Exceptions/Handler.php`.\n\nAs documented here (Reporting Exceptions) simply add :\n\n```\n/**\n * Register the exception handling callbacks for the application.\n *\n * @return void\n */\npublic function register()\n{\n // ...\n\n // Exclude this annoying 'Vite manifest not found' exception from logs.\n $this->reportable(function (\\Spatie\\LaravelIgnition\\Exceptions\\ViewException $e) {\n if (Str::of($e->getMessage())->contains('Vite manifest not found')) {\n return false; // or anything else for that matter\n }\n });\n\n // ...\n}\n```\n\nAnd that's it, the error stop being logged.\n\nBut at this point I haven't made tests to check if still shows error 500 to the user.\n\nAlso, another way (perhaps more reliable or at least elegant) could be to define `report` and `render` methods directly on your application's exceptions.\n\nIt's documented here (Renderable Exceptions)\n\n========================================\n\nCode:\n```bash\nVite manifest not found at: /home/forge/<myproject>/public/build/manifest.json\n```\n\n```text\n/public/build\n```\n\n```text\nnpm run prod\n```\n\n```text\nvite build\n```\n\n```text\npackage.json\n```\n\n```text\nmanifest.json\n```\n\n```text\nError 500\n```\n\n```text\n\"build\": \"vite build && rm -rf ./public/build/* && mv ./public/build_prod/* ./public/build/\"\n```\n\n```text\nexport default defineConfig({\n  build: {\n    outDir: './public/build_prod',\n  },\n});\n```\n\n```php\n/**\n * Register the exception handling callbacks for the application.\n *\n * @return void\n */\npublic function register()\n{\n    // ...\n\n    // Exclude this annoying 'Vite manifest not found' exception from logs.\n    $this->reportable(function (\\Spatie\\LaravelIgnition\\Exceptions\\ViewException $e) {\n        if (Str::of($e->getMessage())->contains('Vite manifest not found')) {\n            return false; // or anything else for that matter\n        }\n    });\n\n    // ...\n}\n```\n\n```text\nreportable\n```\n\n```text\nregister\n```\n\n```text\n/app/Exceptions/Handler.php\n```\n\n```text\nreport\n```\n\n```text\nrender\n```\n\n========================================\n\nComments:\n- the `vite.config.js` file\n- My bad. did not see the `traffic` part. Can you put your page in maintenance mode then generate the manifest.json?\n- So that users wont access these files when building\n- Thanks for your response. I already suggested it to my superiors, but the response was that they didn't want to put the site in maintenance mode during deployments. I agree that this would be the best solution, and I'm going to ask for more explanation on \"why\" they don't want it. In the meantime, if anyone has another suggestion, I'll take it.\n- I'am also looking at the best solution for this. Was considering maintenance mode, but that would make the app inaccessible during the deployment (1 min) which is not really wanted.\n- @TwystO did you solve this in any other way than setting to maintenance mode? Maybe ViteJS could keep the files until the new files are generated?\n- @5less I added an answer, see below.\n- Yes this will still show the 500 error to the user if they are browsing as the manifest.json file is not accessible. See my answer for another solution.\n- This doesn't prevent the error from happening, users will still see it. Now you just won't know about it.","metadata":{"transformedAt":"2026-08-18T18:33:46.438Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":155,"estimatedTokens":1089}}584{"id":"stack-75358894","source":"stackoverflow","questionId":75358894,"title":"Error 404 on Github Pages using React Router v6.6.1 and Vite","tags":["reactjs","react-router","web-deployment","github-pages","vite"],"text":"Title: Error 404 on Github Pages using React Router v6.6.1 and Vite\nTags: reactjs, react-router, web-deployment, github-pages, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to publish my first React app using Vite, React-Router-Dom-v6.6.1 and Github Pages but for some reason the `index.html` file is not detected and the \"404 error\" is being shown, however this error is shown on a page added by me to deal with possible errors and there is an option to return to the homepage ; however this homepage is generated from the reading of the `index.html` file and respective javascript. But at this moment the browser is already able to interpret the `index.html` file and everything behaves similarly to the development environment, without errors.\nThat is, for some reason the browser does not identify the `index.html` file on its first load (I think), even though the path pointed in `base: \"/presentation/\"` is pointing to the right place.\n\nBelow are the files I find most relevant, the link to my `Github Pages` (where this issue is happening) as well as a link to a screen recording I made of this situation so you can better understand what I'm trying to explain.\n\n**Github Page in question:**\n\n**Problem screen recording video:**\n\n### VITE files\n\n**main.jsx**\n\n```\nimport React from \"react\";\nimport ReactDOM from \"react-dom/client\";\nimport {\n createBrowserRouter,\n RouterProvider,\n createRoutesFromElements,\n Route,\n} from \"react-router-dom\";\nimport \"./index.css\";\n\n// Redux Toolkit\nimport { Provider, useSelector } from \"react-redux\";\nimport store from \"./reduxTlk/store\";\n\n/* existing imports */\nimport Root from \"./routes/root\";\nimport ErrorPage from \"./error-page\";\nimport Home from \"./routes/home\";\nimport WeatherStatus from \"./routes/weatherStatus\";\nimport { weatherLoader } from \"./components/projects/ipma/TempTable\";\n\nconst router = createBrowserRouter(\n createRoutesFromElements(\n <>\n } errorElement={}>\n } />\n }\n loader={weatherLoader}\n />\n \n \n )\n);\n\nReactDOM.createRoot(document.getElementById(\"root\")).render(\n \n \n \n \n \n);\n```\n\n**package.json**\n\n```\n{\n \"name\": \"vite-project\",\n \"private\": true,\n \"version\": \"0.0.0\",\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\"\n },\n \"dependencies\": {\n \"@emotion/react\": \"^11.10.5\",\n \"@emotion/styled\": \"^11.10.5\",\n \"@mui/icons-material\": \"^5.11.0\",\n \"@mui/material\": \"^5.11.7\",\n \"@reduxjs/toolkit\": \"^1.9.1\",\n \"dompurify\": \"^2.4.1\",\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\",\n \"react-redux\": \"^8.0.5\",\n \"react-router-dom\": \"^6.6.1\"\n },\n \"homepage\": \"https://cristianolm.github.io/presentation/\",\n \"devDependencies\": {\n \"@types/react\": \"^18.0.24\",\n \"@types/react-dom\": \"^18.0.8\",\n \"@vitejs/plugin-react\": \"^2.2.0\",\n \"vite\": \"^3.2.3\"\n }\n}\n```\n\n**vite.config.js**\n\n```\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n base: \"/presentation/\",\n plugins: [react()],\n});\n```\n\n### dist/`index.html`\n\n```\n\n \n \n \n \n Cristiano Martins\n \n \n \n \n \n \n \n\n```\n\nFirstly, I tried to build for production with the `base line: \"/presentation/,` in *vite.config.js*, then I tried to do this same process without this line and finally I added that line again, but I added it to the *package. json* the line `homepage\": \"https://cristianolm.github.io/presentation/,`.\n\nAnd of course I tried to search for another solution on google, but without success.\n\n========================================\n\nTop Answer:\nthis is not really vite related i think you understand:\n\n```\nconst router = createBrowserRouter(\n createRoutesFromElements(\n <>\n- } errorElement={}>\n+ } errorElement={}>\n } />\n }\n loader={weatherLoader}\n />\n \n \n )\n);\n```\n\nit looks like this:\nhttps://cristianolm.github.io/presentation/\nthe actual route will be `/presentation` not `/`\n\n========================================\n\nCode:\n```text\nimport React from \"react\";\nimport ReactDOM from \"react-dom/client\";\nimport {\n  createBrowserRouter,\n  RouterProvider,\n  createRoutesFromElements,\n  Route,\n} from \"react-router-dom\";\nimport \"./index.css\";\n\n// Redux Toolkit\nimport { Provider, useSelector } from \"react-redux\";\nimport store from \"./reduxTlk/store\";\n\n/* existing imports */\nimport Root from \"./routes/root\";\nimport ErrorPage from \"./error-page\";\nimport Home from \"./routes/home\";\nimport WeatherStatus from \"./routes/weatherStatus\";\nimport { weatherLoader } from \"./components/projects/ipma/TempTable\";\n\nconst router = createBrowserRouter(\n  createRoutesFromElements(\n    <>\n      <Route path=\"/\" element={<Root />} errorElement={<ErrorPage />}>\n        <Route index element={<Home />} />\n        <Route\n          path=\"WeatherStatus\"\n          element={<WeatherStatus />}\n          loader={weatherLoader}\n        />\n      </Route>\n    </>\n  )\n);\n\nReactDOM.createRoot(document.getElementById(\"root\")).render(\n  <React.StrictMode>\n    <Provider store={store}>\n      <RouterProvider router={router} />\n    </Provider>\n  </React.StrictMode>\n);\n```\n\n```text\n{\n  \"name\": \"vite-project\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"preview\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"@emotion/react\": \"^11.10.5\",\n    \"@emotion/styled\": \"^11.10.5\",\n    \"@mui/icons-material\": \"^5.11.0\",\n    \"@mui/material\": \"^5.11.7\",\n    \"@reduxjs/toolkit\": \"^1.9.1\",\n    \"dompurify\": \"^2.4.1\",\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\",\n    \"react-redux\": \"^8.0.5\",\n    \"react-router-dom\": \"^6.6.1\"\n  },\n  \"homepage\": \"https://cristianolm.github.io/presentation/\",\n  \"devDependencies\": {\n    \"@types/react\": \"^18.0.24\",\n    \"@types/react-dom\": \"^18.0.8\",\n    \"@vitejs/plugin-react\": \"^2.2.0\",\n    \"vite\": \"^3.2.3\"\n  }\n}\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  base: \"/presentation/\",\n  plugins: [react()],\n});\n```\n\n```text\n<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <link rel=\"icon\" type=\"image/svg+xml\" href=\"/presentation/vite.svg\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>Cristiano Martins</title>\n    <script type=\"module\" crossorigin src=\"/presentation/assets/index.6cda9410.js\"></script>\n    <link rel=\"stylesheet\" href=\"/presentation/assets/index.85f54fc4.css\">\n  </head>\n  <body>\n    <div id=\"root\"></div>\n    \n  </body>\n</html>\n```\n\n```text\nindex.html\n```\n\n```text\nindex.html\n```\n\n```text\nindex.html\n```\n\n```text\nindex.html\n```\n\n```text\nbase: \"/presentation/\"\n```\n\n```text\nindex.html\n```\n\n```text\nbase line: \"/presentation/,\n```\n\n```text\nhomepage\": \"https://cristianolm.github.io/presentation/,\n```\n\n```text\ncreateBrowserRouter(routes, {\n  basename: \"/app\",\n});\n```\n\n```text\nconst router = createBrowserRouter(\n  createRoutesFromElements(\n    <Route\n      path=\"/\" // <-- \"/presentation\"\n      element={<Root />}\n      errorElement={<ErrorPage />}\n    >\n      <Route\n        index // <-- \"/presentation\"\n        element={<Home />}\n      />\n      <Route\n        path=\"WeatherStatus\" // <-- \"/presentation/WeatherStatus\"\n        element={<WeatherStatus />}\n        loader={weatherLoader}\n      />\n    </Route>\n  ),\n  { basename: \"/presentation\" }\n);\n```\n\n```text\nbasename\n```\n\n```text\nbasename\n```\n\n```text\n\"https://cristianolm.github.io/presentation\"\n```\n\n```text\nconst router = createBrowserRouter(\n  createRoutesFromElements(\n    <>\n-     <Route path=\"/\" element={<Root />} errorElement={<ErrorPage />}>\n+     <Route path=\"/presentation\" element={<Root />} errorElement={<ErrorPage />}>\n        <Route index element={<Home />} />\n        <Route\n          path=\"WeatherStatus\"\n          element={<WeatherStatus />}\n          loader={weatherLoader}\n        />\n      </Route>\n    </>\n  )\n);\n```\n\n```text\n/presentation\n```\n\n```text\n/\n```\n\n========================================\n\nComments:\n- Does this help answer your question? stackoverflow.com/questions/71984401/&hellip;\n- I had already seen this post, I just didn't use \"HashRouter\", because in the latest version React-Router advises using \"createBrowserRouter\".\n- The RRD docs have just about always said that, but Github hosting requires using a `HashRouter` from my understanding. It's more of a \"Use the `BrowserRouter` unless you have an edge-case use case and you know what you are doing.\" sort of thing.\n- Hmmmm... Well that could be it. I think I'll try other hosting services to see if I come to a better conclusion. But that could very well be it. But when I've tested more options I'll come here to say something. Now I'm going to rest a little, because I'm already many hours back from this. But I promise I'll come here to update.\n- Hello. I've been back from this and other errors and I realized that the answer that the \"Tachibana Shin\" of re-invoicing the routes (in my case) resulting from the addition of `path=\"&#47;presentation\"` in \"Route\" solved the problem. As for the other hosting services, I tried the Vercel website, but there was an error related to the routes, but I confess that I didn't invest a lot of time trying to solve this problem, as I was trying to solve the Github Pages problem. But still thanks for the help.\n- I think Tachibana-shin's answer only masks the issue. I suspect what you really need is to simply specify the `basename` prop on the router for the directory the app is hosted in, i.e. `createBrowserRouter(routes, { basename: \"&#47;presentation\" })`. Their answer *effectively* did this, but not quite in the idiomatic RRD way.\n- After all this time, I noticed that you are right in your answer. I redid my entire portfolio for TypeScript and tried to solve this Github Pages hosting issue again, and I noticed that you were right, however, it only worked for me when I indicated the name of the repository (where the github page would take place) in both places: `vite .config.ts` with ` base: \"/presentation\",` and in ``createBrowserRouter` with `{ basename: \"&#47;presentation\" }`.\n- I don't think it's Vite-related either, more like React Router. But I don't think that can be it, because \"/presentation\" is the name of the repo, hence having written \"base: \"/presentation/\" in `vite.config.js`. But if you click on the video I put associated with \"Problem screen recording video:\" you'll be able to see more clearly that \"/presentation\" is the name given to the repo on github, and within that repo, the branch taken as a reference for GitHub Pages is called `react`, which within itself has the `index.html` file to be loaded (which is the one at location \"/\").\n- you are not understanding the problem react-router will get path route from location.href you understand but when you go to `https:&#47;&#47;&#47;presentation` the route path is `&#47;presentation` however your app set here (`index.html`) only serves the route path as `&#47;` and the fact you want it to run that way means that the implementation needs to set `&#47;presentation` as `path root`. try it here is the solution for you\n- Hello, I've been trying several approaches and you're actually right. I I initially thought that it was enough to indicate \"base:/presentation/\" and the SPA should work normally, but I really had to make the change you suggested. Thank you very much. By the way, however, I managed to solve other problems such as the 404 error when refreshing, but this problem is completely resolved on the computer, but on the mobile phone if I leave the SPA and go back to the SPA again, the 404 error is displayed. Do you know anything about this?\n- that's because the paths don't really exist you can create a `404.html` file in `public` and use any method to redirect back to `index.html` for example `'>` or use javascript\n- I used Javascript, as I resorted to a repository for SPA on github, called \"spa-github-pages\" from a user called \"rafgraph\", which uses this approach. But I'm going to take a closer look at this repository and your suggestion, because I don't think I'm missing much, as this error only happens on my cell phone. But anyway, if I can't solve the problem within a few days I'll make a new post here on stackoverflow. Thanks.\n- I managed to solve the problem, but the name of your repository must be indicated in both places (and not just in one). Those locations are the `vite .config.ts` file (as I indicated in my question) and the Router `createBrowserRouter` (as indicated in this answer). Thanks.\n- @Cristianolm Yes, sorry, I did intend for that to mean \"... you may only *additionally* need to ...\". I'll edit to make this more clear. Thanks.","metadata":{"transformedAt":"2026-08-18T18:33:46.438Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":385,"estimatedTokens":3150}}585{"id":"stack-77115733","source":"stackoverflow","questionId":77115733,"title":"Vite custom plugin transformIndexHtml hook not working during build","tags":["javascript","vite","bundler"],"text":"Title: Vite custom plugin transformIndexHtml hook not working during build\nTags: javascript, vite, bundler\nSource: Stack Overflow\n\nQuestion:\nI'm writing custom plugin in vite.js to transform my `index.html` file:\n\n```\nreturn {\n name: 'html-build-plugin',\n apply: 'build',\n transformIndexHtml: {\n order: 'post',\n handler(htmlData, ctx) {\n const transformedHtml = htmlData.replace('', 'aaa:');\n\n return transformedHtml;\n }\n }\n };\n}\n```\n\nI'm using this plugin in my `vite.config.ts` file:\n\n```\nexport default defineConfig(({ mode }) => {\n return {\n mode,\n build: {\n outDir: 'dist',\n sourcemap: mode === 'development' ? 'inline' : true,\n target: 'modules',\n cssCodeSplit: false,\n rollupOptions: {\n input: {\n app: path.resolve(__dirname, 'src', 'scripts', 'entry.ts'),\n },\n output: {\n format: 'systemjs',\n dir: path.resolve(__dirname, 'dist'),\n generatedCode: 'es2015',\n manualChunks(id: string): string {\n if (id.includes('node_modules')) {\n return 'vendor';\n }\n },\n chunkFileNames: '[name].[hash].js',\n entryFileNames: '[name].[hash].js',\n assetFileNames: 'assets/[name].[hash][extname]',\n plugins: [\n manifestJSON.default({\n fileName: 'manifest.json',\n }),\n ],\n },\n logLevel: 'debug',\n },\n },\n plugins: [HtmlBuildPlugin()],\n };\n});\n```\n\nPlugin is working and hook is called only in dev mode (when I call `npx vite dev`). When I'm running build mode `npx vite build` (Vite does in fact copy my `index.html` from my public directory to dist directory) it does not. Docs states that it should work in both cases: `The context exposes the ViteDevServer instance during dev, and exposes the Rollup output bundle during build`. What am I doing wrong? I tried placing this plugin in rollup options, but it does not work either.\n\n========================================\n\nCode:\n```text\nreturn {\n    name: 'html-build-plugin',\n    apply: 'build',\n    transformIndexHtml: {\n      order: 'post',\n      handler(htmlData, ctx) {\n        const transformedHtml = htmlData.replace('<title>', '<title>aaa:');\n\n        return transformedHtml;\n      }\n    }\n  };\n}\n```\n\n```text\nexport default defineConfig(({ mode }) => {\n  return {\n    mode,\n    build: {\n      outDir: 'dist',\n      sourcemap: mode === 'development' ? 'inline' : true,\n      target: 'modules',\n      cssCodeSplit: false,\n      rollupOptions: {\n        input: {\n          app: path.resolve(__dirname, 'src', 'scripts', 'entry.ts'),\n        },\n        output: {\n          format: 'systemjs',\n          dir: path.resolve(__dirname, 'dist'),\n          generatedCode: 'es2015',\n          manualChunks(id: string): string {\n            if (id.includes('node_modules')) {\n              return 'vendor';\n            }\n          },\n          chunkFileNames: '[name].[hash].js',\n          entryFileNames: '[name].[hash].js',\n          assetFileNames: 'assets/[name].[hash][extname]',\n          plugins: [\n            manifestJSON.default({\n              fileName: 'manifest.json',\n            }),\n          ],\n        },\n        logLevel: 'debug',\n      },\n    },\n    plugins: [HtmlBuildPlugin()],\n  };\n});\n```\n\n```text\nindex.html\n```\n\n```text\nvite.config.ts\n```\n\n```text\nnpx vite dev\n```\n\n```text\nnpx vite build\n```\n\n```text\nindex.html\n```\n\n```text\nThe context exposes the ViteDevServer instance during dev, and exposes the Rollup output bundle during build\n```\n\n```text\nrollupOptions: {\n  input: {\n    app: path.resolve(__dirname, 'src', 'scripts', 'entry.ts'),\n    template: path.resolve(__dirname, 'index.html'),\n  },\n```\n\n```text\nrollupOptions\n```\n\n========================================\n\nComments:\n- @Ssh-uunen kind of - see my answer","metadata":{"transformedAt":"2026-08-18T18:33:46.438Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":164,"estimatedTokens":895}}586{"id":"stack-75261643","source":"stackoverflow","questionId":75261643,"title":"How to execute react/vite/nodejs/express app simultaneously?","tags":["reactjs","express","proxy","vite"],"text":"Title: How to execute react/vite/nodejs/express app simultaneously?\nTags: reactjs, express, proxy, vite\nSource: Stack Overflow\n\nQuestion:\nI am new to React and JavaScript. I am having troubles linking my client and backend together. I try to start frontend and backend simultaneously to be able to send requests to backend and fetch data into my frontend.\nI followed this tutorial: https://levelup.gitconnected.com/how-to-simultaneously-run-the-client-and-server-of-your-full-stack-app-in-one-folder-ef5a988d56d7\n\nAfter i try to run npm run dev i am getting following error:\n\n```\nPS C:\\Users\\sebas\\Downloads\\LiveFanaticSS> npm run dev\nnpm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.\n> livefanaticss@1.0.0 dev\n> concurrently \"npm run server\" \"npm run client\"\n[0] npmnpm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.\n[0] WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead. \n[1] \n[1] > livefanaticss@1.0.0 client\n[1] > npm start --prefix client \n[1] \n[0] \n[0] > livefanaticss@1.0.0 server\n[0] > npm start --prefix server \n[0] \n[0] npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.\n[1] npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.\n[0] \n[0] > server@1.0.0 start\n[0] > nodemon index.js \n[0] \n[1] npm ERR! Missing script: \"start\"\nnpm ERR! \n[1] npm ERR! Did you mean one of these?\n[1] npm ERR! npm star # Mark your favorite packages \nnpm ERR! npm stars # View packages marked as favorites\n[1] npm ERR! \n[1] npm ERR! To see a list of scripts, run:\nnpm ERR! npm run\n[1]\n[1] npm ERR! A complete log of this run can be found in:\n[1] npm ERR! C:\\Users\\sebas\\AppData\\Local\\npm-cache\\_logs\\2023-01-27T18_44_00_542Z-debug-0.log\n[1] npm run client exited with code 1\n[0] [nodemon] 2.0.20\n[0] [nodemon] to restart at any time, enter `rs`\n[0] [nodemon] watching path(s): *.*\n[0] [nodemon] watching extensions: js,mjs,json\n[0] [nodemon] starting `node index.js`\n[0] http://localhost:3333\n[0] server running on port 3333\n```\n\nHow can i fix it?\n\n========================================\n\nTop Answer:\nIn addition to the answer @Ibs91 just gave:\n\nYour solution worked. Thank you. I wanted to add that it didn't work right away, because I was in VSCode, and somehow it didn't cache my changes and still gave me the error. So, I closed my VSCode after I made those changes, and reopened it, and then it worked.\n\n========================================\n\nCode:\n```text\nPS C:\\Users\\sebas\\Downloads\\LiveFanaticSS> npm run dev\nnpm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.\n> livefanaticss@1.0.0 dev\n> concurrently \"npm run server\" \"npm run client\"\n[0] npmnpm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.\n[0]  WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.      \n[1] \n[1] > livefanaticss@1.0.0 client\n[1] > npm start --prefix client \n[1] \n[0] \n[0] > livefanaticss@1.0.0 server\n[0] > npm start --prefix server \n[0] \n[0] npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.\n[1] npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.\n[0] \n[0] > server@1.0.0 start\n[0] > nodemon index.js  \n[0] \n[1] npm ERR! Missing script: \"start\"\nnpm ERR! \n[1] npm ERR! Did you mean one of these?\n[1] npm ERR!     npm star # Mark your favorite packages   \nnpm ERR!     npm stars # View packages marked as favorites\n[1] npm ERR! \n[1] npm ERR! To see a list of scripts, run:\nnpm ERR!   npm run\n[1]\n[1] npm ERR! A complete log of this run can be found in:\n[1] npm ERR!     C:\\Users\\sebas\\AppData\\Local\\npm-cache\\_logs\\2023-01-27T18_44_00_542Z-debug-0.log\n[1] npm run client exited with code 1\n[0] [nodemon] 2.0.20\n[0] [nodemon] to restart at any time, enter `rs`\n[0] [nodemon] watching path(s): *.*\n[0] [nodemon] watching extensions: js,mjs,json\n[0] [nodemon] starting `node index.js`\n[0] http://localhost:3333\n[0] server running on port 3333\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.438Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":105,"estimatedTokens":1033}}587{"id":"stack-75991211","source":"stackoverflow","questionId":75991211,"title":"How can I conditionally apply a plugin in Vite depending on build type?","tags":["ionic-framework","vite","ionic-react"],"text":"Title: How can I conditionally apply a plugin in Vite depending on build type?\nTags: ionic-framework, vite, ionic-react\nSource: Stack Overflow\n\nQuestion:\nI am using Vite to build an Ionic React app, which has three versions:\n\n- iOS\n\n- Android\n\n- PWA\n\nI'm using vite-plugin-compression2 to gzip the PWA files.\n\nHere's my `vite.config.ts`:\n\n```\nplugins: [\n eslint(),\n compression({\n algorithm: 'gzip',\n exclude: [/\\.(br)$ /, /\\.(gz)$/],\n }),\n // Deleting the originals will break the PWA because index.html gets deleted.\n compression({\n algorithm: 'brotliCompress',\n exclude: [/\\.(br)$ /, /\\.(gz)$/],\n deleteOriginalAssets: false,\n }),\n```\n\nThe problem is that this compression breaks my Android build, because Android's `gradle` attempts to compress the already compressed files, which gives a `duplicate resources` error and aborts the build.\n\nSo I want to apply the compression plugin for the PWA and iOS, but not for Android. How can I do that?\n\nThe Vite documentation describes conditional application of plugins for build/serve, but I need conditional application for two different ways to build.\n\n========================================\n\nCode:\n```text\nplugins: [\n    eslint(),\n    compression({\n      algorithm: 'gzip',\n      exclude: [/\\.(br)$ /, /\\.(gz)$/],\n    }),\n    // Deleting the originals will break the PWA because index.html gets deleted.\n    compression({\n      algorithm: 'brotliCompress',\n      exclude: [/\\.(br)$ /, /\\.(gz)$/],\n      deleteOriginalAssets: false,\n    }),\n```\n\n```text\nvite.config.ts\n```\n\n```text\ngradle\n```\n\n```text\nduplicate resources\n```\n\n```text\n// https://vitejs.dev/config/\nexport default ({ mode }) => {\n  // Make Vite env vars available.\n  // https://stackoverflow.com/a/66389044\n  process.env = { ...process.env, ...loadEnv(mode, process.cwd()) };\n  const isEnvBuildPwa = () => process.env.VITE_BUILD_PWA === 'true';\n\n  return defineConfig({\n    build: {\n        // All the build config.\n      },\n    },\n    plugins: [\n      eslint(),\n      isEnvBuildPwa() && compression({\n        algorithm: 'gzip',\n        exclude: [/\\.(br)$ /, /\\.(gz)$/],\n      }),\n      // Deleting the originals will break the PWA because index.html gets deleted.\n      isEnvBuildPwa() && compression({\n        algorithm: 'brotliCompress',\n        exclude: [/\\.(br)$ /, /\\.(gz)$/],\n        deleteOriginalAssets: false,\n      }),\n    ],\n  });\n};\n```\n\n```text\nVITE_BUILD_PWA\n```\n\n========================================\n\nComments:\n- for future anyone that lands on this answer, this works as vite accepts false-y plugins, which basically means you can gate whether a plugin is loaded via a method that returns true or false, per this citation from the vite docs: \"Falsy plugins will be ignored, which can be used to easily activate or deactivate plugins\"","metadata":{"transformedAt":"2026-08-18T18:33:46.438Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":106,"estimatedTokens":693}}588{"id":"stack-77230560","source":"stackoverflow","questionId":77230560,"title":"Disabling color output in Vite – Equivalent to webpack-cli's `--no-color`?","tags":["webpack","vite"],"text":"Title: Disabling color output in Vite – Equivalent to webpack-cli's `--no-color`?\nTags: webpack, vite\nSource: Stack Overflow\n\nQuestion:\nIs there a way to disable color output in Vite, similar to webpack-cli's `--no-color` option?\n\n- `--no-color` is not a valid parameter\n\n- I tried `FORCE_COLOR=0 vite` but I still see the colored output\n\n- Tried with `CI` env parameter but it didn't help either\n\nThank you!\n\n========================================\n\nCode:\n```text\n--no-color\n```\n\n```text\n--no-color\n```\n\n```text\nFORCE_COLOR=0 vite\n```\n\n```text\nCI\n```\n\n```text\nNO_COLOR=true\n```\n\n========================================\n\nComments:\n- Yes, `NODE_DISABLE_COLORS=1` worked as well Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:46.439Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":42,"estimatedTokens":172}}589{"id":"stack-75714004","source":"stackoverflow","questionId":75714004,"title":"is there a browserify for vite? how can I use webrtc-swarm with a vite based project?","tags":["vite","browserify","p2p"],"text":"Title: is there a browserify for vite? how can I use webrtc-swarm with a vite based project?\nTags: vite, browserify, p2p\nSource: Stack Overflow\n\nQuestion:\nThe title about says it. To use webrtc-swarm I believe that you need browserify -- Buffer is needed to be globally defined, and although there is a handy replacement, it won't load in time to resolve its requirement just by adding code like:\n\n```\nimport { Buffer } from 'buffer'\nglobalThis.Buffer = Buffer\n```\n\nThe usage that I implemented from webrtc-swarm's readme is:\n\n```\nimport swarm from 'webrtc-swarm'\nimport signalhub from 'signalhub'\n\n const hub = signalhub('swarm-example', [clientOpts.server])\n const swarmClient = swarm(hub)\n```\n\nthe error that I see is:\n\n```\nUncaught (in promise) TypeError: Buffer is undefined\n js index.js:12\n __require2 chunk-TFWDKVI3.js:18\n js browser.js:15\n __require2 chunk-TFWDKVI3.js:18\n js index.js:6\n __require2 chunk-TFWDKVI3.js:18\n js index.js:1\n __require2 chunk-TFWDKVI3.js:18\n webrtc-swarm.js:1620\n```\n\n========================================\n\nCode:\n```text\nimport { Buffer } from 'buffer'\nglobalThis.Buffer = Buffer\n```\n\n```text\nimport swarm from 'webrtc-swarm'\nimport signalhub from 'signalhub'\n\n  const hub = signalhub('swarm-example', [clientOpts.server])\n  const swarmClient = swarm(hub)\n```\n\n```text\nUncaught (in promise) TypeError: Buffer is undefined\n    js index.js:12\n    __require2 chunk-TFWDKVI3.js:18\n    js browser.js:15\n    __require2 chunk-TFWDKVI3.js:18\n    js index.js:6\n    __require2 chunk-TFWDKVI3.js:18\n    js index.js:1\n    __require2 chunk-TFWDKVI3.js:18\n    <anonymous> webrtc-swarm.js:1620\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport { nodePolyfills } from 'vite-plugin-node-polyfills'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [\n    nodePolyfills({\n      // Whether to polyfill `node:` protocol imports.\n      protocolImports: true,\n    }),\n  ],\n})\n```\n\n```js\n// vite.config.js\n\nexport default {\n  resolve: {\n    alias: {\n      // Ensure that you install 'rollup-plugin-polyfill-node' package\n      'events': 'rollup-plugin-node-polyfills/polyfills/events',\n    }\n}\n```\n\n```js\n// vite.config.js\nimport nodePolyfills from 'rollup-plugin-polyfill-node';\n\nexport default {\n  plugins: [\n    // Automatically polyfill all the core node.js modules\n    // May or may not be desirable depending on the required build.\n    // Also polyfill globals like `process` and `Buffer`.\n    nodePolyfills({})\n  ]\n}\n```\n\n```text\nevents\n```\n\n```text\nresolve.alias\n```\n\n```text\nrollup-plugin-node-polyfills\n```\n\n```text\nbuild.rollupOptions.plugins\n```\n\n```text\nBuffer\n```\n\n```text\nprocess\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.439Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":131,"estimatedTokens":664}}590{"id":"stack-72848937","source":"stackoverflow","questionId":72848937,"title":"laravel heroku Vite manifest not found at: /app/public/build/manifest.jso","tags":["laravel","npm","heroku","vite"],"text":"Title: laravel heroku Vite manifest not found at: /app/public/build/manifest.jso\nTags: laravel, npm, heroku, vite\nSource: Stack Overflow\n\nQuestion:\nafter uploading my project Laravel in Heroku say \"Vite manifest not found at: /app/public/build/manifest.json\"\n\nit work perfectly in localhost but in Heroku not working.\n\nthis is a preview of the problem\n\nhttps://res.cloudinary.com/wanis4007/image/upload/v1656872417/Screenshot_2022-07-03_211622_ohzgs5.png\n\nI run this code before push the project in Heroku\n\n```\nnpm install\nnpm run dev\nnpm run build\n```\n\nany suggestion ?\n\n========================================\n\nTop Answer:\nI solved my code with this\n\n`$ heroku buildpacks:add --index 1 heroku/nodejs` and\n`$ heroku buildpacks`\n\nafter running this in my terminal, I adjusted my code and push to heroku again.\nNote: The `--index 1` means nodejs build pack will run first before php. PHP Buildpack has already been reinstalled with laravel/heroku.\nwhen you run\n\n`heroku buildpacks`\n\nit should give you the two buildpacks which is\n\n```\n$ heroku/nodejs and heroku/php\n```\n\n========================================\n\nCode:\n```text\nnpm install\nnpm run dev\nnpm run build\n```\n\n```text\nheroku buildpacks:set heroku/php\nheroku buildpacks:set heroku/nodejs\n```\n\n```text\nheroku buildpacks\n```\n\n```text\n$ heroku plugins:install buildpack-registry\n$ heroku plugins:install buildpacks\n```\n\n```text\n$ heroku buildpacks\n```\n\n```text\n$ heroku buildpacks:set heroku/nodejs\n```\n\n```text\n$ heroku/nodejs and heroku/php\n```\n\n```text\n$ heroku buildpacks:add --index 1 heroku/nodejs\n```\n\n```text\n$ heroku buildpacks\n```\n\n```text\n--index 1\n```\n\n```text\nheroku buildpacks\n```\n\n========================================\n\nComments:\n- Also read: Vite manifest not found at: manifest.json in Laravel 9\n- Hi Solayman Mousa, I got an error on adding the first module, which is heroku buildpacks:set heroku/app Error: Cannot find module '@heroku/buildpack-registry', can you help me resolve this? thanks","metadata":{"transformedAt":"2026-08-18T18:33:46.439Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":99,"estimatedTokens":493}}591{"id":"stack-72577532","source":"stackoverflow","questionId":72577532,"title":"How to make VSCode recognize DefinitelyTyped global variable (grecaptcha) in Vuejs 3 TypeScript project","tags":["typescript","vue.js","vuejs3","vite","grecaptcha"],"text":"Title: How to make VSCode recognize DefinitelyTyped global variable (grecaptcha) in Vuejs 3 TypeScript project\nTags: typescript, vue.js, vuejs3, vite, grecaptcha\nSource: Stack Overflow\n\nQuestion:\nI have a **Vue.js 3 TypeScript** project scaffolded with the command `npm init vue@latest`. Now I want to add **reCaptcha v2** to the project **from scratch** instead of installing support libraries like `vue3-recaptcha-v2` etc.\n\nThen, instead of having to define the `grecaptcha` object myself, I used `npm i -D @types/grecaptcha` instead and in theory I should get the global variable `grecaptcha`, however, my VSCode cannot recognize this variable.\n\nScreenshot:\n\n`vite.config.js`\n\n```\nimport vueI18n from \"@intlify/vite-plugin-vue-i18n\";\nimport vue from \"@vitejs/plugin-vue\";\nimport { fileURLToPath, URL } from \"url\";\nimport { defineConfig } from \"vite\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [vue(), vueI18n({ useVueI18nImportName: true })],\n resolve: {\n alias: {\n \"@\": fileURLToPath(new URL(\"./src\", import.meta.url)),\n },\n },\n});\n```\n\n`tsconfig.json`\n\n```\n{\n \"extends\": \"@vue/tsconfig/tsconfig.web.json\",\n \"include\": [\"env.d.ts\", \"src/**/*\", \"src/**/*.vue\"],\n \"compilerOptions\": {\n \"baseUrl\": \".\",\n \"types\": [\"element-plus/global\", \"@intlify/vite-plugin-vue-i18n/client\"],\n \"paths\": {\n \"@/*\": [\"./src/*\"]\n }\n },\n\n \"references\": [\n {\n \"path\": \"./tsconfig.config.json\"\n }\n ]\n}\n```\n\n`tsconfig.config.json`\n\n```\n{\n \"extends\": \"@vue/tsconfig/tsconfig.node.json\",\n \"include\": [\"vite.config.*\", \"vitest.config.*\", \"cypress.config.*\"],\n \"compilerOptions\": {\n \"composite\": true,\n \"types\": [\"node\"]\n }\n}\n```\n\nThese files are initialized automatically by the command `npm init vue@latest`. Now what should I do to make VSCode understand global variables from https://github.com/DefinitelyTyped/DefinitelyTyped.\n\nMany thanks!\n\n========================================\n\nCode:\n```js\nimport vueI18n from \"@intlify/vite-plugin-vue-i18n\";\nimport vue from \"@vitejs/plugin-vue\";\nimport { fileURLToPath, URL } from \"url\";\nimport { defineConfig } from \"vite\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue(), vueI18n({ useVueI18nImportName: true })],\n  resolve: {\n    alias: {\n      \"@\": fileURLToPath(new URL(\"./src\", import.meta.url)),\n    },\n  },\n});\n```\n\n```js\n{\n  \"extends\": \"@vue/tsconfig/tsconfig.web.json\",\n  \"include\": [\"env.d.ts\", \"src/**/*\", \"src/**/*.vue\"],\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"types\": [\"element-plus/global\", \"@intlify/vite-plugin-vue-i18n/client\"],\n    \"paths\": {\n      \"@/*\": [\"./src/*\"]\n    }\n  },\n\n  \"references\": [\n    {\n      \"path\": \"./tsconfig.config.json\"\n    }\n  ]\n}\n```\n\n```js\n{\n  \"extends\": \"@vue/tsconfig/tsconfig.node.json\",\n  \"include\": [\"vite.config.*\", \"vitest.config.*\", \"cypress.config.*\"],\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"types\": [\"node\"]\n  }\n}\n```\n\n```text\nnpm init vue@latest\n```\n\n```text\nvue3-recaptcha-v2\n```\n\n```text\ngrecaptcha\n```\n\n```text\nnpm i -D @types/grecaptcha\n```\n\n```text\ngrecaptcha\n```\n\n```text\nvite.config.js\n```\n\n```text\ntsconfig.json\n```\n\n```text\ntsconfig.config.json\n```\n\n```text\nnpm init vue@latest\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"types\": [\"@types/grecaptcha\"]\n  },\n  ⋮\n}\n```\n\n```text\ntsconfig.json\n```\n\n```text\n@types/grecaptcha\n```\n\n```text\ncompilerOptions.types[]\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.439Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":176,"estimatedTokens":832}}592{"id":"stack-72351035","source":"stackoverflow","questionId":72351035,"title":"Building for vue2 and vue3 in monorepo: Version mismatch error from vue-template-compiler","tags":["vue.js","vite","pnpm","pnpm-workspace"],"text":"Title: Building for vue2 and vue3 in monorepo: Version mismatch error from vue-template-compiler\nTags: vue.js, vite, pnpm, pnpm-workspace\nSource: Stack Overflow\n\nQuestion:\nLet's say I have two packages in a monorepo using pnpm. One for Vue@3 (`package-a`), one other for Vue@2 (`package-b`). For the record, they both depend on a third package called `core`.\n\nYou can find what it looks like below:\n\n```\n.\n├── .npmrc\n├── .nvmrc\n├── package.json\n├── packages\n│   ├── package-a\n│   │   ├── index.ts\n│   │   ├── node_modules\n│   │   │   ├── .bin\n│   │   │   │   ├── tsc\n│   │   │   │   ├── tsserver\n│   │   │   │   ├── vite\n│   │   │   │   └── vue-tsc\n│   │   │   ├── @myscope\n│   │   │   │   └── core -> ../../../core\n│   │   │   ├── @vitejs\n│   │   │   │   └── plugin-vue -> ../../../../node_modules/.pnpm/@vitejs+plugin-vue@2.3.3_vite@2.9.9+vue@3.2.36/node_modules/@vitejs/plugin-vue\n│   │   │   ├── typescript -> ../../../node_modules/.pnpm/typescript@4.6.4/node_modules/typescript\n│   │   │   ├── vite -> ../../../node_modules/.pnpm/vite@2.9.9/node_modules/vite\n│   │   │   ├── vue -> ../../../node_modules/.pnpm/vue@3.2.36/node_modules/vue\n│   │   │   └── vue-tsc -> ../../../node_modules/.pnpm/vue-tsc@0.34.16_typescript@4.6.4/node_modules/vue-tsc\n│   │   ├── package.json\n│   │   ├── tsconfig.json\n│   │   ├── tsconfig.node.json\n│   │   └── vite.config.ts\n│   ├── package-b\n│   │   ├── index.ts\n│   │   ├── node_modules\n│   │   │   ├── .bin\n│   │   │   │   ├── tsc\n│   │   │   │   ├── tsserver\n│   │   │   │   ├── vite\n│   │   │   │   └── vue-tsc\n│   │   │   ├── @myscope\n│   │   │   │   └── core -> ../../../core\n│   │   │   ├── typescript -> ../../../node_modules/.pnpm/typescript@4.6.4/node_modules/typescript\n│   │   │   ├── vite -> ../../../node_modules/.pnpm/vite@2.9.9/node_modules/vite\n│   │   │   ├── vite-plugin-vue2 -> ../../../node_modules/.pnpm/vite-plugin-vue2@2.0.1_dj3dtukdyynhbiqf2xbv2ocyei/node_modules/vite-plugin-vue2\n│   │   │   ├── vue -> ../../../node_modules/.pnpm/vue@2.6.14/node_modules/vue\n│   │   │   ├── vue-template-compiler -> ../../../node_modules/.pnpm/vue-template-compiler@2.6.14/node_modules/vue-template-compiler\n│   │   │   └── vue-tsc -> ../../../node_modules/.pnpm/vue-tsc@0.34.16_typescript@4.6.4/node_modules/vue-tsc\n│   │   ├── package.json\n│   │   ├── tsconfig.json\n│   │   ├── tsconfig.node.json\n│   │   └── vite.config.ts\n│   └── core\n│   ├── index.ts\n│   └── package.json\n├── pnpm-lock.yaml\n└── pnpm-workspace.yaml\n```\n\nIn `packages/package-a/package.json`:\n\n```\n{\n \"name\": \"@myscope/package-a\",\n \"version\": \"0.0.0\",\n \"private\": true,\n \"scripts\": {\n \"build\": \"vue-tsc --noEmit && vite build\"\n },\n \"dependencies\": {\n \"@myscope/core\": \"workspace:*\",\n \"vue\": \"^3.2.25\"\n },\n \"devDependencies\": {\n \"@vitejs/plugin-vue\": \"^2.3.3\",\n \"typescript\": \"^4.5.4\",\n \"vite\": \"^2.9.9\",\n \"vue-tsc\": \"^0.34.7\"\n }\n}\n```\n\nIn `packages/package-b/package.json`\n\n```\n{\n \"name\": \"@myscope/package-b\",\n \"version\": \"0.0.0\",\n \"private\": true,\n \"scripts\": {\n \"build\": \"vue-tsc --noEmit && vite build\"\n },\n \"dependencies\": {\n \"@myscope/core\": \"workspace:*\",\n \"vue\": \"^2.6.14\"\n },\n \"devDependencies\": {\n \"typescript\": \"^4.5.4\",\n \"vite\": \"^2.9.9\",\n \"vite-plugin-vue2\": \"^2.0.0\",\n \"vue-template-compiler\": \"^2.6.14\",\n \"vue-tsc\": \"^0.34.7\"\n }\n}\n```\n\nWhen I run `pnpm run build` in `package-b` (Vue@2) I get the version mismatch error whereas it shouldnt:\n\n```\n> vue-tsc --noEmit && vite build\n\nfailed to load config from /path/to/my/project/monorepo/packages/package-b/vite.config.ts\nerror during build:\nError: \n\nVue packages version mismatch:\n\n- vue@3.2.36 (/path/to/my/project/monorepo/node_modules/.pnpm/vue@3.2.36/node_modules/vue/index.js)\n- vue-template-compiler@2.6.14 (/path/to/my/project/monorepo/node_modules/.pnpm/vue-template-compiler@2.6.14/node_modules/vue-template-compiler/package.json)\n\nThis may cause things to work incorrectly. Make sure to use the same version for both.\nIf you are using vue-loader@>=10.0, simply update vue-template-compiler.\nIf you are using vue-loader@ (/path/to/my/project/monorepo/node_modules/.pnpm/vue-template-compiler@2.6.14/node_modules/vue-template-compiler/index.js:10:9)\n at Module._compile (node:internal/modules/cjs/loader:1101:14)\n at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)\n at Module.load (node:internal/modules/cjs/loader:981:32)\n at Function.Module._load (node:internal/modules/cjs/loader:822:12)\n at Module.require (node:internal/modules/cjs/loader:1005:19)\n at require (node:internal/modules/cjs/helpers:102:18)\n at Object. (/path/to/my/project/monorepo/node_modules/.pnpm/vite-plugin-vue2@2.0.1_dj3dtukdyynhbiqf2xbv2ocyei/node_modules/vite-plugin-vue2/dist/utils/descriptorCache.js:34:42)\n at Module._compile (node:internal/modules/cjs/loader:1101:14)\n at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)\n at Module.load (node:internal/modules/cjs/loader:981:32)\n at Function.Module._load (node:internal/modules/cjs/loader:822:12)\n at Module.require (node:internal/modules/cjs/loader:1005:19)\n at require (node:internal/modules/cjs/helpers:102:18)\n at Object. (/path/to/my/project/monorepo/node_modules/.pnpm/vite-plugin-vue2@2.0.1_dj3dtukdyynhbiqf2xbv2ocyei/node_modules/vite-plugin-vue2/dist/main.js:35:27)\n at Module._compile (node:internal/modules/cjs/loader:1101:14)\n ELIFECYCLE  Command failed with exit code 1.\n ELIFECYCLE  Command failed with exit code 1.\n```\n\nIt seems that the resolved version doesn't follows `package.json` and uses `Vue@3` instead of `Vue@2`. I don't understand why. Could this be a bug about how `vue-template-compiler` resolves Vue or something?\n\nA \"dirty\" workaround I've found to get it work is to add `hoist=false` to `.npmrc` at the project's root but I don't know what are the possible side-effects I can get by doing this. Anyway, is there a cleaner way to fix this?\n\nPS. This can be related to https://github.com/vuejs/vue/issues/11828 but I'm asking here do do not reply in a closed issue.\n\n========================================\n\nCode:\n```text\n.\n├── .npmrc\n├── .nvmrc\n├── package.json\n├── packages\n│   ├── package-a\n│   │   ├── index.ts\n│   │   ├── node_modules\n│   │   │   ├── .bin\n│   │   │   │   ├── tsc\n│   │   │   │   ├── tsserver\n│   │   │   │   ├── vite\n│   │   │   │   └── vue-tsc\n│   │   │   ├── @myscope\n│   │   │   │   └── core -> ../../../core\n│   │   │   ├── @vitejs\n│   │   │   │   └── plugin-vue -> ../../../../node_modules/.pnpm/@vitejs+plugin-vue@2.3.3_vite@2.9.9+vue@3.2.36/node_modules/@vitejs/plugin-vue\n│   │   │   ├── typescript -> ../../../node_modules/.pnpm/typescript@4.6.4/node_modules/typescript\n│   │   │   ├── vite -> ../../../node_modules/.pnpm/vite@2.9.9/node_modules/vite\n│   │   │   ├── vue -> ../../../node_modules/.pnpm/vue@3.2.36/node_modules/vue\n│   │   │   └── vue-tsc -> ../../../node_modules/.pnpm/vue-tsc@0.34.16_typescript@4.6.4/node_modules/vue-tsc\n│   │   ├── package.json\n│   │   ├── tsconfig.json\n│   │   ├── tsconfig.node.json\n│   │   └── vite.config.ts\n│   ├── package-b\n│   │   ├── index.ts\n│   │   ├── node_modules\n│   │   │   ├── .bin\n│   │   │   │   ├── tsc\n│   │   │   │   ├── tsserver\n│   │   │   │   ├── vite\n│   │   │   │   └── vue-tsc\n│   │   │   ├── @myscope\n│   │   │   │   └── core -> ../../../core\n│   │   │   ├── typescript -> ../../../node_modules/.pnpm/typescript@4.6.4/node_modules/typescript\n│   │   │   ├── vite -> ../../../node_modules/.pnpm/vite@2.9.9/node_modules/vite\n│   │   │   ├── vite-plugin-vue2 -> ../../../node_modules/.pnpm/vite-plugin-vue2@2.0.1_dj3dtukdyynhbiqf2xbv2ocyei/node_modules/vite-plugin-vue2\n│   │   │   ├── vue -> ../../../node_modules/.pnpm/vue@2.6.14/node_modules/vue\n│   │   │   ├── vue-template-compiler -> ../../../node_modules/.pnpm/vue-template-compiler@2.6.14/node_modules/vue-template-compiler\n│   │   │   └── vue-tsc -> ../../../node_modules/.pnpm/vue-tsc@0.34.16_typescript@4.6.4/node_modules/vue-tsc\n│   │   ├── package.json\n│   │   ├── tsconfig.json\n│   │   ├── tsconfig.node.json\n│   │   └── vite.config.ts\n│   └── core\n│       ├── index.ts\n│       └── package.json\n├── pnpm-lock.yaml\n└── pnpm-workspace.yaml\n```\n\n```json\n{\n  \"name\": \"@myscope/package-a\",\n  \"version\": \"0.0.0\",\n  \"private\": true,\n  \"scripts\": {\n    \"build\": \"vue-tsc --noEmit && vite build\"\n  },\n  \"dependencies\": {\n    \"@myscope/core\": \"workspace:*\",\n    \"vue\": \"^3.2.25\"\n  },\n  \"devDependencies\": {\n    \"@vitejs/plugin-vue\": \"^2.3.3\",\n    \"typescript\": \"^4.5.4\",\n    \"vite\": \"^2.9.9\",\n    \"vue-tsc\": \"^0.34.7\"\n  }\n}\n```\n\n```json\n{\n  \"name\": \"@myscope/package-b\",\n  \"version\": \"0.0.0\",\n  \"private\": true,\n  \"scripts\": {\n    \"build\": \"vue-tsc --noEmit && vite build\"\n  },\n  \"dependencies\": {\n    \"@myscope/core\": \"workspace:*\",\n    \"vue\": \"^2.6.14\"\n  },\n  \"devDependencies\": {\n    \"typescript\": \"^4.5.4\",\n    \"vite\": \"^2.9.9\",\n    \"vite-plugin-vue2\": \"^2.0.0\",\n    \"vue-template-compiler\": \"^2.6.14\",\n    \"vue-tsc\": \"^0.34.7\"\n  }\n}\n```\n\n```text\n> vue-tsc --noEmit && vite build\n\nfailed to load config from /path/to/my/project/monorepo/packages/package-b/vite.config.ts\nerror during build:\nError: \n\nVue packages version mismatch:\n\n- vue@3.2.36 (/path/to/my/project/monorepo/node_modules/.pnpm/vue@3.2.36/node_modules/vue/index.js)\n- vue-template-compiler@2.6.14 (/path/to/my/project/monorepo/node_modules/.pnpm/vue-template-compiler@2.6.14/node_modules/vue-template-compiler/package.json)\n\nThis may cause things to work incorrectly. Make sure to use the same version for both.\nIf you are using vue-loader@>=10.0, simply update vue-template-compiler.\nIf you are using vue-loader@<10.0 or vueify, re-installing vue-loader/vueify should bump vue-template-compiler to the latest.\n\n    at Object.<anonymous> (/path/to/my/project/monorepo/node_modules/.pnpm/vue-template-compiler@2.6.14/node_modules/vue-template-compiler/index.js:10:9)\n    at Module._compile (node:internal/modules/cjs/loader:1101:14)\n    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)\n    at Module.load (node:internal/modules/cjs/loader:981:32)\n    at Function.Module._load (node:internal/modules/cjs/loader:822:12)\n    at Module.require (node:internal/modules/cjs/loader:1005:19)\n    at require (node:internal/modules/cjs/helpers:102:18)\n    at Object.<anonymous> (/path/to/my/project/monorepo/node_modules/.pnpm/vite-plugin-vue2@2.0.1_dj3dtukdyynhbiqf2xbv2ocyei/node_modules/vite-plugin-vue2/dist/utils/descriptorCache.js:34:42)\n    at Module._compile (node:internal/modules/cjs/loader:1101:14)\n    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)\n    at Module.load (node:internal/modules/cjs/loader:981:32)\n    at Function.Module._load (node:internal/modules/cjs/loader:822:12)\n    at Module.require (node:internal/modules/cjs/loader:1005:19)\n    at require (node:internal/modules/cjs/helpers:102:18)\n    at Object.<anonymous> (/path/to/my/project/monorepo/node_modules/.pnpm/vite-plugin-vue2@2.0.1_dj3dtukdyynhbiqf2xbv2ocyei/node_modules/vite-plugin-vue2/dist/main.js:35:27)\n    at Module._compile (node:internal/modules/cjs/loader:1101:14)\n ELIFECYCLE  Command failed with exit code 1.\n ELIFECYCLE  Command failed with exit code 1.\n```\n\n```text\npackage-a\n```\n\n```text\npackage-b\n```\n\n```text\ncore\n```\n\n```text\npackages/package-a/package.json\n```\n\n```text\npackages/package-b/package.json\n```\n\n```text\npnpm run build\n```\n\n```text\npackage-b\n```\n\n```text\npackage.json\n```\n\n```text\nVue@3\n```\n\n```text\nVue@2\n```\n\n```text\nvue-template-compiler\n```\n\n```text\nhoist=false\n```\n\n```text\n.npmrc\n```\n\n```none\ndiff --git i/package.json w/package.json\nindex 95cda08..182e89d 100644\n--- i/package.json\n+++ w/package.json\n@@ -41,5 +41,14 @@\n   \"packageManager\": \"pnpm@7.1.3\",\n   \"engines\": {\n     \"node\": \">=16.15.0\"\n+  },\n+  \"pnpm\": {\n+    \"packageExtensions\": {\n+      \"vue-template-compiler\": {\n+        \"peerDependencies\": {\n+          \"vue\": \"^2.6.14\"\n+        }\n+      }\n+    }\n   }\n }\n```\n\n```text\npnpm.packageExtensions\n```\n\n```text\nnohoist=false\n```\n\n```text\n.npmrc\n```\n\n========================================\n\nComments:\n- The biggest high five of the day to you, @bgondy! Really helped me out.\n- This should not be an issue as of `vue@2.7` since `vue-template-compiler` is not used anymore.","metadata":{"transformedAt":"2026-08-18T18:33:46.439Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":377,"estimatedTokens":3040}}593{"id":"stack-73068281","source":"stackoverflow","questionId":73068281,"title":"process.env.NODE_ENV suddenly UNDEFINED in current SvelteKit project","tags":["node.js","vite","sveltekit"],"text":"Title: process.env.NODE_ENV suddenly UNDEFINED in current SvelteKit project\nTags: node.js, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nInside `svelte.config.js` I was using this\n\n```\nconst dev = process.env.NODE_ENV === 'development';\n```\n\nto conditionally set a base path which was working fine in projects with `@sveltejs/kit@1.0.0-next.350` and `*.357`\n\nAfter installing now the most recent SvelteKit version `@sveltejs/kit@1.0.0-next.386` it only results to `undefined`\n\nDifferences I notice is that the new project lists `\"vite\": \"^3.0.0\"` as devDependency and the script changed from `\"dev\": \"svelte-kit dev\",` to `\"dev\": \"vite dev\"`\n\nUpdate: It's also the case for a project with `@sveltejs/kit@1.0.0-next.366`, `vite@2.9.14`, `\"dev\": \"vite dev\"` - so the switch was before vite 3.0\n\nGoing through the vite docs I find `import.meta.env`, but that's also `undefined` inside `svelte.config.js`\n\nSwitching from Node v16 to 17 didn't make a difference as well\n\nWhat changed and how can I now distinguish between `dev` and `build` mode?\n\n========================================\n\nTop Answer:\nThis might help someone in the future. I encountered this error when I created an express server in a react application. I created the server directory in the root folder of the react application and I was running both react app and express server at the same time.\n\n========================================\n\nCode:\n```text\nconst dev = process.env.NODE_ENV === 'development';\n```\n\n```text\nsvelte.config.js\n```\n\n```text\n@sveltejs/kit@1.0.0-next.350\n```\n\n```text\n*.357\n```\n\n```text\n@sveltejs/kit@1.0.0-next.386\n```\n\n```text\nundefined\n```\n\n```text\n\"vite\": \"^3.0.0\"\n```\n\n```text\n\"dev\": \"svelte-kit dev\",\n```\n\n```text\n\"dev\": \"vite dev\"\n```\n\n```text\n@sveltejs/kit@1.0.0-next.366\n```\n\n```text\nvite@2.9.14\n```\n\n```text\n\"dev\": \"vite dev\"\n```\n\n```text\nimport.meta.env\n```\n\n```text\nundefined\n```\n\n```text\nsvelte.config.js\n```\n\n```text\ndev\n```\n\n```text\nbuild\n```\n\n```text\nexport NODE_ENV=development && npm run dev\n```\n\n```text\nNODE_DEV\n```\n\n========================================\n\nComments:\n- Hint: backticks do not work in question string.\n- I'm not sure - is this really related to `$app&#47;env`? I'm not in a `src&#47;` project file but in the `svelte.config.js`. I first thought it was only with the current version and somehow related to vite 3, but it's the same in a project with `next.366` and `vite@2.9.14`. The vite docs page you linked is where I got `import.meta.env` from which as stated unforunately doesn't work in the config file.\n- I see what you say. Then, shouldn't be enough to export `NODE_ENV` environment variable?\n- export how/where?\n- it depends on your environment/os. for linux development I run `export NODE_ENV='dev' npm run dev`. ymmv\n- I'm on Mac and `export NODE_ENV=development && ...` seems to be doing the trick, great! Thanks!!","metadata":{"transformedAt":"2026-08-18T18:33:46.439Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":118,"estimatedTokens":714}}594{"id":"stack-72017405","source":"stackoverflow","questionId":72017405,"title":"\"TypeError: can't convert undefined to object\" only after vite build, before, with vide dev, everything works perfectly","tags":["javascript","reactjs","typescript","material-ui","vite"],"text":"Title: \"TypeError: can't convert undefined to object\" only after vite build, before, with vide dev, everything works perfectly\nTags: javascript, reactjs, typescript, material-ui, vite\nSource: Stack Overflow\n\nQuestion:\nI'm using Vite combined with React and Typescript.\nWhen I run `vite dev` the live version of the website runs perfectly, not even errors on the console.\n\nWhen I run `vite build` and then `vite preview` all I get to see is a white page and the\n`TypeError: can't convert undefined to object`\nerror in the console.\n\nI cannot trace the problem in my code because the error happens after the build/minimization, but just to be sure, I added safety checks in the instances where I call `Object.keys()`.\n\nThis is the segment of the code where the error starts:\n\n```\nObject.keys(pd).forEach(function (e) {\n if (pd[e] === 0)\n Xd.prototype[\"on\" + e] = function () {\n this.scope.emit(e);\n };\n else if (pd[e] === 1)\n Xd.prototype[\"on\" + e] = function (t) {\n this.scope.emit(e, t);\n };\n});\n```\n\nEdit:\n\nI was checking the minimized code and right before the long block of code where the bug is, I saw a MuiTouchRipple. I'm using the MaterialUI library, is it possible that the library is causing this problem?\nI tried to update from version 5.4.2 to 5.6.3, but after the build it still crashes.\n\nhttps://i.sstatic.net/DpooZ.png\n\n========================================\n\nTop Answer:\nI had similar problem, and for me this was caused by `\"target\": \"es5\"` in tsconfig.json.\n\nAfter changing to `esnext`, problem is gone.\n\nhttps://esbuild.github.io/content-types/#es5\n\n========================================\n\nCode:\n```js\nObject.keys(pd).forEach(function (e) {\n  if (pd[e] === 0)\n    Xd.prototype[\"on\" + e] = function () {\n      this.scope.emit(e);\n    };\n  else if (pd[e] === 1)\n    Xd.prototype[\"on\" + e] = function (t) {\n      this.scope.emit(e, t);\n    };\n});\n```\n\n```text\nvite dev\n```\n\n```text\nvite build\n```\n\n```text\nvite preview\n```\n\n```text\nTypeError: can't convert undefined to object\n```\n\n```text\nObject.keys()\n```\n\n```text\nnode_modules\n```\n\n```text\ngrep -r\n```\n\n```text\n\"target\": \"es5\"\n```\n\n```text\nesnext\n```\n\n```text\nbuild.lib.formats\n```\n\n```text\nvite.config.ts\n```\n\n========================================\n\nComments:\n- There's not enough context to reproduce the problem. Can you show the code that causes the problem?\n- That's what I'm saying, i don't know where the code that causes the problem is. My code runs smoothly, and both eslint and typescript report no errors. The problem appears only after minimization and as you can see in the screenshot I attached, it doesn't point to a specific file, but to the minimized bundle.\n- same package was giving me error, found a replacement html-react-parse, changed it and it worked!!\n- Thank you @Berenluth and @partizan! Your answers brought me onto the right track!","metadata":{"transformedAt":"2026-08-18T18:33:46.439Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":112,"estimatedTokens":709}}595{"id":"stack-71107754","source":"stackoverflow","questionId":71107754,"title":"Build is not working in React.js using Vite bundler","tags":["javascript","reactjs","vite"],"text":"Title: Build is not working in React.js using Vite bundler\nTags: javascript, reactjs, vite\nSource: Stack Overflow\n\nQuestion:\nI use Webpack before and wanted to change it to Vite. I copied all the file from the Webpack version to the Vite version. When I run `yarn dev` it work, but when I build it and run the build with `serve dist` it give me this error on the browser and it won't render any thing:\n\nReferenceError: React is not defined\n\n========================================\n\nTop Answer:\nYou need to use this config, (take a look at `@vitejs/plugin-react` which you probably need to install)\n\n`vite.config.js`:\n\n```\nimport react from \"@vitejs/plugin-react\";\nimport { defineConfig } from \"vite\";\n\nexport default ({ mode }) => {\n return defineConfig({\n plugins: [\n react(),\n ],\n });\n};\n```\n\nThe thing is that vite does not import React by default into jsx components, so you need to do it manually in every component or use this plugin.\n\n========================================\n\nCode:\n```text\nyarn dev\n```\n\n```text\nserve dist\n```\n\n```text\nimport react from \"@vitejs/plugin-react\";\nimport { defineConfig } from \"vite\";\n\nexport default ({ mode }) => {\n  return defineConfig({\n    plugins: [\n      react(),\n    ],\n  });\n};\n```\n\n```text\n@vitejs/plugin-react\n```\n\n```text\nvite.config.js\n```\n\n========================================\n\nComments:\n- Have you tried `npm isntall` again so all dependencies can be installed ?\n- You shared too little information about the issue; the error is not reproducible. It would be necessary to know how you set up the Vite project. In fact, Vite provides proper guides and starter kits. vite.dev/guide/#trying-vite-online - vite.new/react-ts - `npm create vite@latest my-react-app -- --template react`\n- this now comes with new vite react installation by default.\n- I've got exactly the same issue with react-custom-scrollbars-2. It's quite strange that Vite doesn't show just errors in dev mode.","metadata":{"transformedAt":"2026-08-18T18:33:46.439Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":70,"estimatedTokens":483}}596{"id":"stack-71018015","source":"stackoverflow","questionId":71018015,"title":"Vite.js (Vue): Unwanted Page Reload Happens Only On Samsung Internet","tags":["javascript","vue.js","vite"],"text":"Title: Vite.js (Vue): Unwanted Page Reload Happens Only On Samsung Internet\nTags: javascript, vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nI have a weird problem with `Vite.js` and it only happens on `Samsung Internet` when I'm on development server...\n\nProblem: page reloads automatically 3 seconds in a loop and I don't set nor write any intervals... the page reload happens at browser level.\n\nThese are unwanted reloads and I want to get rid of them.\n\nAny Idea why it happens?\n\n========================================\n\nTop Answer:\n**Edited asnwer:**\n\nOk so, I looked closer to this problem and I found some possible solutions.\n\nSamsung Internet (same as Chrome) doesn't allow unsecure websocket (ws) connections to localhost (only wss, so you should setup a TLS certificate for your local web/websocket server). However the same should work fine with Firefox.\n\nAnother reason for this error could be \"overloading\" the same port. Maybe other app, which you are running, uses port 3000. The solution would be to stop that process or again change the port.\n\nTesting solution: Does the code works if you do this?\n\n```\n// Original line\nnew WebSocket(`${socketProtocol}://${socketHost}`, 'vite-hmr')\n\n// Replace with exact url with port that you are running the app\nnew WebSocket(\"ws://localhost:3000\")\n```\n\n========================================\n\nCode:\n```text\nVite.js\n```\n\n```text\nSamsung Internet\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  ⋮\n  server: {\n    https: true,\n  }\n})\n```\n\n```text\nserver.https\n```\n\n```js\n// Original line\nnew WebSocket(`${socketProtocol}://${socketHost}`, 'vite-hmr')\n\n\n// Replace with exact url with port that you are running the app\nnew WebSocket(\"ws://localhost:3000\")\n```\n\n========================================\n\nComments:\n- @tony19 first I installed the app using: npm init vite@latest my-vue-app -- --template vue-ts and then run npm run dev -- --host. After that navigate to the network IP address via a Samsung Mobile Browser. I tested in latest 3 version of Samsung Internet Browser and it was there...\n- @Ehrlich_Bachman I just created the vite application and changed nothing..I created an issue in vite.js github too...\n- @mahatmanich I found the problem and it was not for Samsung Internet...I ran a debugger on Samsung Internet and the problem as exactly like this: `client.ts:28 WebSocket connection to 'ws:&#47;&#47;:3000&#47;' failed: Error in connection establishment: net::ERR_SSL_PROTOCOL_ERROR`\n- I had different problem for developing for safari. So I changed browser for developing. Recommend swapping it.\n- I ran a debugger on Samsung Internet and the problem as exactly like this: `client.ts:28 WebSocket connection to 'ws:&#47;&#47;:3000&#47;' failed: Error in connection establishment: net::ERR_SSL_PROTOCOL_ERROR`\n- This is the piece of code that causing the bug from `vite.js`..I think if I disable `hmr` from vite.js the problem would solve\n- The websocket is not in my codes. it's from `vite.js core`...\n- Vite.js uses `hmr` for hot reloading and to handle the updates it opens a websocket connection to the browser to listening for changes in codes in order to refresh the browser...The problem is from `Vite.js` core... take a look at this code: github.com/vitejs/vite/blob/&hellip;\n- Changed my answer, is any method working?\n- @Atzuki No. I just enabled https server in vite.js configurations and it started working..It seems Samsung Internet browser disallows insecure websockets.\n- That's exactly what I said in my 3rd paragraph, but ok. Atleast you figured it out.","metadata":{"transformedAt":"2026-08-18T18:33:46.439Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":84,"estimatedTokens":898}}597{"id":"stack-74877171","source":"stackoverflow","questionId":74877171,"title":"Prefix Vue3 & TailwindCSS on build only","tags":["vue.js","vuejs3","tailwind-css","vite","postcss"],"text":"Title: Prefix Vue3 & TailwindCSS on build only\nTags: vue.js, vuejs3, tailwind-css, vite, postcss\nSource: Stack Overflow\n\nQuestion:\nIntroducing a new frontend stack (Vue3, Tailwind CSS) into an already established application.\n\nThe old stack has dependencies which includes CSS classes that conflict with Tailwind.\n\nThe end goal is to use ***only*** Vue and TailwindCSS, so I don't want to use a prefix during development as it won't be necessary... but I need to support both old and new stack until I am able to entirely remove the old CSS.\n\nI am aware of using the prefix property in the TW config (`prefix: 'tw-',`) but this means the source .vue files will need to use the prefix.\n\nAm I able to tell Vue during *build only* (using Vite) to add a prefix to all classes, then likewise pass a rule to Tailwind during *build only* to add the prefix (but not required during development)?\n\nI saw a similar question where an answer mentioned if this existed in TW, then how would TW know which to convert and which not to... I understand this but in my scenario I have no other plugin.\n\nI've had a brief look at `postcss-prefixer` but not sure if that's what I need...\n\nI guess I can just use the TW prefixer as it's not the end of the world, but feels dirty for my end goal...\n\n========================================\n\nCode:\n```text\nprefix: 'tw-',\n```\n\n```text\npostcss-prefixer\n```\n\n========================================\n\nComments:\n- Yeah you're right, the cleanest option is to re-build and release when entirely finished. I was hoping there would be an option to support this edge-case but I understand it's a weird one as I'm trying to force two different systems to interact in an uncommon way that I want... I think I will just deal with the prefix!","metadata":{"transformedAt":"2026-08-18T18:33:46.439Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":36,"estimatedTokens":440}}598{"id":"stack-71744750","source":"stackoverflow","questionId":71744750,"title":"Vite React TypeScript monorepo hot module reloading (HMR) not working","tags":["reactjs","typescript","vite","hot-module-replacement"],"text":"Title: Vite React TypeScript monorepo hot module reloading (HMR) not working\nTags: reactjs, typescript, vite, hot-module-replacement\nSource: Stack Overflow\n\nQuestion:\nI have a Vite/React/Typescript/Yarn monorepo that contains two applications and some shared components. I'm having trouble getting HMR working when running `vite dev`.\n\nThe example repo is here: https://github.com/jakeboone02/em-hmr-test. If you run `yarn && yarn start:app1`, open http://localhost:3012/, then edit any of the components and save, the page will reload instead of just replacing the component in place.\n\nThe repo is a stripped down version of the actual proprietary code. I tried converting all the exports to `default`s as suggested in this discussion question answer, but the page still reloads on every change.\n\nIs there something wrong with the Vite config that is preventing HMR from working?\n\n========================================\n\nTop Answer:\nFor me i found out after a bunch of struggle that it was someone’s bad class init call not wrapped in a singleton pattern in our stack, so not Vite or HMR but HMR reinitiating something that shouldn’t be reinitiatable so it errored out. By wrapping it in a singleton pattern it stopped pausing the second hot module reload. So pay very close attention to your browser console warnings and local server logs on this one before chasing random confit stuff with vite, it’s possibly not vite at all\n\n========================================\n\nCode:\n```text\nvite dev\n```\n\n```text\nyarn && yarn start:app1\n```\n\n```text\ndefault\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.439Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":32,"estimatedTokens":390}}599{"id":"stack-69589953","source":"stackoverflow","questionId":69589953,"title":"vite/rollup with @rollup/plugin-babel does not strip template literal backticks when set to ie >= 11","tags":["javascript","internet-explorer","babeljs","template-literals","vite"],"text":"Title: vite/rollup with @rollup/plugin-babel does not strip template literal backticks when set to ie >= 11\nTags: javascript, internet-explorer, babeljs, template-literals, vite\nSource: Stack Overflow\n\nQuestion:\nAttempting to use Vite in library mode to compile an ES6 `.js` files down to a bundled ES5 `.js` file that will run in Internet Explorer 11. In my actual app there are several files that use ESM import/export, however I have verified that I can reproduce the problem with a single, simplified example file. Which I will include below.\n\nHere is my configuration:\n\n```\n//vite.config.js\nconst path = require('path');\nconst { defineConfig } = require('vite');\nimport { babel } from '@rollup/plugin-babel';\n\nmodule.exports = defineConfig({\n esbuild: false,\n plugins: [\n babel({\n babelHelpers: 'bundled',\n presets: [['@babel/preset-env', { targets: { browsers: 'defaults, ie >= 11' } }]],\n }),\n ],\n build: {\n outDir: 'javascript',\n lib: {\n entry: path.resolve(__dirname, 'js-src/index.js'),\n name: 'MyLib',\n fileName: (format) => 'my-lib.js',\n },\n },\n});\n```\n\nTest File:\n\n```\nconst aWord = 'World';\nconst multiLineString = `\n Hello ${aWord}\n`;\nconsole.log(multiLineString);\n```\n\nResulting output file:\n\n```\n(function(n){typeof define==\"function\"&&define.amd?define(n):n()})(function(){\"use strict\";var n=`\n Hello `.concat(aWord,`\n`);console.log(n)});\n```\n\nNotice how the transpiled code does down-shift to ES5 (see `var` instead of `const`) but it does not remove the template literal backticks and convert them to some other type of string that is safe for Internet Explorer 11. It only happens on multi-line template literal strings though. A single-line template literal will get changed to a string with `\"` characters.\n\nLooking for a solution to force babel to remove these backtick characters and convert them a supported type of string (that preserves the linebreaks as well)\n\n========================================\n\nTop Answer:\nYou can use @vitejs/plugin-legacy to support IE 11 in Vite.\n\nI test with a simple Vite project with vanilla JavaScript and add the test file code like yours. I first run `npm i -D @vitejs/plugin-legacy`, then use a **vite.config.js** file like below:\n\n```\nimport legacy from '@vitejs/plugin-legacy'\n\nexport default {\n plugins: [\n legacy({\n targets: ['ie >= 11'],\n additionalLegacyPolyfills: ['regenerator-runtime/runtime']\n })\n ]\n}\n```\n\nThen I run `npm run build`, the generated js file in **dist** folder is like below which supports IE 11:\n\n```\nSystem.register([],(function(){\"use strict\";return{execute:function(){var e=\"\\n Hello \".concat(\"World\",\"\\n\");console.log(e)}}}));\n```\n\n========================================\n\nCode:\n```text\n//vite.config.js\nconst path = require('path');\nconst { defineConfig } = require('vite');\nimport { babel } from '@rollup/plugin-babel';\n\nmodule.exports = defineConfig({\n  esbuild: false,\n  plugins: [\n    babel({\n      babelHelpers: 'bundled',\n      presets: [['@babel/preset-env', { targets: { browsers: 'defaults, ie >= 11' } }]],\n    }),\n  ],\n  build: {\n    outDir: 'javascript',\n    lib: {\n      entry: path.resolve(__dirname, 'js-src/index.js'),\n      name: 'MyLib',\n      fileName: (format) => 'my-lib.js',\n    },\n  },\n});\n```\n\n```text\nconst aWord = 'World';\nconst multiLineString = `\n  Hello ${aWord}\n`;\nconsole.log(multiLineString);\n```\n\n```text\n(function(n){typeof define==\"function\"&&define.amd?define(n):n()})(function(){\"use strict\";var n=`\n  Hello `.concat(aWord,`\n`);console.log(n)});\n```\n\n```text\n.js\n```\n\n```text\n.js\n```\n\n```text\nvar\n```\n\n```text\nconst\n```\n\n```text\n\"\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport { getBabelOutputPlugin } from '@rollup/plugin-babel'\n\nexport default defineConfig({\n  build: {\n    target: 'ie11',\n    lib: {\n      /* your vite lib mode params */\n    },\n    rollupOptions: {\n      // make sure to externalize deps that shouldn't be bundled\n      // into your library\n      external: [],\n      output: {\n        plugins: [\n          /**\n           * Running Babel on the generated code:\n           *  https://github.com/rollup/plugins/blob/master/packages/babel/README.md#running-babel-on-the-generated-code\n           *\n           * Transforming ES6+ syntax to ES5 is not supported yet, there are two ways to do:\n           *  https://github.com/evanw/esbuild/issues/1010#issuecomment-803865232\n           * We choose to run Babel on the output files after esbuild.\n           *\n           * @vitejs/plugin-legacy does not support library mode:\n           *  https://github.com/vitejs/vite/issues/1639\n           */\n          getBabelOutputPlugin({\n            allowAllFormats: true,\n            presets: [\n              [\n                '@babel/preset-env',\n                {\n                  targets: '> 0.25%, not dead, IE 11',\n                  useBuiltIns: false, // Default:false\n                  // // https://babeljs.io/docs/en/babel-preset-env#modules\n                  modules: false\n                },\n              ]\n            ]\n          }),\n        ]\n      },\n      plugins: [...]\n    }\n  }\n})\n```\n\n```text\nesbuild = false\n```\n\n```text\nbuild.minify = false\n```\n\n```text\nbuild.target = 'ie11'\n```\n\n```text\nbuild.target\n```\n\n```text\nie11\n```\n\n```text\n@vite/babel\n```\n\n```text\n@rollup/plugin-babel\n```\n\n```text\nvite.config.js\n```\n\n```text\nimport legacy from '@vitejs/plugin-legacy'\n\nexport default {\n  plugins: [\n    legacy({\n      targets: ['ie >= 11'],\n      additionalLegacyPolyfills: ['regenerator-runtime/runtime']\n    })\n  ]\n}\n```\n\n```text\nSystem.register([],(function(){\"use strict\";return{execute:function(){var e=\"\\n  Hello \".concat(\"World\",\"\\n\");console.log(e)}}}));\n```\n\n```text\nnpm i -D @vitejs/plugin-legacy\n```\n\n```text\nnpm run build\n```\n\n========================================\n\nComments:\n- I tried that but the project I am creating needs to be in vite's \"library mode\" and I got an error when trying to use plugin-legacy that it does not support library mode. github.com/vitejs/vite/issues/1639\n- I can reproduce the issue when use @rollup/plugin-babel. I haven't found the solution yet. I suggest that you can open an issue in Vite GitHub. I also find a similar issue and you can refer to it.","metadata":{"transformedAt":"2026-08-18T18:33:46.439Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":256,"estimatedTokens":1545}}600{"id":"stack-78043075","source":"stackoverflow","questionId":78043075,"title":"why jpg images can't be imported in vite for React?","tags":["javascript","reactjs","vite"],"text":"Title: why jpg images can't be imported in vite for React?\nTags: javascript, reactjs, vite\nSource: Stack Overflow\n\nQuestion:\nI wanted to import a `.jpg` file to my React file but when I wanted to do that, an error popped up, so I don't have this problem with `.png` or `.svg` files, so I was wondering why this error pops up for `.jpg` files and how should we fix that?\n\nerror:\n\n```\nFailed to parse source for import analysis because the content contains \ninvalid JS syntax. You may need to install appropriate plugins \nto handle the .JPG file format, or if it's an asset, add \"**/*.JPG\" to \n`assetsInclude` in your configuration.\n```\n\n========================================\n\nTop Answer:\nI was having a similar issue trying to build my assets. It turns out that file extensions are case sensitive, so although according to the documentation 'jpg' are part of the known asset types, if your file is named '*.JPG', it will not recognize it as a plain 'jpg' image.\n\nTL;DR: Make sure your file extensions are properly cased so Vite can interpret them correctly.\n\n========================================\n\nCode:\n```text\nFailed to parse source for import analysis because the content contains \ninvalid JS syntax. You may need         to install appropriate plugins \nto handle the .JPG file format, or if it's an asset, add \"**/*.JPG\" to       \n`assetsInclude` in your configuration.\n```\n\n```text\n.jpg\n```\n\n```text\n.png\n```\n\n```text\n.svg\n```\n\n```text\n.jpg\n```\n\n```js\nexport default defineConfig({\n  assetsInclude: ['**/*.JPG'],\n})\n```\n\n```text\n**/*.JPG\n```\n\n========================================\n\nComments:\n- The message is telling you to add the JPG format to the `assetsInclude` config, do you have a config like `defineConfig`? vitejs.dev/config/shared-options.html#assetsinclude\n- so why is this happening even from the first place?@Harrison\n- It seems to be a deliberate decision from Vite to reduce the build size, but to still allow developers to include that functionality as needed","metadata":{"transformedAt":"2026-08-18T18:33:46.439Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":65,"estimatedTokens":497}}601{"id":"stack-66414059","source":"stackoverflow","questionId":66414059,"title":"How can one use a path alias in *.vue component imports in Vite?","tags":["vue.js","vite"],"text":"Title: How can one use a path alias in *.vue component imports in Vite?\nTags: vue.js, vite\nSource: Stack Overflow\n\nQuestion:\nWhen I work with Vue single file components in Vite I can use a *baseUrl* and *path* alias in *tsconfig.json* to import *.ts files into component files. However, the same does not work with imports of *.vue files because I get a run-time error.\n\n```\n// ts files: works fine\nimport { FooModel } from \"@/models/FooModel\"\n\n// vue files: relative path works fine\nimport { FooComponent } from \"./models/FooComponent.vue\"\n\n// vue files: path alias gives a run-time error!\nimport { FooComponent } from \"@/models/FooComponent.vue\"\n```\n\nThere is a similar question on Vite.js Discord Server but it has not been answered yet.\n\nTherefore, my **main question** is: how can one get the path alias working for single file component imports in Vite?\n\nThe subquestion is who does the path resolving for *.vue files in Vite? With Vue CLI this is handled in webpack, if I am not mistaken, so in Vite it is rollup?\n\n========================================\n\nCode:\n```text\n// ts files: works fine\nimport { FooModel } from \"@/models/FooModel\"\n\n// vue files: relative path works fine\nimport { FooComponent } from \"./models/FooComponent.vue\"\n\n// vue files: path alias gives a run-time error!\nimport { FooComponent } from \"@/models/FooComponent.vue\"\n```\n\n```text\n// vite.config.js\nimport { defineConfig } from \"vite\";\nimport vue from \"@vitejs/plugin-vue\";\nimport path from \"path\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue()],\n  resolve: {\n    alias: {\n      \"@\": path.resolve(__dirname, \"./src\") // map '@' to './src' \n    },\n  },\n});\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.439Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":54,"estimatedTokens":419}}602{"id":"stack-77753947","source":"stackoverflow","questionId":77753947,"title":"Inline svg in vite build","tags":["javascript","vue.js","svg","vite"],"text":"Title: Inline svg in vite build\nTags: javascript, vue.js, svg, vite\nSource: Stack Overflow\n\nQuestion:\nUsing Vite and Vue, I want to get a single JavaScript file without generating an `assets` folder containing SVG and GIF files when I run the build (without copying the SVG code and pasting it in a Vue JS file as a placeholder).\n\nIs there is a way to do that? I have been searching for a day but I didn't find any answers. Any help is appreciated. However GIFs seem to be automatically inlined.\n\n========================================\n\nCode:\n```text\nassets\n```\n\n```js\n/* vite.config.js */\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n  build: {\n    assetsInlineLimit: Number.MAX_SAFE_INTEGER,\n  },\n});\n```\n\n```text\nbuild.assetsInlineLimit\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.439Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":30,"estimatedTokens":192}}603{"id":"stack-76602107","source":"stackoverflow","questionId":76602107,"title":"How can config Nginx properly, when base property added inside of Vite.config.js?","tags":["nginx","vuejs3","vite"],"text":"Title: How can config Nginx properly, when base property added inside of Vite.config.js?\nTags: nginx, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI am using Vue 3 and Vite as build tool. and defined the base property inside of Vite.config as follows:\n\n```\nexport default defineConfig({\n base: \"/main\",\n ///\n\n});\n```\n\nand also, my nginx config before adding base inside Vite.config is as follows:\n\n```\nserver {\n listen 8080;\n charset utf-8; \n root /usr//nginx/html;\n include /etc/nginx/mime.types;\n\n location / {\n root /usr//nginx/html;\n index index.html index.htm;\n try_files $uri $uri/ /index.html;\n }\n}\n```\n\nAll things work correctly before adding base property, but when it defined, after building , the sources of build project are not recognized and following error appears by nginx:\n`Failed to load resource: the server responded with a status of 500 (Internal Server Error)`\n\nhow can handle it and modify my nginx config?\n\n========================================\n\nCode:\n```text\nexport default defineConfig({\n  base: \"/main\",\n  ///\n\n});\n```\n\n```text\nserver {\n    listen 8080;\n    charset     utf-8;  \n    root /usr/share/nginx/html;\n    include /etc/nginx/mime.types;\n\n    location / {\n        root /usr/share/nginx/html;\n        index index.html index.htm;\n        try_files $uri $uri/ /index.html;\n    }\n}\n```\n\n```text\nFailed to load resource: the server responded with a status of 500 (Internal Server Error)\n```\n\n```text\nserver {\n    listen 8080;\n    charset     utf-8;  \n    root /usr/share/nginx/html;\n    include /etc/nginx/mime.types;\n\n      location /main {\n         alias /usr/share/nginx/html/;\n        try_files $uri $uri/ /main/index.html;\n    }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.439Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":80,"estimatedTokens":419}}604{"id":"stack-71601464","source":"stackoverflow","questionId":71601464,"title":"`Uncaught TypeError: Error resolving module specifier “.prisma/client/index-browser”","tags":["node.js","svelte","prisma","vite","sveltekit"],"text":"Title: `Uncaught TypeError: Error resolving module specifier “.prisma/client/index-browser”\nTags: node.js, svelte, prisma, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have the following error message in my browser upon using sveltekit and the command \"`npm run preview`\":\n\n`Uncaught TypeError: Error resolving module specifier “.prisma/client/index-browser”. Relative module specifiers must start with “./”, “../” or “/”.`\n\nIt references a piece of code that was compiled with \"`npm run build`\" in `localhost:3000/_app/start-b07b1607.js`:\n\n`...s-d1fb5791.js\";import\".prisma/client/index-browser\";let Be=\"\",et=\"\";function ...`\n\nI have tried reproducing this error with using older versions of Prisma, the adaptor and Svelte, switching from pnpm to npm, but nothing helps. I have a MWE repository that comes close to reproducing the error but doesn't actually reproduce it at https://github.com/wvhulle/prisma-sveltekit-bug-report.\n\nHow come the Svelte compiler emits “.prisma/client/index-browser” as a module specifier? Is this an error in Prisma, Vite or something else? The dev mode works without problem.\n\nThe question seems to be related, but is about Vue, not about Svelte.\n\nThanks!\n\n========================================\n\nTop Answer:\nYou need to copy prisma generated files as follows (`package.json`):\n\n```\n{\n \"prisma:inline\": \"cp ./node_modules/.prisma/client/*.js ./node_modules/@prisma/client\",\n \"prisma:generate\": \"prisma generate && npm run prisma:inline\"\n}\n```\n\n========================================\n\nCode:\n```text\nnpm run preview\n```\n\n```text\nUncaught TypeError: Error resolving module specifier “.prisma/client/index-browser”. Relative module specifiers must start with “./”, “../” or “/”.\n```\n\n```text\nnpm run build\n```\n\n```text\nlocalhost:3000/_app/start-b07b1607.js\n```\n\n```text\n...s-d1fb5791.js\";import\".prisma/client/index-browser\";let Be=\"\",et=\"\";function ...\n```\n\n```text\nimport { Enum } from '@prisma/client';\n```\n\n```text\n{\n  \"prisma:inline\": \"cp ./node_modules/.prisma/client/*.js ./node_modules/@prisma/client\",\n  \"prisma:generate\": \"prisma generate && npm run prisma:inline\"\n}\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- > \"It references a piece of code that was compiled\" < Your code or prisma's?\n- @ClemensTolboom I don't recognize my own code in the Svelte compiled (built) file, so I assume it is Prisma's?\n- You code exists twice `prisma-client&#47;index-browser.js:1:const prisma = require('.prisma&#47;client&#47;index-browser')` and `prisma-client&#47;scripts&#47;backup-index-browser.js:1:const prisma = require('.prisma&#47;client&#47;index-browser')` Not sure but ... you can try to change those into `require('.&#47;.prisma&#47;client&#47;index-browser')` to check it fixes it? I learned the existance of hidden dirs :-p\n- @ClemensTolboom Maybe i confused you with the repository and you thought something is wrong with the repository. It works in the repository, since I couldn't reproduce the issue. So I am not sure what you mean with the comment.\n- Your code (not the MWE) has a wrong path which you can edit to see if there's a workaround.\n- I think a better solution is: \\ `resolve: { alias: { \".prisma&#47;client&#47;index-browser\": \".&#47;node_modules&#47;.prisma&#47;client&#47;index-browser.js\" } }` \\ from github.com/prisma/prisma/issues/12504#issuecomment-128588308&zwnj;&#8203;3 \\ (if that doesnt work, maybe use `@` instead of `.`, `'.prisma&#47;client&#47;index-browser': '.&#47;node_modules&#47;@prisma&#47;client&#47;index-browser.js',`)","metadata":{"transformedAt":"2026-08-18T18:33:46.439Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":80,"estimatedTokens":887}}605{"id":"stack-76336844","source":"stackoverflow","questionId":76336844,"title":"How can I make socket.io work through proxy with react and vite using express backend?","tags":["reactjs","express","socket.io","proxy","vite"],"text":"Title: How can I make socket.io work through proxy with react and vite using express backend?\nTags: reactjs, express, socket.io, proxy, vite\nSource: Stack Overflow\n\nQuestion:\nI'm unable to get socket.io to work through proxy with react+vite (PORT 5173), express (PORT 5002).\nI'm receiving an `ERROR: server error` from my current configuration. And my backend isn't receiving any connection attempts.\n\nI want the proxy to make the socket connection using my backend. (I think I'm trying to proxy the namespace e.g. `const socket = io(\"/api\"), to change from /api to http://localhost:5002)`)\n\nHere are the relevant bits from my setup.\nMy react / client component:\n\n```\nimport { io } from 'socket.io-client';\n\nexport const socket = io('/ws', {\n autoConnect: false,\n withCredentials: true,\n});\n```\n\nMy vite.config.ts code:\n\n```\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n server: {\n host: '0.0.0.0',\n proxy: {\n '/ws': {\n target: 'http://localhost:5002',\n changeOrigin: true,\n secure: false,\n ws: true,\n rewrite: path => path.replace(/^\\/ws/, ''),\n },\n }\n },\n plugins: [react()],\n});\n```\n\nMy express server side code:\n\n```\nimport express, from 'express';\nimport { createServer } from 'http';\nimport { Server } from 'socket.io';\n\nconst app = express();\nconst httpServer = createServer(app);\n\napp.use(\n cors({\n credentials: true,\n origin: process.env.CLIENT_URL,\n })\n);\n\nconst port = 5002;\n\nconst io = new Server(httpServer, {\n cors: {\n origin: process.env.CLIENT_URL,\n credentials: true,\n },\n});\n\nio.on('connection', async (socket) => {...})\n\nhttpServer.listen(port, () => {\n console.log(`Server is listening on Port: ${port}`);\n});\n```\n\nWhenever I change the path in the vite config and react component from `'ws'` to `'socket'`, the error changes and I get an `Error: xhr poll error`. When this happens my backend receives a `GET /.io/?EIO=4&transport=polling&t=OXLHE7k 404 1.653 ms - 5`\n\nWhen I remove the proxy from vite and just use the complete url in the react component it works fine and everything functions as expected with no errors,\n\n```\nexport const socket = io('http://localhost:5002', {\n autoConnect: false,\n withCredentials: true,\n});\n```\n\nHowever I want to use the proxy now in dev, that's my goal and eventually I will use an nginx proxy in production.\n\n========================================\n\nCode:\n```text\nimport { io } from 'socket.io-client';\n\nexport const socket = io('/ws', {\n  autoConnect: false,\n  withCredentials: true,\n});\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  server: {\n    host: '0.0.0.0',\n    proxy: {\n      '/ws': {\n        target: 'http://localhost:5002',\n        changeOrigin: true,\n        secure: false,\n        ws: true,\n        rewrite: path => path.replace(/^\\/ws/, ''),\n      },\n    }\n  },\n  plugins: [react()],\n});\n```\n\n```text\nimport express, from 'express';\nimport { createServer } from 'http';\nimport { Server } from 'socket.io';\n\nconst app = express();\nconst httpServer = createServer(app);\n\napp.use(\n  cors({\n    credentials: true,\n    origin: process.env.CLIENT_URL,\n  })\n);\n\nconst port = 5002;\n\nconst io = new Server(httpServer, {\n   cors: {\n     origin: process.env.CLIENT_URL,\n     credentials: true,\n   },\n});\n\nio.on('connection', async (socket) => {...})\n\nhttpServer.listen(port, () => {\n  console.log(`Server is listening on Port: ${port}`);\n});\n```\n\n```text\nexport const socket = io('http://localhost:5002', {\n  autoConnect: false,\n  withCredentials: true,\n});\n```\n\n```text\nERROR: server error\n```\n\n```text\nconst socket = io(\"/api\"), to change from /api to http://localhost:5002)\n```\n\n```text\n'ws'\n```\n\n```text\n'socket'\n```\n\n```text\nError: xhr poll error\n```\n\n```text\nGET /.io/?EIO=4&transport=polling&t=OXLHE7k 404 1.653 ms - 5\n```\n\n```text\nexport default defineConfig({\n  server: {\n    host: '0.0.0.0',\n    proxy: {\n      '/socket.io/': {\n        target: 'http://localhost:5002',\n        changeOrigin: true,\n        secure: false,\n        ws: true,\n      },\n    }\n  },\n  plugins: [react()],\n});\n```\n\n========================================\n\nComments:\n- I get the `Error: xhr poll error` with changing the path in the vite config and react component from `ws` to any of these `so, sock, socket, or socket.io` - But anything else causes an server error and the backend doesn't receive any attempts to connect.","metadata":{"transformedAt":"2026-08-18T18:33:46.440Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":209,"estimatedTokens":1119}}606{"id":"stack-75217726","source":"stackoverflow","questionId":75217726,"title":"Can't declare interface in React, Typescript, & Vite","tags":["reactjs","typescript","frontend","vite","react-typescript"],"text":"Title: Can't declare interface in React, Typescript, & Vite\nTags: reactjs, typescript, frontend, vite, react-typescript\nSource: Stack Overflow\n\nQuestion:\nI have a project created with React, Typescript & Vite. It gives this error when I declare an interface for a component. I have included the files below that I think will be causing the issue. Let me know if you think anyother file is causing this issue.\n\n```\n[plugin:vite:esbuild] Transform failed with 1 error:\nC:/Users/Aqib/Desktop/React/New-Agrod-Frontend/src/components/ui/IconTextField.tsx:3:10: ERROR: Expected \";\" but found \"Props\"\n\nC:/Users/Aqib/Desktop/React/New-Agrod-Frontend/src/components/ui/IconTextField.tsx:4:10\n\nExpected \";\" but found \"Props\"\n1 | import RefreshRuntime from \"/@react-refresh\";let prevRefreshReg;let prevRefreshSig;if (import.meta.hot) { if (!window.__vite_plugin_react_preamble_installed__) { throw new Error( \"@vitejs/plugin-react can't detect preamble. Something is wrong. \" + \"See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201\" ); } prevRefreshReg = window.$RefreshReg$; prevRefreshSig = window.$RefreshSig$; window.$RefreshReg$ = (type, id) => { RefreshRuntime.register(type, \"C:/Users/Aqib/Desktop/React/New-Agrod-Frontend/src/components/ui/IconTextField.tsx\" + \" \" + id) }; window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;}import { BaseTextFieldProps, Box, TextField } from '@mui/material';\n2 | import { FC, ReactNode } from 'react';\n3 | interface Props extends BaseTextFieldProps {\n | ^\n4 | icon?: ReactNode | ReactNode[];\n5 | }\n\n at failureErrorWithLog (C:\\Users\\Aqib\\Desktop\\React\\New-Agrod-Frontend\\node_modules\\esbuild\\lib\\main.js:1604:15)\n at C:\\Users\\Aqib\\Desktop\\React\\New-Agrod-Frontend\\node_modules\\esbuild\\lib\\main.js:837:29\n at responseCallbacks. (C:\\Users\\Aqib\\Desktop\\React\\New-Agrod-Frontend\\node_modules\\esbuild\\lib\\main.js:701:9)\n at handleIncomingPacket (C:\\Users\\Aqib\\Desktop\\React\\New-Agrod-Frontend\\node_modules\\esbuild\\lib\\main.js:756:9)\n at Socket.readFromStdout (C:\\Users\\Aqib\\Desktop\\React\\New-Agrod-Frontend\\node_modules\\esbuild\\lib\\main.js:677:7)\n at Socket.emit (node:events:513:28)\n at addChunk (node:internal/streams/readable:324:12)\n at readableAddChunk (node:internal/streams/readable:297:9)\n at Readable.push (node:internal/streams/readable:234:10)\n at Pipe.onStreamRead (node:internal/stream_base_commons:190:23\n```\n\nCode causing the bug\n\n```\nimport { BaseTextFieldProps, Box, TextField } from '@mui/material'\nimport { FC, ReactNode } from 'react'\n\ninterface Props extends BaseTextFieldProps {\n icon?: ReactNode | ReactNode[]\n}\n\nconst IconTextField: FC = ({ icon, ...rest }) => {\n return (\n \n \n {icon}\n \n )\n}\n\nexport default IconTextField\n```\n\ntsconfig.ts\n\n```\n{\n \"compilerOptions\": {\n \"baseUrl\": \".\",\n \"target\": \"ESNext\",\n \"useDefineForClassFields\": true,\n \"lib\": [\"DOM\", \"DOM.Iterable\", \"ESNext\"],\n \"allowJs\": false,\n \"skipLibCheck\": true,\n \"esModuleInterop\": false,\n \"allowSyntheticDefaultImports\": true,\n \"strict\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Node\",\n \"resolveJsonModule\": true,\n \"isolatedModules\": true,\n \"noEmit\": true,\n \"jsx\": \"react-jsx\",\n \"paths\": {\n \"@Pages/*\": [\"./src/pages/*\"],\n \"@Layout/*\": [\"./src/layouts/*\"],\n \"@Assets/*\": [\"./src/assets/*\"],\n \"@Components/*\": [\"./src/components/*\"]\n }\n },\n \"include\": [\"src\"],\n \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\nvite.config.ts\n\n```\nimport react from '@vitejs/plugin-react'\nimport { defineConfig } from 'vite'\nimport tsconfigPaths from 'vite-tsconfig-paths'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n esbuild: {\n loader: 'jsx',\n },\n root: './',\n build: {\n outDir: './build',\n },\n optimizeDeps: {\n esbuildOptions: {\n loader: {\n '.js': 'jsx',\n '.ts': 'tsx',\n },\n },\n },\n plugins: [react(), tsconfigPaths()],\n})\n```\n\nI tried searching for this bug but couldn't find anything.\n\n========================================\n\nCode:\n```text\n[plugin:vite:esbuild] Transform failed with 1 error:\nC:/Users/Aqib/Desktop/React/New-Agrod-Frontend/src/components/ui/IconTextField.tsx:3:10: ERROR: Expected \";\" but found \"Props\"\n\nC:/Users/Aqib/Desktop/React/New-Agrod-Frontend/src/components/ui/IconTextField.tsx:4:10\n\nExpected \";\" but found \"Props\"\n1  |  import RefreshRuntime from \"/@react-refresh\";let prevRefreshReg;let prevRefreshSig;if (import.meta.hot) {  if (!window.__vite_plugin_react_preamble_installed__) {    throw new Error(      \"@vitejs/plugin-react can't detect preamble. Something is wrong. \" +      \"See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201\"    );  }  prevRefreshReg = window.$RefreshReg$;  prevRefreshSig = window.$RefreshSig$;  window.$RefreshReg$ = (type, id) => {    RefreshRuntime.register(type, \"C:/Users/Aqib/Desktop/React/New-Agrod-Frontend/src/components/ui/IconTextField.tsx\" + \" \" + id)  };  window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;}import { BaseTextFieldProps, Box, TextField } from '@mui/material';\n2  |  import { FC, ReactNode } from 'react';\n3  |  interface Props extends BaseTextFieldProps {\n   |            ^\n4  |    icon?: ReactNode | ReactNode[];\n5  |  }\n\n    at failureErrorWithLog (C:\\Users\\Aqib\\Desktop\\React\\New-Agrod-Frontend\\node_modules\\esbuild\\lib\\main.js:1604:15)\n    at C:\\Users\\Aqib\\Desktop\\React\\New-Agrod-Frontend\\node_modules\\esbuild\\lib\\main.js:837:29\n    at responseCallbacks.<computed> (C:\\Users\\Aqib\\Desktop\\React\\New-Agrod-Frontend\\node_modules\\esbuild\\lib\\main.js:701:9)\n    at handleIncomingPacket (C:\\Users\\Aqib\\Desktop\\React\\New-Agrod-Frontend\\node_modules\\esbuild\\lib\\main.js:756:9)\n    at Socket.readFromStdout (C:\\Users\\Aqib\\Desktop\\React\\New-Agrod-Frontend\\node_modules\\esbuild\\lib\\main.js:677:7)\n    at Socket.emit (node:events:513:28)\n    at addChunk (node:internal/streams/readable:324:12)\n    at readableAddChunk (node:internal/streams/readable:297:9)\n    at Readable.push (node:internal/streams/readable:234:10)\n    at Pipe.onStreamRead (node:internal/stream_base_commons:190:23\n```\n\n```text\nimport { BaseTextFieldProps, Box, TextField } from '@mui/material'\nimport { FC, ReactNode } from 'react'\n\ninterface Props extends BaseTextFieldProps {\n  icon?: ReactNode | ReactNode[]\n}\n\nconst IconTextField: FC<Props> = ({ icon, ...rest }) => {\n  return (\n    <Box sx={{ position: 'relative' }}>\n      <TextField\n        {...rest}\n        variant='outlined'\n        size='small'\n        InputProps={{\n          style: {\n            backgroundColor: 'white',\n            outline: 'none',\n            borderRadius: 10,\n          },\n        }}\n        fullWidth\n      />\n      <Box sx={{ position: 'absolute', top: 10, left: -30 }}>{icon}</Box>\n    </Box>\n  )\n}\n\nexport default IconTextField\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"target\": \"ESNext\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"DOM\", \"DOM.Iterable\", \"ESNext\"],\n    \"allowJs\": false,\n    \"skipLibCheck\": true,\n    \"esModuleInterop\": false,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\",\n    \"paths\": {\n      \"@Pages/*\": [\"./src/pages/*\"],\n      \"@Layout/*\": [\"./src/layouts/*\"],\n      \"@Assets/*\": [\"./src/assets/*\"],\n      \"@Components/*\": [\"./src/components/*\"]\n    }\n  },\n  \"include\": [\"src\"],\n  \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\n```text\nimport react from '@vitejs/plugin-react'\nimport { defineConfig } from 'vite'\nimport tsconfigPaths from 'vite-tsconfig-paths'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  esbuild: {\n    loader: 'jsx',\n  },\n  root: './',\n  build: {\n    outDir: './build',\n  },\n  optimizeDeps: {\n    esbuildOptions: {\n      loader: {\n        '.js': 'jsx',\n        '.ts': 'tsx',\n      },\n    },\n  },\n  plugins: [react(), tsconfigPaths()],\n})\n```\n\n```text\nimport react from '@vitejs/plugin-react';\nimport { defineConfig } from 'vite';\nimport tsconfigPaths from 'vite-tsconfig-paths';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n    esbuild: {\n        loader: 'tsx',\n    },\n    root: './',\n    build: {\n        outDir: './build',\n    },\n    optimizeDeps: {\n        esbuildOptions: {\n            loader: {\n                '.js': 'jsx',\n                '.ts': 'tsx',\n            },\n        },\n    },\n    plugins: [react(), tsconfigPaths()],\n});\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.440Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":261,"estimatedTokens":2122}}607{"id":"stack-75688953","source":"stackoverflow","questionId":75688953,"title":"Laravel: use Vite::asset() in SCSS file?","tags":["css","laravel","sass","vite","laravel-10"],"text":"Title: Laravel: use Vite::asset() in SCSS file?\nTags: css, laravel, sass, vite, laravel-10\nSource: Stack Overflow\n\nQuestion:\nI'm new to Laravel 10 and Vite.\n\nIn my Blade templates, I use:\n\n```\n\n```\n\nI can't figure out how to use Vite::asset() in a SASS file, as for example:\n\n```\nbackground-image: url('{{ Vite::asset(\"resources/img/image.jpg\") }}');\n```\n\nIs this possible? How to proceed?\n\nThanks!\n\n========================================\n\nCode:\n```html\n<img src=\"{{ Vite::asset('resources/img/image.jpg') }}\" class=\"card-img\" alt=\"\">\n```\n\n```css\nbackground-image: url('{{ Vite::asset(\"resources/img/image.jpg\") }}');\n```\n\n```css\nbackground-image: url(\"resources/img/image.jpg\");\n```\n\n```text\nIntroduction to Vite\n```\n\n========================================\n\nComments:\n- I just see I need to write `background-image: url(\"&#47;resources&#47;img&#47;image.jpg\");` with a heading slash\n- That is possible, I did not have the pleasure to use it, you could also use relative path (`..&#47;`) and it should work too","metadata":{"transformedAt":"2026-08-18T18:33:46.440Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":47,"estimatedTokens":254}}608{"id":"stack-70338657","source":"stackoverflow","questionId":70338657,"title":"npm run build error with vite (typescript)","tags":["reactjs","react-router","react-router-dom","vite"],"text":"Title: npm run build error with vite (typescript)\nTags: reactjs, react-router, react-router-dom, vite\nSource: Stack Overflow\n\nQuestion:\n**error**\n\n```\nnode_modules/@types/react-router-dom/index.d.ts:13:10 - error TS2305: Module '\"react-router\"' has no exported member 'match'.\nnode_modules/@types/react-router-dom/index.d.ts:19:5 - error TS2305: Module '\"react-router\"' has no exported member 'PromptProps'.\nnode_modules/@types/react-router-dom/index.d.ts:20:5 - error TS2305: Module '\"react-router\"' has no exported member 'Prompt'.\nnode_modules/@types/react-router-dom/index.d.ts:23:5 - error TS2305: Module '\"react-router\"' has no exported member 'RedirectProps'.\nnode_modules/@types/react-router-dom/index.d.ts:24:5 - error TS2305: Module '\"react-router\"' has no exported member 'Redirect'.\nnode_modules/@types/react-router-dom/index.d.ts:25:5 - error TS2305: Module '\"react-router\"' has no exported member 'RouteChildrenProps'.\nnode_modules/@types/react-router-dom/index.d.ts:26:5 - error TS2305: Module '\"react-router\"' has no exported member 'RouteComponentProps'.\nnode_modules/@types/react-router-dom/index.d.ts:31:5 - error TS2305: Module '\"react-router\"' has no exported member 'StaticRouterProps'.\nnode_modules/@types/react-router-dom/index.d.ts:32:5 - error TS2305: Module '\"react-router\"' has no exported member 'StaticRouter\nnode_modules/@types/react-router-dom/index.d.ts:33:5 - error TS2305: Module '\"react-router\"' has no exported member 'SwitchProps'.\nnode_modules/@types/react-router-dom/index.d.ts:34:5 - error TS2305: Module '\"react-router\"' has no exported member 'Switch'.\nnode_modules/@types/react-router-dom/index.d.ts:35:5 - error TS2305: Module '\"react-router\"' has no exported member 'match'.\n... same errors but different members\n\nnode_modules/@types/react-router/index.d.ts:189:53 - error TS2694: Namespace '\"C:/Users/user/Desktop/app/frontend/node_modules/history/index\"' has no exported member 'LocationState'.\n189 export function useHistory(): H.History;\nnode_modules/@types/react-router/index.d.ts:189:71 - error TS2315: Type 'History' is not generic.\n189 export function useHistory(): H.History; \nnode_modules/@types/react-router/index.d.ts:191:35 - error TS2694: Namespace '\"C:/Users/user/Desktop/app/frontend/node_modules/history/index\"' has no exported member 'LocationState'.\n191 export function useLocation(): H.Location; \nnode_modules/@types/react-router/index.d.ts:191:53 - error TS2315: Type 'Location' is not generic.\n191 export function useLocation(): H.Location;\n... again more errors\n```\n\n**package.json**\n\n```\n{\n \"name\": \"frontend\",\n \"version\": \"0.0.0\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"tsc && vite build\",\n \"preview\": \"vite preview\"\n },\n \"dependencies\": {\n \"@reduxjs/toolkit\": \"^1.7.0\",\n \"@types/react-redux\": \"^7.1.20\",\n \"@types/react-router-dom\": \"^5.3.2\",\n \"axios\": \"^0.24.0\",\n \"react\": \"^17.0.2\",\n \"react-dom\": \"^17.0.2\",\n \"react-redux\": \"^7.2.6\",\n \"react-router-dom\": \"^6.1.0\"\n },\n \"devDependencies\": {\n \"@types/react\": \"^17.0.33\",\n \"@types/react-dom\": \"^17.0.10\",\n \"@vitejs/plugin-react\": \"^1.0.7\",\n \"typescript\": \"^4.4.4\",\n \"vite\": \"^2.7.0\"\n }\n}\n```\n\nWhenever I try to build, it shows me all of these errors which i have never encountered before so no idea why this is happening..., the first part has to do with ts so that's fixable but the 2nd part doesn't make sense, any help is appreciated!\n\n========================================\n\nTop Answer:\nMaybe you can try add `\"skipLibCheck\": true` to tsconfig.json.\n\n```\n{\n \"compilerOptions\": {\n // ...\n \"skipLibCheck\": true\n }\n}\n```\n\n========================================\n\nCode:\n```text\nnode_modules/@types/react-router-dom/index.d.ts:13:10 - error TS2305: Module '\"react-router\"' has no exported member 'match'.\nnode_modules/@types/react-router-dom/index.d.ts:19:5 - error TS2305: Module '\"react-router\"' has no exported member 'PromptProps'.\nnode_modules/@types/react-router-dom/index.d.ts:20:5 - error TS2305: Module '\"react-router\"' has no exported member 'Prompt'.\nnode_modules/@types/react-router-dom/index.d.ts:23:5 - error TS2305: Module '\"react-router\"' has no exported member 'RedirectProps'.\nnode_modules/@types/react-router-dom/index.d.ts:24:5 - error TS2305: Module '\"react-router\"' has no exported member 'Redirect'.\nnode_modules/@types/react-router-dom/index.d.ts:25:5 - error TS2305: Module '\"react-router\"' has no exported member 'RouteChildrenProps'.\nnode_modules/@types/react-router-dom/index.d.ts:26:5 - error TS2305: Module '\"react-router\"' has no exported member 'RouteComponentProps'.\nnode_modules/@types/react-router-dom/index.d.ts:31:5 - error TS2305: Module '\"react-router\"' has no exported member 'StaticRouterProps'.\nnode_modules/@types/react-router-dom/index.d.ts:32:5 - error TS2305: Module '\"react-router\"' has no exported member 'StaticRouter\nnode_modules/@types/react-router-dom/index.d.ts:33:5 - error TS2305: Module '\"react-router\"' has no exported member 'SwitchProps'.\nnode_modules/@types/react-router-dom/index.d.ts:34:5 - error TS2305: Module '\"react-router\"' has no exported member 'Switch'.\nnode_modules/@types/react-router-dom/index.d.ts:35:5 - error TS2305: Module '\"react-router\"' has no exported member 'match'.\n... same errors but different members\n\nnode_modules/@types/react-router/index.d.ts:189:53 - error TS2694: Namespace '\"C:/Users/user/Desktop/app/frontend/node_modules/history/index\"' has no exported member 'LocationState'.\n189 export function useHistory<HistoryLocationState = H.LocationState>(): H.History<HistoryLocationState>;\nnode_modules/@types/react-router/index.d.ts:189:71 - error TS2315: Type 'History' is not generic.\n189 export function useHistory<HistoryLocationState = H.LocationState>(): H.History<HistoryLocationState>;                     \nnode_modules/@types/react-router/index.d.ts:191:35 - error TS2694: Namespace '\"C:/Users/user/Desktop/app/frontend/node_modules/history/index\"' has no exported member 'LocationState'.\n191 export function useLocation<S = H.LocationState>(): H.Location<S>;                                   \nnode_modules/@types/react-router/index.d.ts:191:53 - error TS2315: Type 'Location' is not generic.\n191 export function useLocation<S = H.LocationState>(): H.Location<S>;\n... again more errors\n```\n\n```text\n{\n  \"name\": \"frontend\",\n  \"version\": \"0.0.0\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"tsc && vite build\",\n    \"preview\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"^1.7.0\",\n    \"@types/react-redux\": \"^7.1.20\",\n    \"@types/react-router-dom\": \"^5.3.2\",\n    \"axios\": \"^0.24.0\",\n    \"react\": \"^17.0.2\",\n    \"react-dom\": \"^17.0.2\",\n    \"react-redux\": \"^7.2.6\",\n    \"react-router-dom\": \"^6.1.0\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^17.0.33\",\n    \"@types/react-dom\": \"^17.0.10\",\n    \"@vitejs/plugin-react\": \"^1.0.7\",\n    \"typescript\": \"^4.4.4\",\n    \"vite\": \"^2.7.0\"\n  }\n}\n```\n\n```text\n@types/react-router-dom\n```\n\n```text\nType definitions for react-router-dom 5.3\n```\n\n```text\n{\n  \"compilerOptions\": {\n    // ...\n    \"skipLibCheck\": true\n  }\n}\n```\n\n```text\n\"skipLibCheck\": true\n```\n\n```text\nnpm update typescript -g \n or\nnpm install typescript@latest -g\n```\n\n========================================\n\nComments:\n- Looks like you've accidentally upgraded to `react-router-dom` v6.... none of those items being complained about exist in v6, they were removed. Either revert back to v5 or the upgrade from v5 guide.\n- The same issue i upgraded to v6 - but types non exist","metadata":{"transformedAt":"2026-08-18T18:33:46.440Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":170,"estimatedTokens":1857}}609{"id":"stack-76259677","source":"stackoverflow","questionId":76259677,"title":"Vite Dev Server throws error when resolving external path from importmap","tags":["vuejs3","vite"],"text":"Title: Vite Dev Server throws error when resolving external path from importmap\nTags: vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\n### Environment\n\n- Chrome: 113.0.5672.92\n\n- Vite: 4.3.6\n\n### Reproducing Environment\n\nhttps://github.com/UedaTakeyuki/MyVue3Scaffold2\n\n### What is happen\n\nIn my Vue3 application, I tried to use libraries from CDN with following **importmap** script in the index.html file:\n\n```\n\n \n \n \n \n Vite App\n \n \n {\n \"imports\": {\n \"vue\": \"https://cdn.jsdelivr.net/npm/vue@3/dist/vue.esm-browser.prod.js\",\n \"vuetify\": \"https://cdn.jsdelivr.net/npm/vuetify@3.1.14/dist/vuetify.esm.js\",\n \"vue-router\": \"https://cdn.jsdelivr.net/npm/vue-router@4/dist/vue-router.esm-browser.js\",\n \"@vue/devtools-api\": \"https://cdn.jsdelivr.net/npm/@vue/devtools-api@6/lib/esm/index.js\"\n }\n }\n \n \n \n \n \n \n \n\n```\n\nAnd set vuetify as **external** at the vite.config.ts file:\n\n```\nbuild: {\n rollupOptions: {\n external: [\n 'vue',\n 'vuetify',\n 'vue-router',\n ],\n```\n\nThen import **vuetify** at main.js as follows:\n\n```\nimport { createApp } from 'vue'\nimport App from './App.vue'\nimport Home from '/src/views/Home.vue'\nimport About from '/src/views/About.vue'\nimport { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'\nimport { createVuetify } from 'vuetify'\n```\n\nThen, run LocalServer and brows it, the error `Failed to resolve import \"vuetify\" from \"src/main.js\".` occurred.\n\nhttps://i.sstatic.net/AGUJx.png\n\n### Question\n\nFirst of all, Does vite support the **importmap** by design? Or are there any wrong or mistaken steps in my App? I'm totally confused, any suggestions are welcome.\n\n========================================\n\nCode:\n```text\n<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\">\n    <link rel=\"icon\" href=\"/favicon.ico\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <title>Vite App</title>\n    <!-- https://stackoverflow.com/a/62282239/11073131 -->\n    <script type=\"importmap\">\n      {\n        \"imports\": {\n          \"vue\": \"https://cdn.jsdelivr.net/npm/vue@3/dist/vue.esm-browser.prod.js\",\n          \"vuetify\": \"https://cdn.jsdelivr.net/npm/vuetify@3.1.14/dist/vuetify.esm.js\",\n          \"vue-router\": \"https://cdn.jsdelivr.net/npm/vue-router@4/dist/vue-router.esm-browser.js\",\n          \"@vue/devtools-api\": \"https://cdn.jsdelivr.net/npm/@vue/devtools-api@6/lib/esm/index.js\"\n        }\n      }\n    </script>\n    <link href=\"https://cdn.jsdelivr.net/npm/vuetify@3.1.14/dist/vuetify.min.css\" rel=\"stylesheet\">\n  </head>\n  <body>\n    <div id=\"app\"></div>\n    <script type=\"module\" src=\"/src/main.js\"></script>\n  </body>\n</html>\n```\n\n```text\nbuild: {\n    rollupOptions: {\n      external: [\n        'vue',\n        'vuetify',\n        'vue-router',\n      ],\n```\n\n```text\nimport { createApp } from 'vue'\nimport App from './App.vue'\nimport Home from '/src/views/Home.vue'\nimport About from '/src/views/About.vue'\nimport { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'\nimport { createVuetify } from 'vuetify'\n```\n\n```text\nFailed to resolve import \"vuetify\" from \"src/main.js\".\n```\n\n```text\nfunction viteIgnoreStaticImport(importKeys) {\n  return {\n    name: \"vite-plugin-ignore-static-import\",\n    enforce: \"pre\",\n    // 1. insert to optimizeDeps.exclude to prevent pre-transform\n    config(config) {\n      config.optimizeDeps = {\n        ...(config.optimizeDeps ?? {}),\n        exclude: [...(config.optimizeDeps?.exclude ?? []), ...importKeys],\n      };\n    },\n    // 2. push a plugin to rewrite the 'vite:import-analysis' prefix\n    configResolved(resolvedConfig) {\n      const VALID_ID_PREFIX = `/@id/`;\n      const reg = new RegExp(\n        `${VALID_ID_PREFIX}(${importKeys.join(\"|\")})`,\n        \"g\"\n      );\n      resolvedConfig.plugins.push({\n        name: \"vite-plugin-ignore-static-import-replace-idprefix\",\n        transform: (code) =>\n          reg.test(code) ? code.replace(reg, (m, s1) => s1) : code,\n      });\n    },\n    // 3. rewrite the id before 'vite:resolve' plugin transform to 'node_modules/...'\n    resolveId: (id) => {\n      if (importKeys.includes(id)) {\n        return { id, external: true };\n      }\n    },\n  };\n}\n```\n\n```text\nexport default defineConfig({\n  plugins: [\n     vue(),\n     viteIgnoreStaticImport([\"vuetify\"]) // <---- pass in the modules you want to ignore\n  ],\n  ...\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.440Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":174,"estimatedTokens":1079}}610{"id":"stack-74635060","source":"stackoverflow","questionId":74635060,"title":"Vite creating its own node_modules in workspace instead of using monorepo","tags":["javascript","npm","vite","monorepo","react-fullstack"],"text":"Title: Vite creating its own node_modules in workspace instead of using monorepo\nTags: javascript, npm, vite, monorepo, react-fullstack\nSource: Stack Overflow\n\nQuestion:\nI have a monorepo for a fullstack webapp with the following directory structure\n\n```\n.\n├── client\n│ ├── index.html\n│ ├── package.json\n│ ├── src\n│ └── vite.config.ts\n├── node_modules\n├── package-lock.json\n├── package.json\n├── server\n│ ├── package.json\n│ └── src\n├── tsconfig.json\n└── tsconfig.node.json\n```\n\nHowever, when I run `npm run dev -ws client`, vite generates it's own `node_modules/` inside `client/`.\n\n```\n.\n├── client\n│ ├── index.html\n│ ├── node_modules My understanding is that the point of using npm workspaces is to avoid having multiple `node_modules/` in each sub-project, instead having all dependencies installed in the root `node_modules/`. Vite generating its own seems to defeat that point.\n\nI'm assuming I don't have something configured properly (I used `npx create-vite` to setup vite).\n\nOutput of `npm run dev -ws client`\n\n```\n> @sargon-dashboard/client@0.0.0 dev\n> vite client\n\n(!) Could not auto-determine entry point from rollupOptions or html files and there are no explicit optimizeDeps.include patterns. Skipping dependency pre-bundling.\n\n VITE v3.2.4 ready in 175 ms\n\n ➜ Local: http://localhost:5173/\n ➜ Network: use --host to expose\n```\n\nContents of `vite.config.ts`\n\n```\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()]\n})\n```\n\ncontents of `root/package.json`\n\n```\n{\n \"name\": \"app\",\n \"private\": true,\n \"workspaces\": [\n \"client\",\n \"server\"\n ]\n}\n```\n\ncontents of `root/client/package.json`\n\n```\n{\n \"name\": \"@app/client\",\n \"private\": true,\n \"version\": \"0.0.0\",\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"tsc && vite build\",\n \"preview\": \"vite preview\"\n },\n \"dependencies\": {\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\"\n },\n \"devDependencies\": {\n \"@types/react\": \"^18.0.24\",\n \"@types/react-dom\": \"^18.0.8\",\n \"@vitejs/plugin-react\": \"^2.2.0\",\n \"typescript\": \"^4.6.4\",\n \"vite\": \"^3.2.3\"\n }\n}\n```\n\ncontents of `root/server/package.json`\n\n```\n{\n \"name\": \"@app/server\",\n \"version\": \"0.0.0\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"keywords\": [],\n \"author\": \"\",\n \"license\": \"ISC\"\n}\n```\n\n========================================\n\nCode:\n```text\n.\n├── client\n│   ├── index.html\n│   ├── package.json\n│   ├── src\n│   └── vite.config.ts\n├── node_modules\n├── package-lock.json\n├── package.json\n├── server\n│   ├── package.json\n│   └── src\n├── tsconfig.json\n└── tsconfig.node.json\n```\n\n```text\n.\n├── client\n│   ├── index.html\n│   ├── node_modules <--- this\n│   │   └── .vite\n│   │       └── deps_temp\n│   │           └── package.json\n│   ├── package.json\n│   ├── src\n│   └── vite.config.ts\n```\n\n```text\n> @sargon-dashboard/client@0.0.0 dev\n> vite client\n\n(!) Could not auto-determine entry point from rollupOptions or html files and there are no explicit optimizeDeps.include patterns. Skipping dependency pre-bundling.\n\n  VITE v3.2.4  ready in 175 ms\n\n  ➜  Local:   http://localhost:5173/\n  ➜  Network: use --host to expose\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()]\n})\n```\n\n```json\n{\n    \"name\": \"app\",\n    \"private\": true,\n    \"workspaces\": [\n        \"client\",\n        \"server\"\n    ]\n}\n```\n\n```json\n{\n  \"name\": \"@app/client\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"tsc && vite build\",\n    \"preview\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^18.0.24\",\n    \"@types/react-dom\": \"^18.0.8\",\n    \"@vitejs/plugin-react\": \"^2.2.0\",\n    \"typescript\": \"^4.6.4\",\n    \"vite\": \"^3.2.3\"\n  }\n}\n```\n\n```json\n{\n  \"name\": \"@app/server\",\n  \"version\": \"0.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"keywords\": [],\n  \"author\": \"\",\n  \"license\": \"ISC\"\n}\n```\n\n```text\nnpm run dev -ws client\n```\n\n```text\nnode_modules/\n```\n\n```text\nclient/\n```\n\n```text\nnode_modules/\n```\n\n```text\nnode_modules/\n```\n\n```text\nnpx create-vite\n```\n\n```text\nnpm run dev -ws client\n```\n\n```text\nvite.config.ts\n```\n\n```text\nroot/package.json\n```\n\n```text\nroot/client/package.json\n```\n\n```text\nroot/server/package.json\n```\n\n```text\nnode_modules/.vite\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.440Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":270,"estimatedTokens":1145}}611{"id":"stack-72530354","source":"stackoverflow","questionId":72530354,"title":"Unable to load stencil components lib with Vue3 using Vite","tags":["vue.js","vuejs3","vite","stenciljs"],"text":"Title: Unable to load stencil components lib with Vue3 using Vite\nTags: vue.js, vuejs3, vite, stenciljs\nSource: Stack Overflow\n\nQuestion:\nI created a sample project to reproduce this issue: https://github.com/splanard/vue3-vite-web-components\n\nI initialized a vue3 project using `npm init vue@latest`, as recommanded in the official documentation.\n\nThen I installed Scale, a stencil-built web components library. (*I have the exact same issue with the internal design system of my company, so I searched for public stencil-built libraries to reproduce the issue.*)\n\nI configured the following in **`main.ts`**:\n\n```\nimport '@telekom/scale-components-neutral/dist/scale-components/scale-components.css';\nimport { applyPolyfills, defineCustomElements } from '@telekom/scale-components-neutral/loader';\n\nconst app = createApp(App);\napp.config.compilerOptions.isCustomElement = (tag) => tag.startsWith('scale-')\n\napplyPolyfills().then(() => {\n defineCustomElements(window);\n});\n```\n\nAnd the same `isCustomElement` function in **`vite.config.js`**:\n\n```\nexport default defineConfig({\n plugins: [vue({\n template: {\n compilerOptions: {\n isCustomElement: (tag) => tag.startsWith('scale-')\n }\n }\n })]\n // ...\n})\n```\n\nI inserted a simple button in my view (`TestView.vue`), then run `npm run dev`.\n\nWhen opening my test page (`/test`) containing the web component, I have an error in my web browser's console:\n\n```\nfailed to load module \"http://localhost:3000/node_modules/.vite/deps/scale-button_14.entry.js?import\" because of disallowed MIME type \" \"\n```\n\n***As it's the case with both Scale and my company's design system, I'm pretty sure it's reproducible with any stencil-based components library.***\n\n**Edit**\n\nIt appears that `node_modules/.vite` is the directory where Vite's dependency pre-bundling feature caches things. And the script `scale-button_14.entry.js` the browser fails to load doesn't exist at all in `node_modules/.vite/deps`. So the issue might be linked to this \"dependency pre-bundling\" feature: somehow, could it not detect the components from the library loader?\n\n**Edit 2**\n\nI just found out there is an issue in Stencil repository mentioning that dynamic imports do not work with modern built tools like Vite. This issue has been closed 7 days ago (lucky me!), and version 2.16.0 of Stencil is supposed to fix this. We shall see.\n\nFor the time being, dropping the lazy loading and loading all the components at once through a plain old `script` tag in the HTML template seems to be an ***acceptable workaround***.\n\n```\n\n```\n\nHowever, I can't get vite pre-bundling feature to ignore these imports. I configured `optimizeDeps.exclude` in `vite.config.js` but I still get massive warnings from vite when I run `npm run dev`:\n\n```\nexport default defineConfig({\n optimizeDeps: {\n exclude: [\n // I tried pretty much everything here: no way to force vite pre-bundling to ignore it...\n 'scale-components-neutral'\n '@telekom/scale-components-neutral'\n '@telekom/scale-components-neutral/**/*'\n '@telekom/scale-components-neutral/**/*.js'\n 'node_modules/@telekom/scale-components-neutral/**/*.js'\n ],\n },\n // ...\n});\n```\n\n========================================\n\nTop Answer:\nI did not configure main.ts\n\nstencil.js version is 2.12.1,tsconfig.json add new config option in stencil:\n\n```\n{\n \"compilerOptions\": {\n ...\n \"skipLibCheck\": true,\n ...\n }\n}\n```\n\nadd new config option in webpack.config.js :\nvue 3 document\n\n```\n...\nmodule: {\n rules:[\n ...\n {\n test: /\\.vue$/,\n use: {\n loader: \"vue-loader\",\n options: {\n compilerOptions: {\n isCustomElement: tag => tag.includes(\"-\")\n }\n }\n }\n }\n ...\n ]\n}\n...\n```\n\n========================================\n\nCode:\n```js\nimport '@telekom/scale-components-neutral/dist/scale-components/scale-components.css';\nimport { applyPolyfills, defineCustomElements } from '@telekom/scale-components-neutral/loader';\n\nconst app = createApp(App);\napp.config.compilerOptions.isCustomElement = (tag) => tag.startsWith('scale-')\n\napplyPolyfills().then(() => {\n  defineCustomElements(window);\n});\n```\n\n```js\nexport default defineConfig({\n  plugins: [vue({\n    template: {\n      compilerOptions: {\n        isCustomElement: (tag) => tag.startsWith('scale-')\n      }\n    }\n  })]\n  // ...\n})\n```\n\n```text\nfailed to load module \"http://localhost:3000/node_modules/.vite/deps/scale-button_14.entry.js?import\" because of disallowed MIME type \" \"\n```\n\n```html\n<link rel=\"stylesheet\" href=\"node_modules/@telekom/scale-components/dist/scale-components/scale-components.css\">\n<script type=\"module\" src=\"node_modules/@telekom/scale-components/dist/scale-components/scale-components.esm.js\"></script>\n```\n\n```js\nexport default defineConfig({\n  optimizeDeps: {\n    exclude: [\n      // I tried pretty much everything here: no way to force vite pre-bundling to ignore it...\n      'scale-components-neutral'\n      '@telekom/scale-components-neutral'\n      '@telekom/scale-components-neutral/**/*'\n      '@telekom/scale-components-neutral/**/*.js'\n      'node_modules/@telekom/scale-components-neutral/**/*.js'\n    ],\n  },\n  // ...\n});\n```\n\n```text\nnpm init vue@latest\n```\n\n```text\nmain.ts\n```\n\n```text\nisCustomElement\n```\n\n```text\nvite.config.js\n```\n\n```text\nTestView.vue\n```\n\n```text\nnpm run dev\n```\n\n```text\n/test\n```\n\n```text\nnode_modules/.vite\n```\n\n```text\nscale-button_14.entry.js\n```\n\n```text\nnode_modules/.vite/deps\n```\n\n```text\nscript\n```\n\n```text\noptimizeDeps.exclude\n```\n\n```text\nvite.config.js\n```\n\n```text\nnpm run dev\n```\n\n```js\nimport '@telekom/scale-components-neutral/dist/scale-components/scale-components.css';\nimport { applyPolyfills, defineCustomElements } from '@telekom/scale-components-neutral/loader';\n\nconst app = createApp(App);\n\napplyPolyfills().then(() => {\n  defineCustomElements(window);\n});\n```\n\n```js\nexport default defineConfig({\n  plugins: [vue({\n    template: {\n      compilerOptions: {\n        isCustomElement: (tag) => tag.startsWith('scale-')\n      }\n    }\n  })]\n  // ...\n})\n```\n\n```text\nexperimentalImportInjection\n```\n\n```js\n{\n  \"compilerOptions\": {\n    ...\n    \"skipLibCheck\": true,\n    ...\n  }\n}\n```\n\n```js\n...\nmodule: {\n  rules:[\n    ...\n    {\n      test: /\\.vue$/,\n      use: {\n        loader: \"vue-loader\",\n        options: {\n          compilerOptions: {\n            isCustomElement: tag => tag.includes(\"-\")\n          }\n        }\n      }\n    }\n    ...\n  ]\n}\n...\n```\n\n========================================\n\nComments:\n- I tested your project on stackblitz. Seem like the error has gone\n- I don't know how stackblitz works but the error is still very much present.","metadata":{"transformedAt":"2026-08-18T18:33:46.441Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":298,"estimatedTokens":1631}}612{"id":"stack-74331668","source":"stackoverflow","questionId":74331668,"title":"How to package a Vue Single File component with Vite to load it via HTTPS?","tags":["vue.js","vite","vue-cli","vue-sfc"],"text":"Title: How to package a Vue Single File component with Vite to load it via HTTPS?\nTags: vue.js, vite, vue-cli, vue-sfc\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a compiled an packaged version of my Vue Single File component to distribute and dynamically load it via HTTP.\n\nI found this article from Markus Oberlehner that uses Vue CLI v3 with the following command:\n\n```\nnpx vue-cli-service build --target lib --formats umd-min --no-clean --dest server/components/MyComponent --name \"MyComponent.[chunkhash]\" server/components/MyComponent/MyComponent.vue\n```\n\nIt seems to work fine, however, I would like to use Vite instead. Is that possible? Which is the equivalent command?\n\n========================================\n\nCode:\n```text\nnpx vue-cli-service build --target lib --formats umd-min --no-clean --dest server/components/MyComponent --name \"MyComponent.[chunkhash]\" server/components/MyComponent/MyComponent.vue\n```\n\n========================================\n\nComments:\n- Hey! Author of the original article here. I recommend you look into Module Federation (webpack.js.org/concepts/module-federation). When I wrote the original article, it did not exist yet. Nowadays, I'd 100% go for Module Federation instead of rolling my own. There is also a Vite plugin for it: github.com/originjs/vite-plugin-federation\n- Didn't get it initially but we're talking about micro-frontends here. I have written an answer on that subject too: stackoverflow.com/q/69000161/8816585 (with some details on how to do that well)","metadata":{"transformedAt":"2026-08-18T18:33:46.441Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":27,"estimatedTokens":382}}613{"id":"stack-77218109","source":"stackoverflow","questionId":77218109,"title":"Vite + React + Flask not proxying frontend to backend","tags":["reactjs","http","flask","proxy","vite"],"text":"Title: Vite + React + Flask not proxying frontend to backend\nTags: reactjs, http, flask, proxy, vite\nSource: Stack Overflow\n\nQuestion:\nI am trying to set a proxy in my frontend so that I can fetch() apis from my backend.\n\nHere is my setup:\n\nvite.config.ts:\n\n```\nserver: {\n proxy: { \"/api\": {\n target: 'http://localhost:3001',\n changeOrigin: true,\n secure: false \n }\n }\n },\n```\n\nfrontend.tsx:\n\n```\nconst Test: React.FC = () => {\n\n useEffect(()=>{\n fetch(`api/hello`)\n .then(res => console.log(res))\n }, [])\n return(\n \n hi\n \n )\n}\n```\n\nBackend:\n\n```\n@app.route('/api/hello', methods=['GET'])\ndef test():\n return jsonify({\"hi\":\"there\"})\n```\n\n**I get the error**:\n`GET http://localhost:5173/api/hello net::ERR_ABORTED 500 (Internal Server Error)`\n\nIt is using port 5173 for the fetch() and not 3001 which is what my server is listening on.\n\nI have tried solutions such as:\nHow to configure proxy in Vite?\nand it does not work.\n\nI added some event listeners to the vite.config.ts file as follows:\n\n```\nproxy: { \"/api\": {\n target: 'http://localhost:3001',\n changeOrigin: true,\n secure: false,\n configure: (proxy, _options) => {\n proxy.on('error', (err, _req, _res) => {\n console.log('proxy error', err);\n });\n proxy.on('proxyReq', (proxyReq, req, _res) => {\n console.log('Sending Request to the Target:', req.method, req.url);\n });\n proxy.on('proxyRes', (proxyRes, req, _res) => {\n console.log('Received Response from the Target:', proxyRes.statusCode, req.url);\n });\n }, \n }\n }\n```\n\n**I got the following errors when I refreshed**:\n\n```\nSending Request to the Target: GET /api/hello\nproxy error Error: connect ECONNREFUSED ::1:3001\n at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {\n errno: -4078,\n code: 'ECONNREFUSED',\n syscall: 'connect',\n address: '::1',\n port: 3001\n}\n3:45:38 p.m. [vite] http proxy error at /api/hello:\nError: connect ECONNREFUSED ::1:3001\n at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) (x3)\n ```\n```\n\n========================================\n\nTop Answer:\nThanks, your provided solution worked for me as well!\nMy vite.config.js:\n\n```\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vite.dev/config/\nexport default defineConfig({\n plugins: [react()],\n server: {\n proxy: {\n \"/api\": {\n target: \"http://127.0.0.1:5000\",\n changeOrigin: true,\n secure: false,\n },\n },\n },\n});\n```\n\npackage.json:\n\n```\n{\n ...\n \"proxy\": \"http://localhost:5000\"\n ...\n}\n```\n\nfetch call:\n\n```\nfetch(`/api/update-news?page=${page}`)\n```\n\n========================================\n\nCode:\n```js\nserver: {\n    proxy: { \"/api\":  {\n                      target: 'http://localhost:3001',\n                      changeOrigin: true,\n                      secure: false      \n                      }\n             }\n  },\n```\n\n```js\nconst Test: React.FC = () => {\n\n  useEffect(()=>{\n    fetch(`api/hello`)\n    .then(res => console.log(res))\n  }, [])\n  return(\n  <div>\n    hi\n  </div>\n  )\n}\n```\n\n```py\n@app.route('/api/hello', methods=['GET'])\ndef test():\n    return jsonify({\"hi\":\"there\"})\n```\n\n```text\nproxy: { \"/api\":  {\n                      target: 'http://localhost:3001',\n                      changeOrigin: true,\n                      secure: false,\n                      configure: (proxy, _options) => {\n                        proxy.on('error', (err, _req, _res) => {\n                          console.log('proxy error', err);\n                        });\n                        proxy.on('proxyReq', (proxyReq, req, _res) => {\n                          console.log('Sending Request to the Target:', req.method, req.url);\n                        });\n                        proxy.on('proxyRes', (proxyRes, req, _res) => {\n                          console.log('Received Response from the Target:', proxyRes.statusCode, req.url);\n                        });\n                      },   \n                      }\n             }\n```\n\n```text\nSending Request to the Target: GET /api/hello\nproxy error Error: connect ECONNREFUSED ::1:3001\n    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {\n  errno: -4078,\n  code: 'ECONNREFUSED',\n  syscall: 'connect',\n  address: '::1',\n  port: 3001\n}\n3:45:38 p.m. [vite] http proxy error at /api/hello:\nError: connect ECONNREFUSED ::1:3001\n    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) (x3)\n    ```\n```\n\n```text\nGET http://localhost:5173/api/hello net::ERR_ABORTED 500 (Internal Server Error)\n```\n\n```text\nserver: {\n    proxy: { \"/api\":  {\n                      target: 'http://127.0.0.1:3001',\n                      changeOrigin: true,\n                      secure: false      \n                      }\n             }\n  },\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vite.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  server: {\n    proxy: {\n      \"/api\": {\n        target: \"http://127.0.0.1:5000\",\n        changeOrigin: true,\n        secure: false,\n      },\n    },\n  },\n});\n```\n\n```text\n{\n    ...\n    \"proxy\": \"http://localhost:5000\"\n    ...\n}\n```\n\n```text\nfetch(`/api/update-news?page=${page}`)\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.441Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":253,"estimatedTokens":1279}}614{"id":"stack-71958593","source":"stackoverflow","questionId":71958593,"title":"Vite outDir outside of the project root","tags":[".htaccess","vuejs2","build","vuejs3","vite"],"text":"Title: Vite outDir outside of the project root\nTags: .htaccess, vuejs2, build, vuejs3, vite\nSource: Stack Overflow\n\nQuestion:\nI am building Vue3 project with Vite and I am using Vite build.outDir option to build the project outside of the Vue3 app root. This is my project structure, where in the `frontend` folder is located Vue3 application:\n\n```\nmy-app/\n├─ frontend/\n├─ public/\n│ ├─ dist/\n| ├─ .htaccess\n│ ├─ app.php\n```\n\nI am trying to build Vue3 project to `my-app/public/dist/` folder and I have achieved that by setting `outDir` in `vite.config.js` to:\n\n```\nbuild: {\n outDir: '../public/dist'\n},\n```\n\nLike that project is builded in the `dist` folder, but then when I open page source in the browser, relative URL to the builded script is not correct:\n\n```\n\n```\n\nFor example instead of `/assets/index.585a031a.css` should be `/dist/assets/index.585a031a.css`. Because of that I have added another Vite option `base` to be:\n\n```\nbase: '/dist/',\n```\n\nLike that when I go to page source everything works fine, but the problem is that URL of the application is change from `example.com` to `example.com/dist`.\n\nThis is my `.htaccess` file, but I think it is not related with `.htaccess`, because I have same settings in Vue2 application with default Vue CLI (Vite is not used):\n\n```\n# Disable directory listing\nOptions -Indexes\n# Enable the rewrite engine\nRewriteEngine On\n# Sets the base URL for rewrites\nRewriteBase /\n# Access to domain root should serve dist folder\nRewriteCond %{REQUEST_URI} ^/$\nRewriteRule ^(.*)$ /dist/$1 [L]\n# If URL doesn't match any static assets it should serve dist folder\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_URI} !/api/*\nRewriteRule . /dist/$1 [L]\n# If URL contains api it should serve app.php\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_URI} /api/*\nRewriteRule .* app.php [QSA,L]\n```\n\nSo, the main problem is how can I still build app in the `public/dist` folder and keep the URL of the application `example.com` instead of `example.com/dist`?\n\n========================================\n\nCode:\n```text\nmy-app/\n├─ frontend/\n├─ public/\n│  ├─ dist/\n|  ├─ .htaccess\n│  ├─ app.php\n```\n\n```text\nbuild: {\n  outDir: '../public/dist'\n},\n```\n\n```text\n<link rel=\"stylesheet\" href=\"/assets/index.585a031a.css\">\n```\n\n```text\nbase: '/dist/',\n```\n\n```text\n# Disable directory listing\nOptions -Indexes\n# Enable the rewrite engine\nRewriteEngine On\n# Sets the base URL for rewrites\nRewriteBase /\n# Access to domain root should serve dist folder\nRewriteCond %{REQUEST_URI} ^/$\nRewriteRule ^(.*)$ /dist/$1 [L]\n# If URL doesn't match any static assets it should serve dist folder\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_URI} !/api/*\nRewriteRule . /dist/$1 [L]\n# If URL contains api it should serve app.php\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_URI} /api/*\nRewriteRule .* app.php [QSA,L]\n```\n\n```text\nfrontend\n```\n\n```text\nmy-app/public/dist/\n```\n\n```text\noutDir\n```\n\n```text\nvite.config.js\n```\n\n```text\ndist\n```\n\n```text\n/assets/index.585a031a.css\n```\n\n```text\n/dist/assets/index.585a031a.css\n```\n\n```text\nbase\n```\n\n```text\nexample.com\n```\n\n```text\nexample.com/dist\n```\n\n```text\n.htaccess\n```\n\n```text\n.htaccess\n```\n\n```text\npublic/dist\n```\n\n```text\nexample.com\n```\n\n```text\nexample.com/dist\n```\n\n```text\n{\n...\n// base: '/dist/', remove base config\nbuild: {\n    outDir: '../public', // this line place index.html in the public folder\n    assetsDir: './dist', // this line place your assets in the public/dist folder\n  }\n}\n```\n\n```text\nindex.html\n```\n\n```text\ndist\n```\n\n```text\nexample.com/dist\n```\n\n```text\nindex.html\n```\n\n```text\nindex.html\n```\n\n```text\npublic\n```\n\n```text\nexample.com\n```","metadata":{"transformedAt":"2026-08-18T18:33:46.441Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":28,"totalLines":210,"estimatedTokens":955}}615