A way to run vite dev on remote server (like Laravel Mix) - vue.js

I've switched from Laravel Mix to Vite, and am trying to accomplish same thing "npm run watch" does for Laravel Mix. Caveat: our staging servers are not local (i.e. staging.app-domain-name.com). If I run npm run dev with Vite it revs up the "dev" server that's supposed to be at http://ip:3000, but that obviously does not work. Aside from not having an active watcher, I can't get the dev to be used with Vue Devtools plugin (since vite only can spit out prod on server).
My vite.config.js:
const { resolve } = require('path');
import vue from '#vitejs/plugin-vue';
export default ({ command }) => ({
base: command === 'serve' ? '' : '/dist/',
publicDir: 'fake_dir_so_nothing_gets_copied',
build: {
manifest: true,
outDir: resolve(__dirname, 'public/dist'),
rollupOptions: {
input: 'resources/js/app.js',
},
},
server: {
host: true,
port: '8080',
hot: true
},
plugins: [vue()],
resolve: {
alias: {
'#': resolve('./resources/js'),
},
},
});
My app.js
import "./bootstrap";
import '../css/app.css';
import { createApp, h } from 'vue';
import { App as InertiaApp, plugin as InertiaPlugin } from '#inertiajs/inertia-vue3';
import { InertiaProgress } from '#inertiajs/progress';
let asyncViews = () => {
return import.meta.glob('./Pages/**/*.vue');
}
const el = document.getElementById('app');
createApp({
render: () =>
h(InertiaApp, {
initialPage: JSON.parse(el.dataset.page),
resolveComponent: async name => {
if (import.meta.env.DEV) {
return (await import(`./Pages/${name}.vue`)).default;
} else {
let pages = asyncViews();
const importPage = pages[`./Pages/${name}.vue`];
return importPage().then(module => module.default);
}
}
}),
})
.mixin({ methods: { route } })
.use(InertiaPlugin)
.mount(el);
And package.json scripts:
"scripts": {
"predev": "printf \"dev\" > public/hot",
"dev": "vite",
"preprod": "printf \"prod\" > public/hot",
"prod": "vite build"
}
Desired outcome to generate dev bundle on a remote server by running
npm run dev
Currently it tries to create localhost dev. I assume something in vite.config.js needs to be set to get that done. I've gone over the docs but could not find anything clear enough.

To tell Vite to listen also on network interface simply add --host parameter to dev script:
"scripts": {
"dev": "vite --host",
"prod": "vite build"
},
It gives me an result like this:
vite v2.5.10 dev server running at:
> Local: http://localhost:3000/
> Network: http://x.y.x.z:3000/ <-- server public IP
> Network: http://10.10.10.1:3000/ <-- server local IP via VPN
ready in 330ms.
But this was not solution. I had a problem with CORS. I resolved it in another way. It depends on web server. I use nGinx and I set reverse proxy to listen on port 3000.
server {
listen x.y.x.z:3000 ssl; ### Server public IP address
server_name dev.example.com;
location / {
proxy_pass https://127.0.0.1:3000/; ### https: is Important
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection upgrade;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
}
# SSL config
ssl_certificate /srv/certs/example.com/fullchain.cer;
ssl_certificate_key /srv/certs/example.com/example.com.key;
include ssl_config;
}
Ii is also important to listen only on public IP address due to not conflict with vite on same port. Vite default listen only on localhost. Reload nGinx
sudo nginx -t
sudo systemctl reload nginx
In package.json I put --https atribute
{
"private": true,
"scripts": {
"dev": "vite --https",
"prod": "vite build"
},
"devDependencies": {
"postcss": "^8.1.14",
"vite": "^2.5.10"
}
}
And that's it. Now I am able run
npm run dev
Finnally I put scripts to my layout blade end Vite start works.
<script type="module" src="https://dev.example.com:3000/#vite/client"></script>
<script type="module" src="https://dev.example.com:3000/resources/js/app.js"></script>
Setup nginx to proxy websocket
https://www.nginx.com/blog/websocket-nginx/
Sebastyan's guide to setup Vite with Laravel
https://sebastiandedeyne.com/vite-with-laravel

Adding this server part of this config to my config in vite.config.js file fixed things for me.
export default defineConfig({
server: {
hmr: {
host: 'localhost',
}
}
});
Except you may want to change the host part from localhost to your server's IP address.
Then do npm run dev -- --host as others have mentioned.
I copy pasted this answer from here without reading anything else about it or why it works.

Adding --host separated by -- worked in my case - no changes in config files needed this way:
npm run dev -- --host

Try this:
CMD [ "npm", "run", "dev", "--", "--host"]
It worked for me but the app keeps reloading

Adding the arguments "--" "--host" to my Docker file did the trick.
like so:
CMD [ "npm", "run", "dev", "--", "--host"]
this allows me to start the server in dev mode and to reach it from my host.

{
"name": "zustand",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"cmd": "cmd /k npm run dev -- --host",
"host": "vite --host",
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"#tanstack/react-query": "^4.20.9",
"axios": "^1.2.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"zustand": "^4.2.0"
},
"devDependencies": {
"#types/react": "^18.0.26",
"#types/react-dom": "^18.0.10",
"#vitejs/plugin-react": "^3.0.1",
"typescript": "^4.9.4",
"vite": "^4.0.4"
}
}
---
vite --host
VITE v4.0.4 ready in 623 ms
➜ Local: http://localhost:5173/
➜ Network: http://172.19.80.1:5173/
➜ Network: http://192.168.100.14:5173/
➜ press h to show help
para que funcione "vite --host", debe estar instalado globalmente.
Ej: npm install vite -g

Related

Nuxt 3 + Vite & HMR : infinite reload & failed

On a fresh install of Nuxt3, using Docker, I have this error on the console and an infinite reload of the page :
client.ts:28 WebSocket connection to 'wss://shop.store.local/_nuxt/'
failed: (anonyme) # client:188 client.ts:224 [vite] server connection
lost. polling for restart...
Here is the configuration of my vite server (via nuxt.config.js):
vite: {
server: {
hmr: {
host: 'shop.store.local',
port: 443,
}
}
}
The docker-compose describes the Traefik labels:
vuejs:
labels:
- "traefik.http.routers.front_store.rule=Host(`shop.store.local`)"
- "traefik.http.routers.front_store.tls=true"
- "traefik.http.services.front_store.loadbalancer.server.port=3000"
What I've tried too, in my package.json file:
"scripts": {
"dev": "nuxi dev --host=0.0.0.0",
"build": "nuxi build",
"start": "node .output/server/index.mjs"
},
Any idea ? I looked over internet, people have the problem, but no solution...
Expose ports for nuxt container.
ports:
3000:3000
24678:24678
Also edit your nuxt.config:
vite: {
server: {
host: "0.0.0.0",
hmr: {
},
},
},

vue3 by vite hot replacement not work in homestead

I am new in Vite, I follow the scaffolding-your-first-vite-project by
npm init #vitejs/app client --template vue
edit the default package.json
{
"version": "0.0.0",
"scripts": {
"dev": "node_modules/vite/bin/vite.js --host 0.0.0.0 --port 3000",
"build": "node_modules/vite/bin/vite.js build --host 0.0.0.0 --port 3000",
"serve": "node_modules/vite/bin/vite.js preview --host 0.0.0.0 --port 3000"
},
"dependencies": {
"vue": "^3.0.5"
},
"devDependencies": {
"#vitejs/plugin-vue": "^1.2.2",
"#vue/compiler-sfc": "^3.0.5",
"vite": "^2.3.4"
}
}
then
npm install
npm run dev
everything works fine
But when I change the components/HelloWorld.vue, nothing happended, the hot module replacement didn't work
I checked the NODE_ENV and change package.json like below:
"scripts": {
"dev": "node_modules/vite/bin/vite.js cross-env NODE_ENV=development --host 0.0.0.0 --port 3000",
But pages turn into blank and a lot of errors appeared in console.
How can I find out the issue?
Great thanks for anyone helps!
The problem is in your script:
node_modules/vite/bin/vite.js cross-env NODE_ENV=development --host 0.0.0.0 --port 3000
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
cross-env needs to be the primary command, so move it to the beginning:
cross-env NODE_ENV=development node_modules/vite/bin/vite.js --host 0.0.0.0 --port 3000
But just so you're aware, vite by default sets NODE_ENV to development, so there's no need to do it yourself.
Ok, finally I fixed this by
replace the #/~ in your import() with .//../
✅ Do
import('./pages/index.vue')
❌Do not
import('#/pages/index.vue)
more detail: https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations
passing usePolling to the server.watch options in the Vite config
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
server: {
watch: {
usePolling: true
}
}
})
more detail: https://github.com/vitejs/vite/issues/1153#issuecomment-785467271

Can I change the default port from 8080 to something else in Vue?

I have been working on Vue.js and Node.js to build my app. When I have started with Vue it is by default running on 8080 and Node I am running on 3008.
What I am trying to do is due to some circumstances I want to change the port for Vue from 8080 to any other like 8086 or 3005. How can I do that?
Simply you can run the following command to run vue app as per your required port :
npm run serve --port 8086
Another way is to update the serve script command in your package.json file. Just append --port 8086 like so:
"scripts": {
"serve": "vue-cli-service serve --port 8086",
"build": "vue-cli-service build",
"inspect": "vue-cli-service inspect",
"lint": "vue-cli-service lint"
}
If you don't have one create vue.config.js in the root dir of your project and there add this option:
module.exports = {
devServer: {
port: 8086
}
}
In webpack docs you can see all the available options for configuring the dev server.
Check also vue-cli docs.
This is the way! ...that worked for me!
npm run serve -- --port 8086
With "npm":
npm run serve --port 8086
With "yarn":
yarn serve --port 8086
If you are using vite as your build tool, you can override the default port with the one you want by providing a server.port entry in the vite configuration file - vite.config.js
In the example below, I set the default port to 8086
export default defineConfig({
...
server: {
port: 8086,
},
});
in vue.config.js
module.exports = defineConfig({
...
devServer: {
port: 8086,
},
DIR: node_modules#vue\cli-service\lib\commands
CHANGE FILE: serve.js
const defaults = {
host: '0.0.0.0',
port: 8086,
https: false
}

How to build everything into a dist with folder structure by webpack?

I am a java developer for years and just new to the js world. This question sounds stupid but I don't know what's the proper/best way to build a dist for reactjs app for deploying to production(nginx/apache).
From my understanding, the dist just like simple web app and should looks like
contains:
index.html
client.js (bundled js after compiled)
static files, e.g.
images, css, js libraries, etc
I follow the guide on:
https://github.com/learncodeacademy/react-js-tutorials/tree/master/1-basic-react
and have a simple web app(maybe this is not called web app) running by:
npm run dev
it uses webpack to bundles the client.js.min and deploy to a embedded web server by node(maybe i am wrong).
Question:
How to build all the things by a command, say "npm run build" and it should built everything in a folder called "dist". So I can deploy it to web server root by copying every in dist to the web root.
package.json
{
"name": "react-tutorials",
"version": "0.0.0",
"description": "",
"main": "webpack.config.js",
"dependencies": {
"babel-core": "^6.17.0",
"babel-loader": "^6.2.0",
"babel-plugin-add-module-exports": "^0.1.2",
"babel-plugin-react-html-attrs": "^2.0.0",
"babel-plugin-transform-class-properties": "^6.3.13",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-preset-stage-0": "^6.3.13",
"react": "^0.14.6",
"react-dom": "^0.14.6",
"webpack": "^1.12.9",
"webpack-dev-server": "^1.14.1"
},
"devDependencies": {},
"scripts": {
"dev": "webpack-dev-server --content-base src --inline --hot",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
webpack.config.js
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');
module.exports = {
context: path.join(__dirname, "src"),
devtool: debug ? "inline-sourcemap" : false,
entry: "./js/client.js",
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties'],
}
}
]
},
output: {
path: __dirname + "/src/",
filename: "client.min.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};
In your scripts dictionary of package.json add the following
"build" : "NODE_ENV='production' && node_modules/.bin/webpack -p"
This will tell webpack to read the config file and build it in production mode i.e minify etc etc. The -p flag does it. The node env is to ensure that production build are used for react and other libraries and to set an env variable of production for NODE_Env
To run type. npm run build

npm: How to set NODE_ENV in Windows (10)?

I am trying to add an npm script in package.json that sets NODE_ENV before doing something else (like running webpack). But although the syntax seems to be correct, NODE_ENV is not set when running under Windows 10.
Test script
"scripts": {
"test": "SET NODE_ENV=debug && echo %NODE_ENV%" }
The result from npm run test is "production" (provided NODE_ENV was set to "production" before running the script). Should be "debug".
What could be wrong? I even tried cross-env with no success.
Edit
To clarify my question: I cannot set any environment variable under Windows 10. And I need to call SET because I am running the script under Windows (10). Seems to be some rights problem (scripts not allowed to set environment variables?).
Another (or the actual) question would be: How can I create one script to build (using webpack) with creating minified versions of JavaScript files (for production), and one script to create non-minified versions (for development). So far I use following approach (see comments for the important parts):
Edit 2
I did not now that this probably made a difference, but in case it does: I worked with an React app created with create-react-app. I found the answer to my question, see below.
package.json:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
// Scipts for build for development and for production
"build-dev": "SET NODE_ENV=debug webpack",
"build-release": "SET NODE_ENV=production webpack"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-preset-env": "^1.4.0",
"babel-preset-react": "^6.24.1",
"debug": "^2.6.4",
"webpack": "^2.4.1"
}
}
webpack.config.js:
const path = require('path');
var webpack = require('webpack');
// Check if in debug environment
var debug = process.env.NODE_ENV !== "production";
module.exports = {
context: path.join(__dirname, 'src'),
entry: ['./index.js'],
output: {
path: path.join(__dirname, 'www/js'),
filename: 'index.js',
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: ['babel-loader'],
}],
},
// Add the UglifyJs plugin only in debug mode
plugins: debug ? [] : [new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false })],
resolve: {
modules: [
path.join(__dirname, 'node_modules')
]
}
};
This fails because setting NODE_ENV does not work for some reason. Using the command prompt directly like in the scripts:
SET NODE_ENV = debug
webpack
works by the way. That's proof that the configuration is okay, but just the npm script cannot set NODE_ENV.
Just in case you are STILL having issues setting the NODE_ENV in Windows 10 - this will help you. In your package.json file add the following:
"test": "SET \"NODE_ENV=test\""
If you plan on pushing this to Heroku - you will have to "export" the variable and your string would look like this (you are escaping the Windows-NEEDED quotes with a slash):
"test": "export NODE_ENV=test || SET \"NODE_ENV=test\""
Lastly, if you need a following command like mocha then the line would look like this:
"test": "export NODE_ENV=test || SET \"NODE_ENV=test\" && mocha server/**/*.name_of_files_plus_test.js"
Hope this helps someone :) - Mike
I found the answer to my question in the meantime, basically in the create-react-app readme: Firstly in an app created with create-react-app NODE_ENV cannot be manually overridden. Secondly, when setting environment variables, their name must start with "REACT_APP_". This was the solution for me.
In package.json:
"scripts": {
...
"build:staging": "SET REACT_APP_ENVIRONMENT=Staging && npm run build"
}
In the code:
if (process.env.REACT_APP_ENVIRONMENT === "Staging") ...
Did you try?
set DEBUG=* & npm run test
Make sure debug already installed
npm install debug --save
UPDATE:
To set environment variable in windows use
set NODE_ENV=dev //for development environment
In your case
"scripts": {
"test": "NODE_ENV=dev && echo %NODE_ENV%" }