webpack.config + nuxt.config,js - vue.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.

Related

Vite.js Dynamic Image Loading Fails In Production

I have a problem in importing dynamic assets in production mode. When I ran the development environment everything works fine and the assets loads...but when I build the Vue.js application, assets won't load and I gets below error:
TypeError: URL constructor: ../../../assets/images/name.png is not a valid URL.
how can I fix this issue?
Vue Example
<img :src="findImageFromNumber(card.cartNumber)" alt="image" width="25" />
function findImageFromNumber(number: string) {
const name = identify(number).english;
const path = new URL('../../../assets/images/banks/' + name + '.png', import.meta.url);
return path.href
}
Vite.js Config
export default defineConfig({
root: './',
resolve: {
alias: {
'/#/': path.resolve(__dirname, 'src')
},
},
publicDir: 'assets',
mode: 'production',
build: {
outDir: 'dist',
sourcemap: true,
target: ['es2019', 'safari11', 'firefox60', 'chrome61', 'node12'],
chunkSizeWarningLimit: 500,
minify: false,
emptyOutDir: true,
assetsInlineLimit: 2048,
rollupOptions: {
output: {
entryFileNames: `assets/[name].js`,
chunkFileNames: `assets/[name].js`,
assetFileNames: `assets/[name].[ext]`,
manualChunks(id) {
if (id.includes('vue')) {
return 'react';
} else if (id.includes('node_modules')) {
return 'vendor';
}
},
},
}
},
plugins: [
vue(),
legacy({
polyfills: ['es.promise.finally', 'es/map', 'es/set'],
modernPolyfills: ['es.promise.finally']
})
],
})
Note: Everything works fine in development and it only fails in production...
Assets is your public dir. Should it just be /assets/images/banks, according to the docs?

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!

Ho to not load a head script in dev

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
]
}
},
// ...
}

Can not config Tailwind in NuxtJS

i use "#nuxtjs/tailwindcss": "^2.0.0" for my Nuxt App.
After install, it created a tailwind.config.js file. And then, i added a little code as you could see below:
module.exports = {
theme: {},
variants: {},
plugins: [],
purge: {
enabled: process.env.NODE_ENV === 'production',
content: [
'components/**/*.vue',
'layouts/**/*.vue',
'pages/**/*.vue',
'plugins/**/*.js',
'nuxt.config.js',
],
},
options: {
important: true,
},
};
I want all the Tailwind's class have important, but it weren't.
inside the tailwin's class
What i did wrong?
Most probably you are running NODE_ENV=production so its purging unused classes
Setting purge.enabled=false will do what you want. I don't recommend setting it false. If a class is used purge won't remove the class. As you are not using most of the classes in HTML they are getting removed.
module.exports = {
theme: {},
variants: {},
plugins: [],
purge: {
enabled: false, // DONT DO THIS IN PRODUCTION
content: [
'components/**/*.vue',
'layouts/**/*.vue',
'pages/**/*.vue',
'plugins/**/*.js',
'nuxt.config.js',
],
},
options: {
important: true,
},
};
If I look at the documentation the important key should be at the root of export :
// tailwind.config.js
module.exports = {
important: true,
}
instead of
// tailwind.config.js
module.exports = {
options: {
important: true,
}
}
I know what messed up.
So turn out that the problem was PostCSS
And, another thing is that in older version, the important was in options, but now it placed at the root
// tailwind.config.js
module.exports = {
important: true,
}

vue-devtools always disabled with nuxt.js

I am creating a new project using nuxt.js v2.3.0. When I run npm run dev in my IDE console everything compiles correctly but when I go to the page I get the following error: Nuxt.js + Vue.js is detected on this page. Devtools inspection is not available because it's in production mode or explicitly disabled by the author.
Here is my nuxt.config.js file:
const pkg = require('./package');
module.exports = {
mode: 'spa',
dev: true,
/*
** Headers of the page
*/
head: {
title: pkg.name,
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: pkg.description }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
],
bodyAttrs: {
class: 'h-100'
},
htmlAttrs: {
class: 'h-100'
}
},
/*
** Global CSS
*/
css: [
'#/assets/app.css'
],
/*
** Plugins to load before mounting the App
*/
plugins: [
'~/plugins/vue-notifications',
'~/plugins/vue2-sidebar'
],
/*
** Nuxt.js modules
*/
modules: [
// Doc: https://github.com/nuxt-community/axios-module#usage
'#nuxtjs/axios',
// Doc: https://bootstrap-vue.js.org/docs/
'bootstrap-vue/nuxt',
// Doc: https://auth.nuxtjs.org/getting-starterd/setup
'#nuxtjs/auth',
'#nuxtjs/toast',
'#nuxtjs/font-awesome'
],
/*
** Axios module configuration
*/
axios: {
baseURL: 'http://users:8000'
},
/*
** Auth module configuration
*/
auth: {
strategies: {
password_grant: {
_scheme: 'local',
endpoints: {
login: {
url: '/oauth/token',
method: 'post',
propertyName: 'access_token'
},
logout: 'api/logout',
user: {
url: 'api/user',
method: 'get',
propertyName: false
},
},
tokenRequired: true,
tokenType: 'Bearer'
}
},
redirect: {
login: "/account/login",
logout: "/",
callback: "/account/login",
user: "/"
},
},
/*
** Toast configuration
*/
toast: {
position: 'top-right',
duration: 2000
},
loading: {
name: 'chasing-dots',
color: '#ff5638',
background: 'white',
height: '4px'
},
/*
** Router configuration
*/
router: {
middleware: ['auth']
},
/*
** Build configuration
*/
build: {
/*
** You can extend webpack config here
*/
extend(config, ctx) {
}
}
};
If I was running in production mode then I could understand but I'm not. I would expect vue-devtools to be running as normal.
I had to add the following to the nuxt.config.js:
vue: {
config: {
productionTip: false,
devtools: true
}
}
Now devtools shows up
tl:dr:
vue.config.devtools = true in my nuxt.config.js does not work for me.
I ran nuxt generate --devtools, then nuxt start and opened the website in my browser. Doing so I could use the Vue-Devtools.
After that I now can still use the Vue-Devtools, even when running nuxt dev and no vue.config.devtools flag set in my nuxt.config.js
Full story
So enabling the devtools flag in vue.config as in the accepted answer did not work for me either.
I first tried forcing the Vue-Devtools as described here. Adding a Plugin to set the window properties as described in the link. But without luck.
Digging in the Nuxt code I noticed the --devtools flag for the generate command and wanted to see if the Vue-Devtools work at all with Nuxt.
After running nuxt generate --devtools, then serving the application with nuxt start, I finally could access the devtools.
And now, even when running nuxt dev they are still accessible. And I don't have vue.config.devtools set at all in my nuxt.config.js. Weird. But maybe that helps someone.
More context: I am running Nuxt in spa mode, with target static as I don't have a Node server in the Backend and just want to build an SPA.
As #joshua jackson stated worked for me, while devtools: true did NOT.
Version:
Nuxt.js v2.10.0
Vue v2.6.10
vue: {
config: {
productionTip: false,
devtools: true
}
}
in nuxt.config.js
export default {
mode: 'universal',
devtools: true,
...
}
Hope this help someone stopped here.
I have struggled to get this working and tried all of the steps written here.
My issue was I had to run the server on a specified port.
server: {
port: process.env.PORT || 5000,
host: '0.0.0.0'
},
Adding this to nuxt.config.js solved the problem.