Reference file in public folder from CSS in create-react-app - node.js

I am using creat-react-app (CRA) and simply want to include a png file placed in the public folder via CSS (I keep all image files there).
Now I am trying to reference this image via CSS (I only added the background-image line to a freshly generated CRA app):
.App-header {
background-color: #222;
height: 150px;
padding: 20px;
color: white;
background-image: url("../public/example.png");
}
You attempted to import example.png which falls outside of the project src/ directory
How do I reference the image file from within the CSS-file without copying somewhere inside /src? I also don't want to eject the application and get rid of the error message.
Edit: This question is different from The create-react-app imports restriction outside of src directory because it does not show how to solve this problem at a CSS level. The proposed solution is to add the style inside the JavaScript file which I don't want to do.

Just use a / before the name, this will make it relative to the output root, which includes anything in the public folder (provided the finished hosted application is served at the root of a domain).
so for the question asked above:
.App-header {
background-color: #222;
height: 150px;
padding: 20px;
color: white;
background-image: url("/example.png");
}
the critical part being
/example.png
refers to a file, example.png, that is in the public folder (served at the root level)
Could also be relative:
one could also use
./example.png
provided that the css file was also imported from the public/build directory, this would be relative to the css file and not depend on being served at the domain root, but typically in CRA webpack will bundle the CSS and it may or may not be loaded from this location. (you could import it in the html file directly using rel tag with the %PUBLIC_URL%/Styles.css macro)

In my case, to access the images from css/scss, had to move the images directory as well as fonts, to the src directory. After which i was able to refer them in the css/scss files directly,
background-image: url("/images/background.jpg");
references:
https://github.com/facebook/create-react-app/issues/829
https://create-react-app.dev/docs/using-the-public-folder/

there is a special page about the /public folder in the official documentation:
https://create-react-app.dev/docs/using-the-public-folder/
Here is how you should refer to the public folder:
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
or
render() {
return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;
}
BUT, you can't use those solution in a css file. So you'll have to precise the ressource from the js files:
const MyComp = () => {
return <div style={{ backgroundImage: `${process.env.PUBLIC_URL}/img/logo.png` }} />;
}

I was using "public" folder but it says here to use images inside "src" folder:
https://create-react-app.dev/docs/using-the-public-folder/
"Normally we recommend importing stylesheets, images, and fonts from
JavaScript."

Remove the extra .. in the relative path. :)

Use "./image.png".
The logic behind is that the css file you will place the code in, will be part of index.html when the app is finished, built and deployed.

The only way that helped me is adding full URL-adress to the image path. So this one can help:
background-image: url("http://localhost:3000/background.jpg");

Using the URL directly doesn't work for my environment, for me I needed to specify the path TO the image FROM the current directory.
eg;
/src/styles/style.css
cursor: url("../../public/images/image.png"), auto;
/src/public/images/image.png

background-image: url("http:/images/pexels-photo-1.jpg");

Related

My html cant find my linked javascript event though its in the correct directory, very stumped here

where I link index.js
<script src="/assets/js/index.js"></script>
Folder Directory is such
assests
-css
--style.css
-js
--index.js
enter image description here
Error Im getting
index.html:25 GET file:///assets/js/index.js net::ERR_FILE_NOT_FOUND
I guess you are using an express app(by the tag in question). The static resources such as your javascript, css, images, etc. should be inside the public folder which gets served on running the application. Could you try moving the assets folder inside the public folder and then have a script tag pointing to that resource.
Maybe it helps to remove the first slash:
<script src="assets/js/index.js"></script>
Or startend with a dot
<script src="./assets/js/index.js"></script>

loading a css file from 'assets' directory in a NUXT layout

in a nuxt layout (default.vue) I want to load an image and a css file from assets folder
the image loaded successfully, but the css file not, why?
/layouts/default.vue
<template>
<img src="~assets/photo.jpg" />
<!-- converted to /_nuxt/assets/photo.jpg and loaded successfully -->
</template>
<script>
export default{
head:{
link: [ { rel: 'stylesheet', href: '~assets/style.css' }]
}
}
</sript>
when I view the source code:
<link href="~assets/style.css" />
and it fails to be loaded
also navigating to http://localhost:3000/_nuxt/assets/style.css faild, but http://localhost:3000/_nuxt/assets/photo.jpg successed
note:
I don't want to put style.css in 'static' folder as I want to load it via webpack css-loader to add caching hashes
The image src is automatically compiled by Vue, you can see more at relative path import; From the docs:
all asset URLs such as <img src="...">, background: url(...) and CSS
#import are resolved as module dependencies.
For a custom path besides cases listed above, you need to explicitly require the path for it to be compiled as a path to static assets:
export default{
head:{
link: [{ rel: 'stylesheet', href: require('~assets/style.css') }]
}
}

Ionic 3 background-image svg not appering in Ionic View

I'm developing an App using Ionic 2. Right now, I've this style:
ion-content {
background-image: url('/assets/images/orange-background.svg');
background-repeat: no-repeat;
background-size: 101%;
}
When I ionic serve this works fine, but when I upload a new version to Ionic View channel, this example doesn't work neither any example of background-image with an .svg.
I already tried Ionic - svg does not appear but didn't work.
Thanks in advance.
Edit 1
I already tried this url in background-image:
assets/images/orange-background.svg
/assets/images/orange-background.svg
../assets/images/orange-background.svg
./assets/images/orange-background.svg
None of this worked :'(
Edit 2
I just discovered that this problem only happens on iOS.
Maybe the url is incorrect. In the .css files: url ('../assets/images/orange-background.svg').
In other case, did you make the difference: In Whindows an image.SVG will works when you test the app in a browser but wont in Linux (Also Android). It seems that an image.SVG is the same as image.svg in windows.
I had a similar problem, and I realized that the file was called "Background.svg", and on my css I had:
background-image: url("../assets/imgs/background.svg");
Once I changed the file name to "background.svg" the problem was fixed.

Jekyll - Front Matter defaults not working

Using Jekyll 2.5.3, I've tried to set default values in _config.yml (I'm just playing around to get a feel for it right now). I'm trying to set a default layout right now on a site I'm serving locally. I have set --watch and that's working fine. When I set any YAML defaults in _config.yml, Jekyll does not apply the defaults at all.
Here's the config file I'm currently using:
name: jekyll test
description: test server
url: "http://localhost:4000"
markdown: rdiscount
permalink: pretty
defaults:
-
scope:
path: ""
values:
layout: "default"
The default layout is not applied to any page. I've tried with the title as well, with the same result.
My index.md:
---
title: index
----
{{ page.title }}
My default.html:
<style>
body {
background-color: black;
color: white;
font-family: "Helvetica", Arial, sans-serif;
}
</style>
<body>
{{ content }}
</body>
The default layout works fine when put into the YAML Front Matter of the index page itself, the main reason I'm looking for this is so I can apply default.html to 404 pages. The other elements in config.yml aren't giving me any trouble. Is there something I've done wrong?
Fixed it myself - --watch does not listen for changes to files that aren't included in the site itself (namely _config.yml, which is used to generate pages at runtime). To apply changes to the site configuration, I just had to restart Jekyll and feel a little stupid.
Bottom line: I have learned my lesson. If changes don't appear to be saving, turn it off and on again before asking.
I had this issue. There was an extra space after toggling a comment '#' tag in the frontmatter of my index.md:
---
#title: index
title: index2
----
and I fixed it by removing the space:
---
#title: index
title: index2
----

grunt-usemin block paths not relative to html file?

Having a lot of trouble understand how paths are treated at various points in the configuration and usage of grunt-usemin.
I've got the following repo layout, where the repo root will also be the web app root:
/dashboard/index.html
/Gruntfile.js
/vendor/...some 3rd party CSS and JS...
So the index.html file -> somedomain.com/dashboard/index.html.
The index.html file includes some CSS and JS assets from the /vendor folder. I have grunt configured to put build output in a build folder:
/build/dashboard/index.html
In the index.html file, I have usemin blocks wrapped around all the CSS link and JS script tags:
<!-- build:css(.) app.min.css -->
<!-- build:js(.) app.min.js -->
I had to specify an "alternative search path" with "(.)" so that a script tag for "/vendor/backbone.js" will find it in the right place. Until I did that, it was looking for /dashboard/vendor/backbone.js.
I want the output of processing the CSS/JS assets to be output to build/dashboard/app.min.css and build/dashboard/app.min.js, and included by index.html using a simple relative "app.min.css/js" path.
The problem is, grunt-usemin seems to be using the "app.min.*" path I'm specifying for both contexts in a way that makes it impossible for them to work together:
1) It treats the path as relative to the build directory for purposes of creating the file; the files end up in build/app.min.css and build/app.min.js.
2) It treats the path as relative to the index.html file for purposes of generating the new link/script tags; the browser loads build/dashboard/index.html, which then tries to load "app.min.css", which maps to build/dashboard/app.min.css.
Is there a solution?
I'm really late to the party, but I was also extremely frustrated by this issue and didn't find any satisfying fixes or work arounds. So I worked out some pretty dirty tricks to hopefully better work around this issue. So I'd like to share it with you.
First of all, let's quickly review why this issue happens. When usemin generates output JS/CSS files, it performs a simple path join between your dest directory and the output directory you specified in your usemin block. So if dest is build and usemin block is
<!-- build:css(.) app.min.css -->
then it joins build with app.min.css to spit out the output file at build/app.min.css
But then the usemin task simply replaces the path in your block to you end up with
<link rel="stylesheet" href="app.min.css"/>
which is now linking the wrong directory since your HTML file is under build/dashboard/index.html
So my work around revolves around this idea: what if dest directory is relative to where the HTML file is located? Wouldn't that solve this issue? So given the above example, what if dest is build/dashboard? You can see that it will spit out the output file location and link it correctly. Keep in mind that you are supposed to create a copy task to copy over your HTML files, so make sure your HTML file is copied to build/dashboard/index.html as before.
Of course, the next question would be what if I have HTML files in multiple directories? Wouldn't that be super painful and unintuitive to create a useminPrepare target for each directory, where HTML files could reside? This is why I create a very special grunt task just for working around this issue while I was creating my own grunt scaffolding. I call it useminPreparePrepare Yes, it's deliberately named stupidly, because I'm hoping to remove this thing altogether one day when usemin people make an actual fix for this issue.
As its name suggests, this is a task to prepare useminPrepare configs. It does exactly what I described above. All of its configs mirror useminPrepare configs (in fact, most of them are simply copied over to useminPrepare), with one exception: you need to specify a src directory to identify the root directory of all of your sources so that it can generate relative path to the HTML files. So in your example src: "." will be fine. To use useminPreparePrepare, import it into your build first (you may want to just copy and paste my code, I don't mind), rename your useminPrepare task to useminPreparePrepare and add src property that I just mentioned. Make sure you run useminPreparePrepare with whatever target you like, then immediately run useminPrepare without specifying target so that all of its targets are run. This is because useminPreparePrepare will generate one target for each directory relative to where HTML files are found and copies over your configs for the useminPreparePrepare target your ran. This way, your config can simply look for all HTML files.
Example
"useminPreparePrepare": {
// Search for HTML files under dashboard even though src is .
// because we want to avoid including files generated under build directory.
html: "dashboard/**/*.html",
options: {
src: ".",
dest: "build",
...
"usemin": {
html: ["build/**/*.html"],
...
"copy": {
html: {
files: [{
expand: true,
src: ["dashboard/**/*.html"],
dest: "build"
}
]
},
...
Hope this helps! Have a good day.
EDIT: I realized that given the above example, if you actually include all HTML files from current directory, you will include the generated HTML files too if they are not cleaned ahead of time. So either you clean them ahead of them or look under dashboard directory. I'd recommend separating src and dest directories so that config could look a lot more intuitively.
I don't like it, but the only way I've found to make it work so far is to specify a full path:
<!-- build:css(.) /dashboard/app.min.css -->
<!-- build:js(.) /dashboard/app.min.js -->
The leads to the app* files being in /build/dashboard alongside index.html (which is where I want them), and index.html ends up with the following tags:
<link rel="stylesheet" href="/dashboard/app.min.css">
<script src="/dashboard/app.min.js"></script>
It means the dashboard app is now acutely aware of it's location within the whole, so you can't just rename or relocate it's position in the tree without updating those paths.

Resources