How to set vite.config.js base public path? - vue.js

I'm trying to set a base url for both my dev and prod environments, but vitejs configs are not resolved.
According to vitejs , you can set the base public path when served in development or production, in your config options.
When running vite from the command line, Vite will automatically try to resolve a config file named vite.config.js inside project root.
The 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/.
My current configs are bellow:
// vite.config.js
export default {
base: 'http://localhost:8080/'
}
// packages.json
{
"name": "vue3ui",
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": {
...,
"vue": "^3.0.11"
},
"devDependencies": {
"#vue/compiler-sfc": "^3.0.11",
"vite": "^1.0.0-rc.13"
}
}

Not totally clear to me but I will try to give you an answer to achieve what you want.
I'm trying to set a base url for both my dev and prod environments
Edit: I read again you question, and I think you are looking for the point C on this answer.
Changes should be made in vite.config.js
A) You are looking to change the running port from 3000 to 8080, adjust server.port
server: {
port: '8080'
}
B) But if you are looking to run on localhost:3000 and forward requests to localhost:8080 then you have to adjust server.proxy
server: {
proxy: {
'/': {
target: 'http://localhost:8080/'
},
'/admin': {
target: 'http://localhost:8081/'
}
}
}
example:
'/': will proxy all requests to localhost:8080
'/admin': will proxy only requests that have as endpoint /admin to http://localhost:8081
C) Changing base path depending on dev or prod environment
.env file :
// .env
// Running locally
APP_ENV=local
// you change port of local/dev here to :8000
// do not forget to adjust `server.port`
ASSET_URL=http://localhost:3000
// Running production build
APP_ENV=production
ASSET_URL=https://your-prod-asset-domain.com
vite.config.js:
const ASSET_URL = process.env.ASSET_URL || '';
export default {
base: `${ASSET_URL}/dist/`,
[...]
}
If it's not what you are looking for, please be more precise and I will edit my answer.
For more information, head to the official doc at https://vitejs.dev/config/#server-options

I think I understand what TC wants to solve.
He has 1 build for dev and prod envs.
But it depends on envs, he has a different base path.
Answer:
https://vitejs.dev/guide/build.html#advanced-base-options
At the moment it is an experimental feature
experimental: {
renderBuiltUrl(filename: string, { hostType }: { hostType: 'js' | 'css' | 'html' }) {
if (['js', 'css'].includes(hostType)) {
return { runtime: `window.__getFile(${JSON.stringify(filename)})` }
} else {
return { relative: true }
}
}
}
and create global function
window.__getFile = function(file){
if (window.location.host.includes('dev')) {
return `http://cdn.dev/${file}`
}
return `http://cdn.prod/${file}`
}
P.s. Sorry. I can't find any example with port

Related

In NuxtJS How to configure different paths for publicPath, outputDir, and indexPath

I have situation when i deploy NuxtJS App for production that I need put files in different paths.
I used this configurations before in Vue App in vue.config.js and it’s works fine:
module.exports = {
publicPath:'/assets/my_app/my_page/',
outputDir: path.resolve('../my_app/public/my_page'),
indexPath: path.resolve('../my_app/www/my_page.html'),
devServer: {
allowedHosts: ["my_site.com"],
proxy: {
'^/api': serverProxy,
'^/assets': serverProxy,
'^/files': serverProxy
}
}
};
How can do the same configurations in NuxtJS?
I tried this in nuxt.config.js but it not working:
build: {
publicPath:'/assets/my_app/my_page/',
// outputDir: path.resolve('../my_app/public/my_page'),
},
generate: {
dir: path.resolve('../my_app/www/my_page.html'),
},
there are different Dir properties that you can use in nuxt.config. I think
buildDir ,rootDir or srcDir can help you. However, you can access vue configuration and use your old solution by :
nuxt.config vue.config property

Nuxt static generated page and axios post

I have a Nuxt project. Everything is OK when I generate a static page.
However, I need to send a POST request to the other server.
I tried to use both a proxy in nuxt.config.js and just direct query, but after deploy to the ngnix eventually, nothing works.
Please help.
UPDATE. Steps to reproduce.
Create Nuxt App including axios and proxy
Configure your proxy for other webservice:
proxy: {
'/api': {
target: 'http://example.com:9000',
pathRewrite: {
'^/api': '/',
},
},
changeOrigin: true,
},
call this service somewhere in the code:
const result = await this.$axios.post('/api/email/subscribe', {email: email})
run "yarn dev" and test the service. It works locally properly.
run 'nuxt generate' and deploy the static code hosting service, for example, hosting.com
run your page which calls the above-mentioned service.
As a result, instead of making POST call to the hosting.com/api/email/subscribe, it calls localhost:3000/api/email/subscribe.
Be sure to install the nuxt versions of axios and proxy in your project #nuxt/axios and #nuxtjs/proxy
after that in your nuxt.config.js add axios as module plus this options for axios and proxy:
modules: [
// Doc: https://axios.nuxtjs.org/usage
'#nuxtjs/axios',
//more modules if you need
],
/*
** Axios module configuration
*/
axios: {
proxy: true,
// See https://github.com/nuxt-community/axios-module#options
},
proxy: {
'/api/': {
target: process.env.AXIOS_SERVER, // I use .env files for the variables
pathRewrite: { '^/api/': '' }, //this should be your bug
},
},
now you can use axios in any part of the code like this
const result = await this.$axios.post('/api/email/subscribe', {email: email})
it will internally resolve to AXIOS_SERVER/email/subscribe without cause cors issues.
EXTRA: test enviroments in local using multiples .env files
you can configure .env for dev and .env.prod for production, after that in local you can use yarn build && yarn start for test your app with your production enviroment. You only need add this at the top of your nuxt.config.js file
const fs = require('fs')
const path = require('path')
if (process.env.NODE_ENV === 'production' && fs.existsSync('.env.prod')) {
require('dotenv').config({ path: path.join(__dirname, `.env.prod`) })
} else {
require('dotenv').config()
}
By definition on the Nuxt docs page what nuxt generate does is: Build the application and generate every route as a HTML file (used for static hosting).
Therefore, using proxy is out of question here. Take note that you path is not even being rewritten.
And probably the result you're looking for is not hosting.com/api/email/subscribe (wit /api), but hosting.com/email/subscribe.
Nevertheless, if you use nginx then I don't think you should use Nuxt's proxy option. Nginx is built just for that so point your API calls there and in nginx config file just declare where it should point further.

How to setup multiple Environments in CypressJs

I haven't been able to figure out how to setup my cypressJs environments correctly to test. I'd love some help.
In my index.html file, in the <script> area, i am adding a CONFIG object. In production, this config object is added in by the MVC app. This config object can have many different states (some info might be missing or different for each user). In the cypress.json file, under "env" I have this same object. I use this in the spec.js files by calling Cypress.env("CONFIG"); which works just fine.
However, I want to change the state of the app/environment variable for different tests. Is this possible?
I'd like to run a spec file using a CONFIG that has all the data and one spec file using a CONFIG object that is missing data (ex. address == null) so I can test properly under both circumstances.
Is this possible or am I doing something fundamentally wrong?
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script>
CONFIG = {
dealer: {
id: 19285,
address: "343 Somewhere Lane SpringField, TN 47383",
name: "HUDSON TRACTOR & RENTAL EQUIPMENT & OTHER HEAVY THINGS
}
</script>
</head>
</html>
cypress.json
{
"env": {
"CONFIG": {
dealer: {
id: 19285,
address: "343 Somewhere Lane SpringField, TN 47383",
name: "HUDSON TRACTOR & RENTAL EQUIPMENT & OTHER HEAVY THINGS
}
}
}
}
It is more of a best practice to run spec files against a single environment one at a time. It is either you use an overriding cypress.env.json or create 2 config files for each environment (test and prod for example) which will override env variables both set in cypress.env.json and cypress.json. https://docs.cypress.io/guides/guides/environment-variables.html#Option-2-cypress-env-json
However, if you want a quick and dirty solution to your issue above (I don't suggest this), you can set your spec files with the below:
cypress.json
{
"env": {
"CONFIG": {
"id": "19285",
"address": "343..."
},
"CONFIG_PROD": {
"id": "19285",
"address": ""
}
}
}
spec_1.js
const config = Cypess.env("CONFIG")
spec_2.js
const config = Cypress.env("CONFIG_PROD")
or just simply put them under fixture files (which I believe is more appropriate for this case):
config.json
{
"test": {
"id": "19285",
"address": "343..."
},
"prod": {
"id": "19285",
"address": ""
}
}
spec_1.js
import {test, prod} from '../fixtures/config.json'
const address = test.address
const address_null = prod.address //If you would like to run this on another 'it' test
spec_1.js
import {prod} from '../fixtures/config.json'
const address_null = prod.address

Nuxt How to set baseURL in dev or production

This seems like a simple Nuxt question, but I just can't figure it out.
When running "NPM run dev" I want to set the Axios baseURL to "localhost/api" and when running from the dist folder after "NPM run generate" I want the baseURL to be "/api".
Is there a simple solution?
This is the way to do it through the nuxt.config.js:
let development = process.env.NODE_ENV !== 'production'
module.exports = {
axios: {
baseURL: development ? 'http://localhost:3001/api' : 'https://domain/api'
},
modules: [
'#nuxtjs/axios'
],
}
As you can see, you should specify full URL of your backend, including domain (except SPA-only mode).
And don't forget to install #nuxtjs/axios as dependency to try the example.
you can also set api from outside (eg package.json scripts) by env variable
my package.json fragment (there is additional complexity when browser uses different
api url then server side rendering, still all is supported by Nuxt itself with variables API_URL_BROWSER and API_URL)
"scripts": {
"dev-prodapi": "API_URL=https://kairly.com/api nuxt",
"dev": "API_URL=http://localhost:8000/api nuxt",
"dev-spa-prodapi": "API_URL=https://kairly.com/api nuxt --spa",
"dev-spa": "API_URL=http://localhost:8000/api nuxt --spa",
"build": "API_URL_BROWSER=https://kairly.com/api API_URL=https://internal-apihost/api/ nuxt build --modern=server",
"start": "API_URL_BROWSER=https://kairly.com/api API_URL=https://internal-apihost/api/ nuxt start --modern=server",
and using no axios section in nuxt config at all.
In Nuxt 3 we can use a .env file. Here's the doc.
# .env
API_URL=http://localhost:8080/api
// nuxt.config
export default defineNuxtConfig({
runtimeConfig: {
// Private keys are only available on the server
apiSecret: '123',
// Public keys that are exposed to the client
public: {
apiUrl: process.env.API_URL
}
}
})
// MyComponent.vue
<script setup>
const config = useRuntimeConfig()
console.log(config.public.apiUrl)
</script>

rendering css by environment

I'm looking to switch to webpack on an asp.net mvc website and there's 3 different environments of this website and each environment has their own color scheme (so people know what environment they're on) so I need a way to tell webpack which css file to load and when, but not sure how to go about that.
the end result is:
/asset/styles/style.dev.css
/asset/styles/style.debug.css
/asset/styles/style.prod.css
Update
For example you have a certain theme enabled by default and you have a theme switcher control (layout page) which raises events client-side using JavaScript.
In your entry script you can attach to the changed event of the theme switcher control and do:
Dummy code: Index.js
function changedEventHandler(){
var selectedTheme = $(this).selectedValue;
switch (selectedTheme) {
case "themeA":
require("themeA")
break;
case "themeB":
require("themeB")
break;
default:
require("defaultTheme")
}
}
webpack.config.js
resolve: {
alias: {
"theme$": path.resolve(theme),
"themeA$": path.resolve("./src/css/themeA.css"),
"themeB$": path.resolve("./src/css/themeB.css"),
...
If you want three different builds each with a different theme, you can do the following:
If you want a build with themeA run: npm run themeA
If you want a build with themeB run: npm run themeB
package.json
"scripts": {
"themeA": "webpack --env.theme=themeA --mode development",
"themeB": "webpack --env.theme=themeB --mode development",
webpack.config.js
module.exports = (env) => {
var theme = "";
if (env.theme) {
theme = "./src/css/" + env.theme + ".css"
}
console.log(path.resolve(theme));
return {
entry: './src/index.js',
output: {
path: distfolder,
filename: 'bundle.js'
},
resolve: {
alias: {
"theme$": path.resolve(theme)
}
},
...
..
.
In your entry point you can do:
index.js
import "theme"