Ho to not load a head script in dev - vue.js

In my nuxt.config.js I have a script in the html head config.
export default {
// Target: https://go.nuxtjs.dev/config-target
target: 'static',
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'My cool Website !',
script: [
{
hid: "thesemetrics",
src: "https://unpkg.com/thesemetrics#latest",
async: true,
type: "text/javascript",
},
{ src: 'https://identity.netlify.com/v1/netlify-identity-widget.js'}
]
},
// ...
}
Is there a way to not load this script when I am in Dev Mode ?

Use the function form of head, and conditionally add these scripts based on process.env.NODE_ENV:
export default {
head() {
const productionScripts =
process.env.NODE_ENV === 'production'
? [
{
hid: "thesemetrics",
src: "https://unpkg.com/thesemetrics#latest",
async: true,
type: "text/javascript",
},
{ src: 'https://identity.netlify.com/v1/netlify-identity-widget.js'}
]
: []
return {
title: 'My cool Website !',
script: [
// other scripts to always load here
...productionScripts
]
}
},
// ...
}

Related

Docusaurus: Getting Error: Cannot mix different versions of joi schemas

When I do a npm run start I get the following:
npm run start
> my-website#0.0.0 start
> docusaurus start
[INFO] Starting the development server...
[ERROR] Error: Cannot mix different versions of joi schemas
at new module.exports (/Users/russurquhart_boomi/node_modules/#hapi/hoek/lib/error.js:23:19)
at module.exports (/Users/russurquhart_boomi/node_modules/#hapi/hoek/lib/assert.js:21:11)
at Object.exports.isSchema (/Users/russurquhart_boomi/node_modules/joi/lib/common.js:132:5)
at Object.internals.schema (/Users/russurquhart_boomi/node_modules/joi/lib/compile.js:66:16)
at Object.exports.schema (/Users/russurquhart_boomi/node_modules/joi/lib/compile.js:17:26)
at internals.Base.$_compile (/Users/russurquhart_boomi/node_modules/joi/lib/base.js:646:24)
at /Users/russurquhart_boomi/node_modules/joi/lib/types/keys.js:260:92
at Object.exports.tryWithPath (/Users/russurquhart_boomi/node_modules/joi/lib/common.js:176:16)
at internals.Base.method [as keys] (/Users/russurquhart_boomi/node_modules/joi/lib/types/keys.js:260:32)
at internals.Base.method [as append] (/Users/russurquhart_boomi/node_modules/joi/lib/types/keys.js:189:29)
[INFO] Docusaurus version: 2.1.0
Node version: v16.17.0
Here is my docusaurus.config.js file:
// #ts-check
// Note: type annotations allow type checking and IDEs autocompletion
const lightCodeTheme = require('prism-react-renderer/themes/github');
const darkCodeTheme = require('prism-react-renderer/themes/dracula');
/** #type {import('#docusaurus/types').Config} */
const config = {
title: 'Boomi Docusaurus POC',
url: 'https://your-docusaurus-test-site.com',
baseUrl: '/',
onBrokenLinks: 'throw',
onBrokenMarkdownLinks: 'warn',
favicon: 'img/favicon.ico',
// GitHub pages deployment config.
// If you aren't using GitHub pages, you don't need these.
organizationName: 'facebook', // Usually your GitHub org/user name.
projectName: 'docusaurus', // Usually your repo name.
// Even if you don't use internalization, you can use this field to set useful
// metadata like html lang. For example, if your site is Chinese, you may want
// to replace "en" with "zh-Hans".
i18n: {
defaultLocale: 'en',
locales: ['en'],
},
presets: [
[
'classic',
/** #type {import('#docusaurus/preset-classic').Options} */
({
docs: {
sidebarPath: require.resolve('./sidebars.js'),
// Please change this to your repo.
// Remove this to remove the "edit this page" links.
editUrl:
'https://github.com/facebook/docusaurus/tree/main/packages/create-docusaurus/templates/shared/',
},
blog: {
showReadingTime: true,
// Please change this to your repo.
// Remove this to remove the "edit this page" links.
editUrl:
'https://github.com/facebook/docusaurus/tree/main/packages/create-docusaurus/templates/shared/',
},
theme: {
customCss: require.resolve('./src/css/custom.css'),
},
}),
],
],
themeConfig:
/** #type {import('#docusaurus/preset-classic').ThemeConfig} */
({
navbar: {
title: 'Boomi Atmosphere',
logo: {
alt: 'Boomi Doc Site',
src: 'img/logo.svg',
},
items: [
{
type: 'doc',
docId: 'intro',
position: 'left',
label: 'Tutorial',
},
],
},
footer: {
style: 'dark',
links: [
{
title: 'Docs',
items: [
{
label: 'Atmosphere Documentation',
to: '/docs/intro',
},
],
},
{
title: 'Community',
items: [
{
label: 'Stack Overflow',
href: 'https://stackoverflow.com/questions/tagged/docusaurus',
},
{
label: 'Discord',
href: 'https://discordapp.com/invite/docusaurus',
},
{
label: 'Twitter',
href: 'https://twitter.com/docusaurus',
},
],
},
{
title: 'More',
items: [
],
},
],
copyright: `Copyright © ${new Date().getFullYear()} Docusaurus POC - Built with Docusaurus.`,
},
prism: {
theme: lightCodeTheme,
darkTheme: darkCodeTheme,
},
}),
themes: [
[
"#easyops-cn/docusaurus-search-local",
/** #type {import("#easyops-cn/docusaurus-search-local").PluginOptions} */
({
hashed: true,
language: ["en", "zh"],
highlightSearchTermsOnTargetPage: true,
explicitSearchResultPath: true,
}),
],
],
};
module.exports = config;
I got the errors after I added the docusearch-search-local plugin.
Any help is greatly appreciated!
Thanks,
Russ
I solved the issue, I had NOT installed the docusaurus-search-local item in the directory with my docusaurus files, instead I had installed it in ~/. Once I deleted it from this location, and then put it into the correct location, no problems!

webpack.config + nuxt.config,js

I am new to nuxt.
I want to add following webpack config (from docs for ckeditor vue) to nuxt.js.config
https://ckeditor.com/docs/ckeditor5/latest/installation/getting-started/frameworks/vuejs-v2.html
const path = require( 'path' );
const CKEditorWebpackPlugin = require( '#ckeditor/ckeditor5-dev-webpack-plugin' );
const { styles } = require( '#ckeditor/ckeditor5-dev-utils' );
module.exports = {
// The source of CKEditor is encapsulated in ES6 modules. By default, the code
// from the node_modules directory is not transpiled, so you must explicitly tell
// the CLI tools to transpile JavaScript files in all ckeditor5-* modules.
transpileDependencies: [
/ckeditor5-[^/\\]+[/\\]src[/\\].+\.js$/,
],
configureWebpack: {
plugins: [
// CKEditor needs its own plugin to be built using webpack.
new CKEditorWebpackPlugin( {
// See https://ckeditor.com/docs/ckeditor5/latest/features/ui-language.html
language: 'en',
// Append translations to the file matching the `app` name.
translationsOutputFile: /app/
} )
]
},
// Vue CLI would normally use its own loader to load .svg and .css files, however:
// 1. The icons used by CKEditor must be loaded using raw-loader,
// 2. The CSS used by CKEditor must be transpiled using PostCSS to load properly.
chainWebpack: config => {
// (1.) To handle editor icons, get the default rule for *.svg files first:
const svgRule = config.module.rule( 'svg' );
// Then you can either:
//
// * clear all loaders for existing 'svg' rule:
//
// svgRule.uses.clear();
//
// * or exclude ckeditor directory from node_modules:
svgRule.exclude.add( path.join( __dirname, 'node_modules', '#ckeditor' ) );
// Add an entry for *.svg files belonging to CKEditor. You can either:
//
// * modify the existing 'svg' rule:
//
// svgRule.use( 'raw-loader' ).loader( 'raw-loader' );
//
// * or add a new one:
config.module
.rule( 'cke-svg' )
.test( /ckeditor5-[^/\\]+[/\\]theme[/\\]icons[/\\][^/\\]+\.svg$/ )
.use( 'raw-loader' )
.loader( 'raw-loader' );
// (2.) Transpile the .css files imported by the editor using PostCSS.
// Make sure only the CSS belonging to ckeditor5-* packages is processed this way.
config.module
.rule( 'cke-css' )
.test( /ckeditor5-[^/\\]+[/\\].+\.css$/ )
.use( 'postcss-loader' )
.loader( 'postcss-loader' )
.tap( () => {
return {
postcssOptions: styles.getPostCssConfig( {
themeImporter: {
themePath: require.resolve( '#ckeditor/ckeditor5-theme-lark' )
},
minify: true
} )
};
} );
}
};
My nuxt config is simply current, i did add some modules like axios,boostrap vue and auth to it.
export default {
// Disable server-side rendering: https://go.nuxtjs.dev/ssr-mode
ssr: false,
// Target: https://go.nuxtjs.dev/config-target
target: "static",
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: "spa",
htmlAttrs: {
lang: "en",
},
meta: [
{ charset: "utf-8" },
{ name: "viewport", content: "width=device-width, initial-scale=1" },
{ hid: "description", name: "description", content: "" },
{ name: "format-detection", content: "telephone=no" },
],
link: [{ rel: "icon", type: "image/x-icon", href: "/favicon.ico" }],
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: ["~/assets/less/colors.less"],
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/bootstrap
"bootstrap-vue/nuxt",
"#nuxtjs/axios",
"#nuxtjs/auth-next",
],
auth: {
redirect: {
login: "/login",
logout: "/login",
callback: false,
home: "/",
},
strategies: {
laravelSanctum: {
provider: "laravel/sanctum",
url: "http://localhost",
user: {
property: false, // <--- Default "user"
autoFetch: true,
},
// endpoints: {
// login: { url: "api/login", method: "post" },
// logout: { url: "api/auth/logout", method: "post" },
// user: { url: "api/user", method: "get" },
// },
},
},
},
axios: {
credentials: true,
baseURL: "http://localhost", // Used as fallback if no runtime config is provided
// withCredentials: true,
headers: {
accept: "application/json",
common: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS",
"Access-Control-Allow-Credentials": true,
},
delete: {},
get: {},
head: {},
post: {},
put: {},
patch: {},
},
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {},
router: {
middleware: ["auth"],
},
};
And if config like that can be combine with webpack config for ckeditor , is that right way to do so ?
Or should i separate this and build in another direcrory with another sepparate webpack config?
I guess you're looking for that one: https://nuxtjs.org/docs/configuration-glossary/configuration-build#extend
Could create an external config and import it into this object or directly do that inline as most people do.
There are quite some answers on Stackoverflow anyway on how to achieve specific parts of the configuration, feel free to give it a search to find out what you need.

Nuxt.js Oauth sometimes crashes whole webpage

I have created Nuxt.js application, I decided to build in Nuxt/auth module, everything works fine in web browsers, but somethimes when user navigates with mobile browser my application is crushed, simply it don't respond nothing, also there is no api calls, but after one refresh everything works fine, I can not guess what's happening, I could not find anything in the resources available on the Internet.
const axios = require('axios')
export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'app',
htmlAttrs: {
lang: 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
],
script: [
// { src: "//code-eu1.jivosite.com/widget/UoBOrMfSmm", async: true },
]
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [ '~/assets/css/transition.css', '~/assets/css/errors.css' ],
pageTransition: "fade",
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
{ src: "~/plugins/star-rating", ssr: false },
{ src: "~/plugins/mask", ssr: false },
{ src: "~/plugins/rangeSlider", ssr: false },
{ src: "~/plugins/vueSelect", ssr: false },
{ src: "~/plugins/vuelidate", ssr: false },
],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
[ '#nuxtjs/google-analytics', {
id: 'xxx'
} ]
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/bootstrap
'bootstrap-vue/nuxt',
'#nuxtjs/axios',
'#nuxtjs/toast',
'#nuxtjs/auth-next',
[ 'nuxt-lazy-load', {
defaultImage: '/spin2.gif'
} ],
[ 'nuxt-facebook-pixel-module', {
/* module options */
track: 'PageView',
pixelId: '',
autoPageView: true,
disabled: false
} ],
'nuxt-moment',
'#nuxtjs/robots',
'#nuxtjs/sitemap'
],
moment: {
locales: ['ru', 'en']
},
toast: {
position: 'top-center',
},
robots: [
{
UserAgent: '*',
Disallow: ['/user', '/admin'],
},
],
axios: {
baseURL: 'https://api.test.com/', // Used as fallback if no runtime config is provided
},
sitemap:{
exclude:[
'/user',
'/admin',
'/admin/*',
'/user/*',
],
defaults: {
changefreq: 'daily',
priority: 1,
lastmod: new Date()
},
routes: async () => {
const { data } = await axios.get('https://api.test.com/api/cars/all')
return data.map((product) => `https://test.com/product/${product.id}/${product.name}`)
}
},
loading: {
color: '#F48245',
height: '4px'
},
target: 'server',
/* auth */
auth: {
plugins:[
{ src: "~/plugins/providers", ssr:false},
],
redirect: {
login: '/',
logout: '/',
home: '/',
callback: '/callback'
},
strategies: {
local: {
token: {
property: 'user.token',
},
user: {
property: false
},
endpoints: {
login: { url: 'api/login', method: 'post' },
logout: { url: 'api/logout', method: 'post' },
user: { url: 'api/user', method: 'get' }
},
},
facebook: {
endpoints: {
userInfo: 'https://graph.facebook.com/v6.0/me?fields=id,name,picture{url}',
},
redirectUri:'xxx',
clientId: '184551510189971',
scope: ['public_profile', 'email'],
},
google: {
responseType: 'token id_token',
codeChallengeMethod: '',
clientId: 'xxx',
redirectUri: 'https://test.com/callback',
scope: ['email'],
},
},
cookie: {
prefix: 'auth.',
},
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {},
};
This is my plugins directory file, where i am handling client oauth process.
export default async function ({ app }) {
console.log('auth executed')
if (!app.$auth.loggedIn) {
return
} else {
console.log('auth executed inside loop')
const auth = app.$auth;
const authStrategy = auth.strategy.name;
if (authStrategy === 'facebook') {
let data2 = {
fb_token: auth.user.id,
first_name: auth.user.name
}
try {
const response = await app.$axios.$post("/api/oauth", data2);
await auth.setStrategy('local');
await auth.strategy.token.set("Bearer " + response.user.token);
await auth.fetchUser();
} catch (e) {
console.log(e);
}
} else if (authStrategy === 'google') {
let dataGoogle = {
google_token: auth.user.sub,
first_name: auth.user.given_name,
last_name:auth.user.family_name
}
try {
const response = await app.$axios.$post("/api/oauth", dataGoogle);
await auth.setStrategy('local');
await auth.strategy.token.set("Bearer " + response.user.token);
await auth.fetchUser();
} catch (e) {
console.log(e);
}
}
}
}
For any issues related to DOM hydration, you can check my answer here: https://stackoverflow.com/a/67978474/8816585
It does have several possible cases (dynamic content with a difference between client side and server side rendered template, some random functions, purely wrong HTML structure etc...) and also a good blog article from Alex!

Why do I get this error only when my application is in production?

I am developing an application with NuxtJS and SSR, I am also using axios and auth modules. Everything works perfectly in localhost, but later when I upload the application to the host (Vercel) and try to log in, it gives me the 405 error. Does anyone know why this happens? The server is created with express
Error: Request failed with status code 405
at t.exports (237de42.js:2)
at t.exports (237de42.js:2)
at XMLHttpRequest._.onreadystatechange (237de42.js:2)
This is my nuxt.config.js file:
export default {
// Target: https://go.nuxtjs.dev/config-target
target: 'static',
ssr: true,
// Global page headers: https://go.nuxtjs.dev/config-head,
modules: [
'#nuxtjs/axios',
'#nuxtjs/auth-next',
'~/modules/api/index.js'
],
env:{
baseUrl: process.env.BASE_URL
},
axios: {
credentials: true,
https: true,
baseURL: 'https://www.encontrarhogar.com.ar/',
init(axios) {
axios.defaults.withCredentials = true
}
},
head: {
title: 'Encontrar Hogar',
htmlAttrs: {
lang: 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{ rel: 'stylesheet', href: '/normalize.css' },
{ rel: 'stylesheet', href: "https://unpkg.com/swiper/swiper-bundle.min.css" }
],
script: [
{ src: "https://kit.fontawesome.com/57d52ad1ee.js", crossorigin: "anonymous" },
]
},
loading: {
color: 'black',
height: '8px',
continuous: true
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [
'#/assets/css/index.css'
],
auth: {
strategies: {
local: {
token: {
property: 'token'
},
user: {
property: 'user'
},
endpoints: {
login: { url: '/server/api/usuarios/login', method: 'post', propertyName: 'data' },
user: { url: '/server/api/usuarios/mi-perfil', method: 'get', propertyName: 'data' },
logout: { url: '/server/api/usuarios/logout', method: 'delete' }
}
}
}
},
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: ['~/plugins/swiper.js'],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true
}

Why can't I create routes with parameters in my serverMiddleware in nuxt?

I'm having a problem configuring the serverMIddleware property, everything works perfectly, but I can't create any other route than the initial route
Mi nuxt.config.js file:
export default {
// Target: https://go.nuxtjs.dev/config-target
target: 'static',
ssr: true,
// Global page headers: https://go.nuxtjs.dev/config-head,
modules: [
'#nuxtjs/axios',
'#nuxtjs/auth-next',
// '~/modules/api/index.js'
],
serverMiddleware:[
{ path: '/api', handler: '~/api/index.js'},
],
axios: {
baseURL: 'http://localhost:3000/',
},
head: {
title: 'Encontrar Hogar',
htmlAttrs: {
lang: 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Encontra tu nuevo hogar en chacabuco. Todas las propiedades e inmuebles de Chacabuco en un mismo lugar' },
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{ rel: 'stylesheet', href: '/normalize.css' },
{ rel: 'stylesheet', href: "https://unpkg.com/swiper/swiper-bundle.min.css" }
],
script: [
{ src: "https://kit.fontawesome.com/57d52ad1ee.js", crossorigin: "anonymous" },
]
},
loading: {
color: 'black',
height: '8px',
continuous: true
},
css: [
'#/assets/css/index.css'
],
auth: {
cookie:{
options:{
secure: true
}
},
strategies: {
local: {
token: {
property: 'token'
},
user: {
property: 'user'
},
endpoints: {
login: { url: '/api/usuarios/login', method: 'post', propertyName: 'data' },
user: { url: '/api/usuarios/mi-perfil', method: 'get', propertyName: 'data' },
logout: false
}
}
}
},
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: ['~/plugins/swiper.js'],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true
}
/api/index.js file:
const bodyParser = require('body-parser')
const app = require('express')()
app.get('/api/:id?', (req, res) => res.send('hello'))
module.exports = app
If I try to create endpoints like the one that I will leave below, the only thing I get when making the get requests through the browser or postman is a 404 not found response, I do not understand what I am configuring wrong.
app.get('/api/products', (req, res) => res.send('products'))
Did you call http://localhost:3000/api/youridhere ?
According to your configuration and serveMiddleware, your link should be http://localhost:3000/api/api/youridhere
You have static target, change to "server" if you want serverMiddleware to work