So first of all, I have 2 env file,
env.dev
BASE_URL=xxxx
.env
BASE_URL=xxxx
I tried to load BASE_URL from my env file, so I use nuxt/dotenv to load env file on nuxt.config.js, like this,
buildModules: [
'#nuxtjs/eslint-module',
['#nuxtjs/dotenv', { filename: '.env' + process.env.ENV }]
],
modules: [
'#nuxtjs/axios',
'#nuxtjs/auth',
'#nuxtjs/dotenv'
],
axios: {
baseURL: process.env.BASE_URL,
redirectError: {
401: '/login',
403: '/login',
404: '/notfound'
}
}
But when I try to hit API login, it's always pointing to BASE_URL on .env.
What am I do wrong?
Here I wrote a quick answer on how to user env variables: https://stackoverflow.com/a/67705541/8816585
Here is an answer on how to use a specific .env.dev file: https://github.com/nuxt-community/dotenv-module/issues/59#issuecomment-660646526
yarn add -D #nuxtjs/dotenv
In nuxt.config.js
modules: ['#nuxtjs/dotenv'],
...
buildModules: [
['#nuxtjs/dotenv',
{ filename: '.env.' + process.env.ENV }
]
],
In package.json (your probably missed this one)
"scripts": { "dev": "ENV=dev nuxt" }
And finally, do not forget to add them all to your .gitignore file.
Meanwhile, this way of working is not the recommended way as stated in the official dotenv project: https://github.com/motdotla/dotenv#should-i-have-multiple-env-files
Related
I have a simple Nuxt ssr app with a serverMidlleware handling one api endpoint (/api/contact). To deploy the app I am using pm2.
Running the app in development and in production (locally without pm2) everything works fine. Deploying it on a basic ubuntu server using pm2, the api endpoint becomes unreachable (404 not found).
As pointed out here, the middleware is not included in the .nuxt build. So, I made sure to copy the api directory (where my middleware is located) too.
for pm2 deployment, ecosystem.config.js:
module.exports = {
apps: [
{
name: 'App',
exec_mode: 'cluster',
instances: 'max',
script: './node_modules/nuxt/bin/nuxt.js',
args: 'start'
}
]
}
and inside nuxt.config.js:
serverMiddleware: [
{ path: '/api/contact', handler: '~/api/contact.js' }
]
As only the deployment via pm2 fails, I assume the other files are not of interest. I am assuming this must be related to some sort of pm2 config to find the api folder.
Following my answer here solved the issue here too.
You probably had something missing in your nuxt.config.js file
export default {
ssr: true,
target: 'server',
modules: [
'#nuxtjs/axios',
],
serverMiddleware: [
{ path: '/api', handler: '~/server-middleware/rest.js' },
],
}
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
I have a regular Vue.js project (created using v3.0.3) that uses WebSockets. Also in the project root is the /server folder which has the Node.js code that houses the multi-player aspect and socket code.
However, since the folder /server is independent of the /src folder from the Vue.js project, how do I make use of the Vue CLI webpack config and add babel compiling (using Webpack) to appropriately compile both the /src
https://cli.vuejs.org/guide/webpack.html#simple-configuration
I was able to import babel-cli and just compile/run like so:
./node_modules/.bin/nodemon --exec babel-node --presets env,stage-2 server.js
and it worked.
Actually, you should add .babelrc file and declare presets, env options and etc into it.
I don't know why you don't eject, because of access to webpack configuration. In the webpack config, you can declare your src folder or exclude other folders like node_modlules or your custom server folder.
For example, see webpack config for your issue:
module.exports = {
~~~
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: ['node_modules', 'server'],
use: [
{
loader: 'babel-loader',
},
],
},
~~~
And see a sample .babelrc file:
{
"presets": [
"es2015",
"es2016",
"es2017",
"env",
"stage-0"
],
"plugins": [
"transform-class-properties",
"transform-object-rest-spread",
[
"transform-runtime",
{
"helpers": true,
"polyfill": true,
"regenerator": true
}
]
],
"env": {
"development": {
"compact": false
}
}
}
Then you should use your webpack commands to build:
webpack -p --config ./webpack.production.config.js
I am relatively new to express + webpack, so i am unclear wether this is intended or not, and if not, how to properly configure it. the question is around the additional asset & entry point created when using the mini-css-extract-plugin.
webpack config:
Extract = require('mini-css-extract-plugin');
path = require('path');
Write = require('write-file-webpack-plugin');
module.exports = {
mode: 'development',
entry: {
demo_scripts: path.resolve('server', 'scripts', 'demo.js'),
demo_styles: path.resolve('server', 'styles', 'demo.css')
},
output: {
path: path.resolve('.tmp'),
filename: '[name].js'
},
plugins: [new Write(), new Extract()],
module: {
rules: [
{
test: /\.js$/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['babel-preset-env']
}
}
]
},
{
test: /\.css/,
use: [
{
loader: Extract.loader
},
{
loader: 'css-loader'
}
]
}
]
}
};
webpack output
Asset Size Chunks Chunk Names
demo_scripts.js 3.91 KiB demo_scripts [emitted] demo_scripts
demo_styles.css 36 bytes demo_styles [emitted] demo_styles
demo_styles.js 3.89 KiB demo_styles [emitted] demo_styles
Entrypoint demo_scripts = demo_scripts.js
Entrypoint demo_styles = demo_styles.css demo_styles.js
my question is, why is demo_styles.js being created? although the css is being extracted, it almost seems like webpack is still creating a bundled js with css, but when i view that file, the only line in it is
eval("// extracted by mini-css-extract-plugin\n\n//# sourceURL=webpack:///./server/styles/demo.css?");
can anyone help explain what is going on here?
UPDATE
if i remove the demo_styles entry point, and configure it via the plugin init, no css asset is built.
({
plugins: [
new Write(),
new Extract({
filename: 'demo_styles.css'
})
]
});
Asset Size Chunks Chunk Names
demo_scripts.js 3.91 KiB demo_scripts [emitted] demo_scripts
Entrypoint demo_scripts = demo_scripts.js
the repo for this is here (note the express branch) https://github.com/brewster1134/bumper/tree/express
There are two workarounds for your problem. For both of them, you need to change the entry point of the Webpack configuration file. I, personally, prefer the first option.
Option 1:
Change the entry to the following:
entry: {
demo: [
path.resolve('server', 'scripts', 'demo.js'),
path.resolve('server', 'styles', 'demo.css'),
]
}
This will generate the following outputs (based on the filename you provided for Extract class and output section:
demo.js
demo_styles.css
Option 2:
For this option, you need to remove the CSS file from the entry point and import it inside the JS file:
webpack.config.js
...
entry: path.resolve('server', 'scripts', 'demo.js'),
...
demo.js
import './../styles.demo.css'
//rest of your JS codes
This solution will generate the same output as Option1
Webpack pulls everything into a js file, then MiniCssExtractPlugin takes it out of that file, leaving a blank js file with // extracted by mini-css-extract-plugin.
My solution is to group your css and js in the entry section of webpack.config.js
entry: {
demo: {
import: [ path.join("server", "scripts", "demo.js"), path.join("server", "styles", "demo.css") ],
filename: "demo.js", // outputs demo.js, demo.css to your output directory
},
main: {
import: [ path.join("server", "scripts", "main.js"), path.join("server", "styles", "main.css") ],
filename: "main.js", // outputs main.js, main.css to your output directory
},
}
Also, so naming works well, use this for your plugins section:
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css"
}),
],
Adjust the bundles "demo" and "main", as well as paths accordingly.
Please remove demo_styles from your entry point this is creating demo_styles.js.
instead you can inject css file like this:
plugins: [
new MiniCssExtractPlugin({
filename: 'demo_styles.css',
}),
Let me know if the issue still persists, Happy to help
I have made a website using NUXT that needs SEO
When I use www.xml-sitemaps.com website to see if it can find all my pages, it only finds the home page, and none of the other routes. When I try other NUXT demo websites it finds them all.
My robots.txt file looks like:
User-agent: *
Disallow: /profile/
Sitemap: https://www.example.com/sitemap.xml
I am using #nuxtjs/sitemap to generate the sitemap.xml that ends up looking something like this:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
<url> <loc>https://www.example.com/about</loc> </url>
<url> <loc>https://www.example.com/</loc> </url>
</urlset>
And if this helps, my nuxt.config.js looks like:
module.exports = {
/*
** Headers of the page
*/
head: {
title: 'Title',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Title' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
mode: 'spa',
loading: { color: '#3B8070' },
build: {
/*
** Run ESLint on save
*/
extend (config, { isDev, isClient }) {
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
},
css: [
'~/assets/main.css'
],
modules: [
'#nuxtjs/pwa',
[
'#nuxtjs/sitemap', {
generate: true,
hostname: 'https://www.example.com',
exclude: [
'/profile'
]
}
]
],
plugins: [
'~/plugins/uikit.js',
'~/plugins/fireauth.js'
],
manifest: {
name: 'Title',
lang: 'en'
},
router: {
middleware: 'router-auth'
},
vendor: [
'firebase',
'uikit'
]
}
I'm the creator of the nuxt sitemap module.
Your sitemap-module configuration is set in the wrong section.
Please, update your nuxt.config.js:
modules: ['#nuxtjs/pwa', '#nuxtjs/sitemap'],
sitemap: {
generate: true,
hostname: 'https://www.example.com',
exclude: [
'/profile'
]
},
plugins: [
Then run npm run generate.
Finally check your generated sitemap.xml in the \dist\ folder.
(If you have an other issue or question, you may open an issue on github project: https://github.com/nuxt-community/sitemap-module/issues)
It's important to understand what's going on with different Nuxt.js modes. Read the explanation about server side rendering in the Nuxt.js Guide, where they explain the difference between the three modes the framework can be configured to work in:
Universal (with server side rendering, so that when any page is rendered, that page will be served with all HTML rendered (SEO and crawler friendly mode)
SPA (Single Page Application) which will serve up the HTML skeleton together with css and javascript bundles, which will only be unbundled to create the initial DOM in the browser. Cool for intranet apps, bad for SEO.
Static generation of all pages (pre-rendering) so that the site can be served up in any shared hosting as simple HTML.
Once the concepts are clear, you can try changing the "mode" property in your Nuxt.js configuration file from "SPA" to "Universal", together with the other suggestion regarding xml sitemap configuration in the same nuxt.config.js file.
Additionally, you can try out and learn about different configurations by either using:
The Nuxt.js starter template discussed in the Installation Guide.
Something like Create Nuxt App that, once installed via npm install -g create-nuxt-app allows you to see how many different configurations are automatically set up for you.
Since you are in SPA mode you will not get much success with SEO, if you can run in universal mode then you will see full benefit of nuxt/vue.
See this website I did with Nuxt in universal mode.