Angular fails to fetch CSS file on navigation to nested route - css

When directly navigating to a child component in prod mode (ng serve --prod) it fails to load the CSS file, trying to fetch it from a nested path. For instance, navigating to "localhost:4200/doc/" the CSS Request URL is:
localhost:4200/doc/styles.6eab038f040a1c7c7ed6.css.
The error that is given:
Refused to apply style from 'http://localhost:4200/doc/styles.6eab038f040a1c7c7ed6.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
When accessing the root (localhost:4200) the CSS is loaded correctly. If you then navigate to the child component through the app itself, the problem does not occur.
It only occurs in prod mode, not on the development server. Changed nothing to the regular settings regarding styles.css, it is situated in the default folder.
"styles": [
"src/styles.css"
],
Anyone has any idea how this problem could be caused?
Edit
Found out that the problem lies in navigating to nested routes (helped by the reply of mikegross).
On a route without a nested parameter the problem does not occur, but on a route with a nested parameter (for instance 'doc/:id') it does.
Router module:
const routes: Routes = [
{ path: '', redirectTo: 'list', pathMatch: "full"},
{ path: 'list', component: ListComponent},
{ path: 'doc/:id', component: DocumentComponent},
{ path: '**', redirectTo: ''},
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Update (feb. 28)
Since it was still a small project I generated a new angular project, installed same dependencies and literally copy pasted the code.
Although I have no idea why, in the new project the problem does not occur. The only difference lies in a minor version bump (ng 9.0 to 9.1).

I know this is an older post, but I got around this by using query parameters instead of route parameters. example:
const routes: Routes = [
{ path: '', redirectTo: 'list', pathMatch: "full"},
{ path: 'list', component: ListComponent},
{ path: 'doc', component: DocumentComponent},
{ path: '**', redirectTo: ''},
];
(I removed the :id from "doc/:id")
Navigate to the route:
route this._router.navigate(['/doc'],{queryParams: {id: id}});
Then retrieve the query parameter:
this._activatedRoute.snapshot.queryParamMap.get('id');

Coming late to the party. I had the same error with React in 2022.
Initially, I declared the CSS file with a relative path, as follows:
<link rel="preload" href="./style/Avenir-Light.woff2" as="font" type="font/woff2" crossorigin>
After changing it to an absolute path, it worked
<link rel="preload" href="/style/Avenir-Light.woff2" as="font" type="font/woff2" crossorigin>
Hope it helps future readers.

Related

NextJs image component and jsonplaceholder external url

In a nextJS project, I want to use jsonplaceholder with /photos route.
When I try to insert image or thumbnails into Image component like bellow, I have an error.
import Image from 'next/image'
<Image src="https://via.placeholder.com/150/92c952" width={150} height={150} />
Server Error
Error: Invalid src prop (https://via.placeholder.com/150/92c952) on
next/image, hostname "via.placeholder.com" is not configured under
images in your next.config.js See more info:
https://nextjs.org/docs/messages/next-image-unconfigured-host
When I check documentation, for external sources, and considering I'm using recent version (13), I should convert my next.config.js like that :
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'via.placeholder.com',
port: '',
pathname: '/**',
},
],
},
}
module.exports = nextConfig
But I still have an error, maybe because of a null port. But I don't know which port via.placeholder.com is using :(
Trying old next version with code bellow doesn't work either:
images: {
domains: ['via.placeholder.com'],
},
Thanks in advance
You don't need to use curly braces when using a string literal for the image src. You can just do something like <Image src="https://cdn.architect.io/logo/horizontal.png" width={400} height={59.5} alt="Architect Logo" />. Also if you're loading the image from a server using https, the port should be 443. For more context, I added the following in my next.config.js in order to load the image that I referenced:
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'cdn.architect.io',
},
],
},
Also, when trying to load a .png from via.placeholder.com, be sure to include the file type. For example:
<Image src="https://via.placeholder.com/150/92c952.png" width={150} height={150} alt="Placeholder" />
Despite the settings mentioned in other answers (I tested new ones images. remotePatterns and legacy ones images.domains), none was working.
After upgrading from v13.0.7 to v13.1.6 it works now :)

How to enable NextJS "next/future/image"?

I'm trying to use Next.js next/future/image experimental component.
I upgraded the Next.js version in package.json to "next": "^12.2.0".
Here's my next.config.js file:
/** #type {import('next').NextConfig} */
const nextConfig = {
strictMode: true,
experimental: {
images: {
allowFutureImage: true,
},
},
images: {
domains: ['firebasestorage.googleapis.com',],
},
};
module.exports = nextConfig;
It doesn't allow me to use this feature. Here's the error message in the browser console:
Error: The "next/future/image" component is experimental and may be subject to breaking changes. To enable this experiment, please include `experimental: { images: { allowFutureImage: true } }` in your next.config.js file.
For Next v13 users:
I believe next/future/image is now the default Image component. So no additional work necessary! Just import and use
import Image from 'next/image'
For Next v12.3 users(like the author of this question)
You don't need to add anything to the config to use future/image. The future image is now stable. Just use it directly by importing
import Image from 'next/future/image'
In fact, adding an images property to the config will cause an error, since the config schema has been updated. So don't do that.
// next.config.js
module.exports = {
experimental: {
images: { // This will cause an error
allowFutureImage: true,
},
},
}
The solution that worked for me was to add the experimental rule and stop the nextjs server and restart it. Then it would start working
module.exports = {
experimental: {
images: {
allowFutureImage: true,
},
},
}
I'm currently working with NextJS version 12.3.1, and if I enable it in the next.config.js then I get an ugly warning on the terminal. So it is best to just import Image from "next/future/image" and not add the config to avoid the Warning. Hope others using 12.3.1 find this useful ( using future/image gets rid of the nasty wrapper divs/spans around the )
Warning I'm seeing with config in place:
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
warn - Invalid next.config.js options detected:
- The value at .experimental has an unexpected property, images, which is not in the list of allowed properties (adjustFontFallbacks, amp, appDir, browsersListForSwc, cpus, craCompat, disableOptimizedLoading, disablePostcssPresetEnv, esmExternals, externalDir, fallbackNodePolyfills, forceSwcTransforms, fullySpecified, gzipSize, incrementalCacheHandlerPath, isrFlushToDisk, isrMemoryCacheSize, largePageDataBytes, legacyBrowsers, manualClientBasePath, modularizeImports, newNextLinkBehavior, nextScriptWorkers, optimizeCss, optimisticClientCache, outputFileTracingRoot, pageEnv, profiling, proxyTimeout, runtime, scrollRestoration, serverComponents, sharedPool, sri, swcFileReading, swcMinify, swcMinifyDebugOptions, swcPlugins, swcTraceProfiling, urlImports, workerThreads).
See more info here: https://nextjs.org/docs/messages/invalid-next-config
warn - You have enabled experimental feature (images) in next.config.js.
warn - Experimental features are not covered by semver, and may cause unexpected or broken application behavior. Use at your own risk.

vue 3 with vite - lazy loading with dynamic path problem

I am using Vue 3 with Vite with VueRouter
let test_Route = 'Test';
const routes = [
{ path: '/' , name:'default' ,component: () => import('#/views/login.vue') },
{ path: '/Test' , name:'Test' , component: () => import(`#/views/${test_Route}/login.vue`) }
]
console.log(routes)
//--the rest of the routing code
the problem is Vue does not import the Test component
when log routes - it does not process the template string #/views/${test_Route}/login.vue it treats it like its a normal string
so how to fix this
Please check my answer there: Vue lazy loading does not work in Vite as did in Vue-CLI
The reason behind this, is to help static analysis to avoid a possible shoot in the foot. So to import your component, the imports must start with ./ or ../.
All imports must start relative to the importing file.

Fonts not found: React-slick + nextjs

I am trying to use react-slick inside a NextJs project. The carousel works fine but I have some problems importing the fonts used in the css files.
I have tried the following:
npm install slick-carousel
and imported the css in the component where the react-slick module is used:
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
When i run the application I get the following error in the network log:
404 Not found on both slick.woff and slick.ttf
I found some other responses where they have added the following to the next.config.js:
const withSass = require('#zeit/next-sass')
const withFonts = require('next-fonts');
const withCss = require('#zeit/next-css')
module.exports = withFonts(withSass(withCss({
env: {
environment: 'development'
},
enableSvg: true,
webpack: function (config) {
config.module.rules.push({
test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000,
name: '[name].[ext]'
}
}
})
return config
},
cssLoaderOptions: {
url: false
},
})))
I've tried both with and without the withFonts module.
If i add the direct urls in the <Head>it will work:
<Head>
<>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick-theme.min.css" />
</>
</Head>
But will rather get the fonts to work instead.
Anyone with some suggestion to get the fonts to load in Nextjs?
Not a solution, but I solved it another way.
As I am going to style most of the stuff that requires fonts, i decided to just copy the css from slick-carousel and delete all font references. Override arrow left, arrow right as well as the dots.
Not a solution on the problem stated above but fix my issue.
Pasting both files in public directory with next font installed should resolve 404 error

How does NuxtJS css extraction work for generated static websites?

I am trying to generate a static website out of my (minimal) code with Nuxt. In that code, I integrate in particular the tailwindcss toolkit as well as vue2-leaflet. Upon
nuxt generate
I get two css files, one for the tailwindcss css and the other for the leaflet css. While the former file is fine and contains everything I need, the latter is pretty sparse:
.leaflet-tile-pane{z-index:200}#-webkit-keyframes leaflet-gestures-fadein{to{opacity:1}}#keyframes leaflet-gestures-fadein{0%{opacity:0}to{opacity:1}}
Of course, that makes my map render in a pretty strange way, because most of the css is missing. Here's my current nuxt.config.js:
module.exports = {
mode: 'universal',
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' }
]
},
css: [
],
plugins: [
{ src: '~plugins/leaflet.js', mode: 'client' }
],
buildModules: [
'#nuxtjs/tailwindcss'
],
modules: ['#nuxtjs/apollo', 'nuxt-purgecss', ['nuxt-i18n', i18n]],
[...]
build: {
extractCSS: true,
}
}
Getting rid of the extractCSS ends up incorporating all the relevant css into the index.html. It works, but then I get the following error:
ERROR Webpack mode only works with build.extractCSS set to *true*. Either extract your CSS or use 'postcss' mode
I'm not sure I understand how that whole css extraction works. Could someone enlighten me? Why is it not working with extractCSS: true? How can I make it work? Why is it working in SPA mode but not in static mode?
You are using nuxt-purgecss which is using purgecss to strip unused CSS.
purgecss do scan HTML (or vue) files for CSS classes in use and then strip unused classes from final CSS bundle.
You can take a look at default purgecss configuration used by nuxt-purgecss here. The paths lists the paths purgecss will scan for CSS usage.
Because you are not using most of the leaflet css directly (in your components), its is necessary to configure purgecss to don't remove leaflet's css.
You can do that by whitelisting (btw not sure if "comment" method will work in Vue\Nuxt)
You can read more here and here
Not tested!!
// nuxt.config.js
{
purgeCSS: {
whitelistPatterns: [/leaflet/, /marker/]
}
}
Regarding the error message
Error message is from nuxt-purgecss module - it is clearly documented here
I don't have deep knowledge of Nuxt build process. So I just assume from the docs that extractCSS: true will use extract-css-chunks-webpack-plugin to extract all CSS to separate CSS file, while (default) extractCSS: false will use PostCSS to extract all CSS and put it directly into the <style> tag of rendered page.
All of that doesn't matter IMHO because the root problem is the use of purgecss and the solution is to configure it correctly to whitelist leaflet CSS classes....

Resources