In a Vue + Vite project, I have folder structure like this
The problem is vite doesn't detect changes (ctrl+s) in A.vue or B.vue i.e., components nested under NestedFolder in components folder. Everywhere else works fine.
My vite.config.js looks like this,
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue()
],
resolve: {
alias: {
'#': fileURLToPath(new URL('./src', import.meta.url)),
'#public': fileURLToPath(new URL('./public', import.meta.url))
}
},
server: {
proxy: {
'/api': {
target: 'XXX',
changeOrigin: true,
secure: false,
ws: true,
}
}
}
})
I've tried custom HMR functions as per the vite HMR API docs, got it to send full reload using this.
...
plugins: [
vue(),
{
name: 'custom-hmr',
enforce: 'post',
// HMR
handleHotUpdate({ file, server }) {
if (file.endsWith('.vue')) {
console.log('reloading json file...');
server.ws.send({
type: 'reload',
path: '*'
});
}
},
}
], ...
I looked through vite's HMR API docs but couldn't figure out how to send update event to vite when using custom hmr function
Any help/suggestion on how to solve this would be greatly appreciated.
Ok I solved the problem. The problem is not with nested folders.
Vite seems to ignore components that are imported with absolute path.
E.g. Vite doesn't detect changes in components imported as:
import Dropdown from '#/components/GlobalDropdown.vue'
//# resolves to /src
but detects changes in imports that are relative:
import LoadingSpinner from '../LoadingSpinner.vue'
I couldn't find any setting that addresses this. But having relative paths for component imports solved the issue. Is this an issue?
I think issue is that you made a caseSensitive typo, please check that your path is correct, I had similar issue and this was one letter typed in uppercase.
Related
I'm struggling to get absolute path to work in a Vite react-ts project.
Here's how I created the project
npm init #vitejs/app
npx: installed 6 in 1.883s
√ Project name: ... test-vite
√ Select a framework: » react
√ Select a variant: » react-ts
Then I added baseUrl to tsconfig.json
based on the TS official doc:
{
"compilerOptions": {
"baseUrl": "./src",
...
followed by adding a simple component (T:\test-vite\src\components\Test.tsx)
import React from "react";
const Test = () => <h1>This is a Test.</h1>;
export default Test;
Finally I import the Test component in App.tsx
but it won't let me use absolute path:
import Test from "components/Test";
I get this error
whereas if I use relative path, the app works in dev & build mode without any error:
import Test from "./components/Test";
How can I make absolute path work in the project?
There are two problems here:
Tell typescript how to resolve import path
Tell vite how to build import path
You only tell typescript how to resolve, but vite don't konw how to build. So refer to the official document resolve.alias, maybe this is what you want:
// vite.config.ts
{
resolve: {
alias: [
{ find: '#', replacement: path.resolve(__dirname, 'src') },
],
},
// ...
}
You can import path like this (or any module under ./src):
import Test from "#/components/Test";
import bar from "#/foo/bar"
Moreover, you can use vite plugin vite-tsconfig-paths directly, it makes you don't have to manually configure resolve.alias
Follow the instructions below:
Install vite-tsconfig-paths as dev dependency
Inject vite-tsconfig-paths using the vite.config.ts module
import { defineConfig } from 'vite'
import tsconfigPaths from 'vite-tsconfig-paths'
export default defineConfig({
plugins: [tsconfigPaths()],
})
I 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'
So if you have a /src directory that contains all code and want to use an absolute import path.
vite.config.ts
export default defineConfig({
...
resolve: {
alias: {
src: path.resolve('src/'),
},
}
})
tsconfig.json
{
"compilerOptions": {
...
"baseUrl": "./"
}
}
Note 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.
#Yuns solutions works, but it shows error in vscode. And it was breaking auto-import in vs code.
To make it work in vscode and vite both, I added alias in both tsconfig and vite.config.
// tsconfig.json
{
"paths": {
"#/*": ["src/*"]
}
// ...
}
// vite.config.ts
{
resolve: {
alias: [{ find: '#', replacement: '/src' }],
},
// ...
}
Then, I could import like below (svelte app is in src directory)
import Header from '#/components/Header.svelte
Looking for import {...} from "src/foo/bar";?
I also came here through search results like user Maciej Krawczyk, but the # part also wasn't what I was interested in. That user's answer helped me, but I had trouble with the path.resolve part (ReferenceError because path wasn't defined), so I used a slightly different approach:
vite.config.ts
export default defineConfig({
...
resolve: {
alias: {
src: "/src",
},
},
...
})
Vite's resolver considers the absolute path /src to be from where the server is serving (see GH issue). So if you're running/building from the root of your project with src as a top level directory -- which is pretty common -- this alias points Vite in the right direction.
tsconfig.json
{
"compilerOptions": {
...
"baseUrl": "./",
"paths": {
"src/*": [
"./src/*"
]
}
}
}
This is basically blindly following this StackOverflow answer. TypeScript needs to know that we have special resolving going on as well, otherwise TS will be freaked out about your non-existent src package and not know where it should go looking. (Note: After I changed my TS config, VSCode didn't immediately pick up the change, so I was still getting warnings. I quit, re-opened, and had to wait ~15sec for the warnings to go away.)
1) You need to install these packages:
npm i path
yarn add path
npm i #types/node
yarn add #types/node
npm i vite-tsconfig-paths
yarn add vite-tsconfig-paths
2) Then in the vite.config file:
import { defineConfig } from 'vite';
import react from '#vitejs/plugin-react';
import tsconfigPaths from 'vite-tsconfig-paths';
import path from 'path';
export default defineConfig({
base: './',
resolve: {
alias: {
Components: path.resolve(__dirname, './src/components'),
Assets: path.resolve(__dirname, './src/assets'),
},
},
plugins: [react(), tsconfigPaths()],
});
3) And now we have to tell TS those same paths that we defined in the alias:
{
"compilerOptions": {
...,
"baseUrl": "./",
"paths": {
"src/*": [ "./src/*" ],
// We define this path for all files/folders inside
// components folder:
"Components/*": [ "./src/components/*" ],
// We define this path for the index.ts file inside the
// components folder:
"Components": [ "./src/components" ],
"Assets/*": [ "./src/assets/*" ],
"Assets": [ "./src/assets" ]
}
},
...
}
4) reload vscode: As the comment above said, press Fn1 and type "reload with extensions disabled", re-enabling extensions from the popup.
Now try to import
import Test from "components/Test";
it should work.
For anyone looking specifically to add the nice import "#/something-in-src" syntax like Vue has with the latest (as of posting this answer) version of Vite + React + TypeScript, here's how I did it:
Make sure #types/node is installed as a dev dependency. This didn't come with the latest version of Vite for me, and it will make "path" and __dirname throw an undefined error.
vite.config.ts
import { defineConfig } from "vite";
import react from "#vitejs/plugin-react";
import path from "path";
// https://vitejs.dev/config/
export default defineConfig({
resolve: {
alias: [{ find: "#", replacement: path.resolve(__dirname, "src") }],
},
plugins: [react()],
});
tsconfig.json
Add:
{
"compilerOptions": {
"paths": {
"#/*": ["./src/*"]
}
}
}
For anyone who stucks after all required changes, you need to reload vscode.
My config files:
tsconfig.json
"baseUrl": "./",
"paths": {
"#/*": ["src/*"]
}
vite.config.ts
import { defineConfig } from 'vite';
import react from '#vitejs/plugin-react';
import path from 'path';
// https://vitejs.dev/config/
export default defineConfig({
resolve: {
alias: { '#': path.resolve(__dirname, './src') },
},
plugins: [react()],
});
In above code you need to have 2 libraries installed:
'path': npm i path
'#types/node': npm i #types/node
After configure your project files you need to reload vscode. To do that press ctrl + P and type ">reload with extensions disabled", after that you will get popUp to activate extensions again click it, and your absoulte path should work
If someone installed vite-tsconfig-paths library, you also need to reload the vscode, remember to import given library to vite.config.ts
export default defineConfig({ plugins: [react(), tsconfigPaths()] });
With package you get default 'components/File' import instead of '#components/File' import.
I'm having a devil of a time figuring out how to build a single .js file from Vite in my Svelte project that includes all of the built javascript and CSS from my Svelte projects. By default, Vite bundles the app into one html file (this is ok), two .js files (why??), and one .css file (just want this bundled into the one js file).
I ran this very basic command to get a starter project:
npx degit sveltejs/template myproject
I tried adding a couple of plugins, but nothing I added achieved the results I wanted. Primarily, the plugins I found seem to want to create a single HTML file with everything in it. It seems like PostCSS might be able to help, but I don't understand what configuration I can set via Vite to get it to do what I want.
What is the magic set of plugins and config that will output a single HTML file with a single js file that renders my Svelte app and its CSS onto the page?
Two steps,
We can inject css into js assets with vite-plugin-css-injected-by-js.
We can emit a single js asset by disabling chunks in rollup's config.
Final result,
import cssInjectedByJsPlugin from "vite-plugin-css-injected-by-js";
export default defineConfig({
plugins: [cssInjectedByJsPlugin()],
build: {
rollupOptions: {
output: {
manualChunks: undefined,
},
},
},
});
If you're looking for a solution to this, you might want to take a look at vite-plugin-singlefile.
That doesn't come out of the box for vite but you can write a quick plugin which will be doing exactly that
const bundle_filename = ''
const css_filename = 'style.css'
defineConfig({
build: {
lib: {
entry: 'src/mycomponent.js',
name: 'mycomponent.js',
fileName: () => 'mycomponent.js',
formats: ['iife'],
},
cssCodeSplit: false,
rollupOptions: {
plugins: [
{
apply: 'build',
enforce: 'post',
name: 'pack-css',
generateBundle(opts, bundle) {
const {
[css_filename]: { source: rawCss },
[bundle_filename]: component,
} = bundle
const IIFEcss = `
(function() {
try {
var elementStyle = document.createElement('style');
elementStyle.innerText = ${JSON.stringify(rawCss)}
document.head.appendChild(elementStyle)
} catch(error) {
console.error(error, 'unable to concat style inside the bundled file')
}
})()`
component.code += IIFEcss
// remove from final bundle
delete bundle[css_filename]
},
},
],
},
},
})
I created a boilerplate Vite project for this problem:
https://github.com/mvsde/svelte-micro-frontend
Maybe the configuration helps with your case:
import { defineConfig } from 'vite'
import { svelte } from '#sveltejs/vite-plugin-svelte'
export default defineConfig({
plugins: [
svelte({
emitCss: false
})
],
build: {
assetsDir: '',
sourcemap: true,
lib: {
entry: 'src/main.js',
formats: ['iife'],
name: 'SvelteMicroFrontend',
fileName: 'svelte-micro-frontend'
}
}
})
I had the same issue and was able to fix by editing vite.config.ts as follows tested on vite#2.3.8
export default {
build: {
rollupOptions: {
output: {
manualChunks: undefined,
},
},
},
};
If you are working with Svelte, you can use emitCss:
export default defineConfig({
plugins: [svelte({
emitCss: false,
})],
})
As manualChunks are no longer working in a latest versions of Vite, there's no any way to combine all the chunks into one.
But found a hacky solution to have an index.html + bundle.js after the build: https://github.com/d-velopment/SvelteKit-One-Bundle - it rewraps the project's initial .js files to go from bundle.js, which could be loaded from index.html or external project.
I'm trying to use environment variables in my svelte app. I've installed #Rollup/plugin-replace and dotenv. I created a .env file to hold my API_KEY and added the following to plugins in rollup.config.js from this Medium article:
plugins: [
replace({
__myapp: JSON.stringify({
env: {
isProd: production,
API_URL : process.env.API_URL
}
}),
}),
]
and in the svelte components of my app I would access my API key via
const apiUrl = __myapp.env.API_URL
which worked. However, a few days later I was having authentication issues and after some debugging I found that __myapp.env.API_URL was returning undefined by trying to print it to the console.
I then tried changing the replace call to just replace({'API_KEY': process.env.API_KEY}) and console.log(API_KEY) was still displaying undefined. I tested replace by trying to use it replace some variable with some string and it worked so that confirms that rollup is working fine. So, I suspect the problem is in process.env.API_KEY but I'm not sure. What might I be doing wrong with my attempts to access my environment variables?
(Some background: I am using sveltejs/template as a template to build my app)
dotenv won't register your .env vars until you call config, that's why process.env.API_KEY is undefined when you try to access it.
In your rollup.config.js you can do:
import { config as configDotenv } from 'dotenv';
import replace from '#rollup/plugin-replace';
configDotenv();
export default {
input: 'src/main.js',
...
plugins: [
replace({
__myapp: JSON.stringify({
env: {
isProd: production,
API_URL: process.env.API_URL,
},
}),
}),
svelte({ ... })
]
}
I followed the steps on the website 'https://angular.io/guide/aot-compiler' to adapt an Angular 2 app to use AoT compilation and everything seemed to work as expected until the rollup step, which in theory cleans up the code of unused components.
Leaving the 'rollup-config.js' file the same as in the instructions, when I run 'node_modules/.bin/rollup -c rollup-config.js' I get the following error:
[!] Error: 'ToastModule' is not exported by node_modules/ng2-toastr/ng2-toastr.js
I've googled it, and I came across a solution that pointed to add a 'namedExports' field to the 'commonjs' parameter. The resulting 'rollup-config.js' is:
import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import uglify from 'rollup-plugin-uglify';
export default {
entry: 'src/main.js',
dest: 'src/build.js',
sourceMap: false,
format: 'iife',
onwarn: function(warning) {
if(warning.code === 'THIS_IS_UNDEFINED') { return; }
console.warn(warning.message);
},
plugins: [
nodeResolve({jsnext: true, module: true}),
commonjs({
include: 'node_modules/**',
namedExports: {
'node_modules/ng2-toastr/ng2-toastr': [ 'ToastModule' ]
}
}),
uglify()
]
}
Now, the script generates the 'build.js' file and I can load it through the index.html file, but the component 'ng2-toastr' is not working (the component shows a 'toast' like message, appearing on one side of the screen and disappearing after a few seconds).
Did I miss something? Thanks in advance,
In react because I have to import varies helper or component I have this problem
import approxPerDay from '../../../utils/approxPerDay.js'
import otherstuff from '../components/otherstuff'
and in another file it might be import approxPerDay from '../utils/approxPerDay.js'
It's really hard and time consuming to find is the relative path is. Is there any npm or helper can solve this issue?
I was experiencing a similar problem. I finally resolved it by following this article: https://medium.com/#ktruong008/absolute-imports-with-create-react-app-4338fbca7e3d
Create a .env file in the root of the react app
Add a line NODE_PATH = src/
That worked for me.
It depends on your module bundler. For Webpack 2 you can do something like this:
module.exports = {
...
resolve: {
modules: [
'node_modules',
path.resolve(__dirname + '/src')
],
alias: {
src: path.resolve(__dirname + '/src')
}
},
...
}
the same for Webpack 1:
module.exports = {
...
resolve: {
root: [
path.resolve(__dirname + '/src')
],
alias: {
src: path.resolve(__dirname + '/src')
}
},
...
}
Than you will be able to use src as a native path like this:
import approxPerDay from 'src/utils/approxPerDay.js'
import otherstuff from '../components/otherstuff'
The thing you are asking is called "absolute import".
"create react app" already provides a standard solution and recommends creating a jsconfig.json file in your root directory of react project.
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
Later you can import components as such:
import Button from 'components/Button';
Go to this link of official docs related to importing component and there u will find absolute import section:
https://create-react-app.dev/docs/importing-a-component/
And Yes don't forget to restart your react server after doing the changes : )
If you need to specify the .env file and relative path, the IDE needs to know about it.
For this, the following lines worked for on my IDE.
File
jsconfig.json
{
"compilerOptions": {
"baseUrl": "src"
},
"include": [
"src"
]
}