facebook / create-react-app

Set up a modern web app by running one command.
https://create-react-app.dev
MIT License
102.76k stars 26.87k forks source link

Compilation error with react-scripts 4.0.0 ( Can't resolve file ) #9870

Open masbaehr opened 4 years ago

masbaehr commented 4 years ago

latest update of react-scripts to 4.0.0 from 3.4.4 causes a compilation problem. With 3.4.4 it works, and the file exists

./src/styles/mycssfile.css
Error: Can't resolve '/images/module/filename.png' in 'D:\dev\workspace\xxxxxxxxx\src\styles'

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! xxxxxxxxxxxxxxx@1.0.0 build: `react-scripts build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the xxxxxxxxxxxxx@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\xxxxxxxxxxxxxx\AppData\Roaming\npm-cache\_logs\2020-10-23T16_16_47_530Z-debug.log
efeichen commented 4 years ago

Having a similar issue but with sass url() imports of images in the /public folder

jrr commented 4 years ago

What does the import line look like? What kind of file is it in?

I had the same url() issue as @efeichen and fixed it by moving images to src/.

efeichen commented 4 years ago

@jrr background-image: url(/contact-clip.svg); it's in a sass file in /src/scss

I'd like to move the images to src/ since I believe the relative path from the sass file to the image is working (but can't do that for images in public because of the can't import from outside src restriction), but I'd prefer not to unless absolutely necessary (I have a fairly large public folder). Thanks for the tip though!

gerard0jr commented 4 years ago

I have the same problem with SCSS and CSS files (images and fonts). In 3.x.x works but now it says it can't resolve the file in src.

hmtri1011 commented 4 years ago

I also have a problem when loading fonts from public folder. It did work in 3.x.x

myfatemi04 commented 4 years ago

I had the exact same issue, it started just today when I upgraded to 4.0.0

src: url(/fonts/josefin-sans-regular.ttf)

image

And it leads to the error:

Error: Can't resolve '../fonts/josefin-sans-regular.ttf' in '.\frontend\src\scss'

valtism commented 4 years ago

I had this error on a project that was using absolute imports. It seems like setting NODE_PATH=src/ in the .env file is no longer supported. I instead had to use a jsconfig.json as described here: https://code.visualstudio.com/docs/languages/jsconfig

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}
llamamoray commented 4 years ago

I'm also seeing this issue where we have an image in /public but it's not getting resolved when reference in css using url:

.background-image { background: url('/bg.jpg'); }

Error:

./src/styles/style.css (./node_modules/css-loader/dist/cjs.js??ref--4-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/styles/style.css) Error: Can't resolve '/bg.jpg' in '/mnt/c/git/application/src/styles'

KittyGiraudel commented 4 years ago

Can confirm this happens with url() calls in @font-face directives as well as per react-scripts@4.0.0. For instance:

@font-face {
  font-family: 'Nunito';
  font-style: normal;
  font-weight: normal;
  font-display: swap;
  src: local('Nunito Bold'), local('Nunito-Bold'), url('/fonts/nunito.woff2') format('woff2');
}
./src/index.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/index.css)
Error: Can't resolve '/fonts/nunito.woff2' in '/Path/To/Project/src'

Edit: I dug into the changelog and ~Iā€™m a little confused as to why it stopped working since css-loader and postcss-loader were not updated~ css-loader was in fact updated.

It looks like this is caused by the css-loader migration to v4: https://github.com/webpack-contrib/css-loader/commit/bc19ddd8779dafbc2a420870a3cb841041ce9c7c#diff-b335630551682c19a781afebcf4d07bf978fb1f8ac04c6bf87428ed5106870f5L128.

Originally, a root-relative path like /foo/bar.ext would remain untouched, but as per css-loader@4 it becomes processed:

Screenshot 2020-10-27 at 10 48 15 Screenshot 2020-10-27 at 10 48 31
upadmdh commented 4 years ago

To be fair, there was a warning in v3.4.4 image

But this does not solve the style issues using url() referencing images from public folder

egor-xyz commented 4 years ago

We are using another repo folder for the assets. I'm getting an error:

./src/components/HTMLPreview/HTMLPreview.module.scss (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-7-1!./node_modules/postcss-loader/src??postcss!./node_modules/resolve-url-loader??ref--5-oneOf-7-3!./node_modules/sass-loader/dist/cjs.js??ref--5-oneOf-7-4!./src/components/HTMLPreview/HTMLPreview.module.scss)

Error: Can't resolve '../../assets/iphone.svg' in '.../src/components/HTMLPreview'

How can I disable this validation and use this path? Worked in v3.4.4

x5engine commented 4 years ago

this is crazy! no testing seriously? I broke a production app before deploying thank God!

you have not even mentioned this anywhere??

iwan-uschka commented 4 years ago

this is crazy! no testing seriously? I broke a production app before deploying thank God!

you have not even mentioned this anywhere??

@x5engine What? Who is "you"?

Edit:

The šŸ‘Ž urges me to clarify that the question Who is "you"? could be replaced with Who has not even mentioned this anywhere?

KittyGiraudel commented 4 years ago

this is crazy! no testing seriously? I broke a production app before deploying thank God!

Chill. Also, this is a major update. That implies breaking changes.

x5engine commented 4 years ago

this is crazy! no testing seriously? I broke a production app before deploying thank God!

you have not even mentioned this anywhere??

@x5engine What? Who is "you"?

Who dis new phone?

I am the engine.

x5engine commented 4 years ago

this is crazy! no testing seriously? I broke a production app before deploying thank God!

Chill. Also, this is a major update. That implies breaking changes.

Yeah man I was going nuts.

Hope this gets sorted out soon šŸ™‚

GersonDias commented 4 years ago

running the same issue... waiting for clues

elylucas commented 4 years ago

If you care to dive into the react-scripts webpack setup, you can pass in the option to disable url routing to css-loader. In node_modules/react-scripts/config/webpack.config.js on line 121 change

options: cssOptions,

to

options: {...cssOptions, url: false},

Of course this entails all the issues that come around with modifying the config inside of node_modules, but hopefully this might help in a long term fix for the change in css-loader resolving the urls.

Gatix commented 4 years ago

Looking at css-loader it looks like they're not going to fix it https://github.com/webpack-contrib/css-loader/issues/1136#issuecomment-664984703

You would have to include /public to the resolve paths. I just moved my assets to /src as I didn't want to eject

ejose19 commented 4 years ago

For those used to patch-package, here's the patch based on @elylucas workaround

diff --git a/node_modules/react-scripts/config/webpack.config.js b/node_modules/react-scripts/config/webpack.config.js
index 80c6ac2..01de68e 100644
--- a/node_modules/react-scripts/config/webpack.config.js
+++ b/node_modules/react-scripts/config/webpack.config.js
@@ -117,7 +117,7 @@ module.exports = function (webpackEnv) {
       },
       {
         loader: require.resolve('css-loader'),
-        options: cssOptions,
+        options: {...cssOptions, url: false},
       },
       {
         // Options for PostCSS as we reference these options twice

Edit: Actually, that workaround only solves the issue in development (npm start), but build files are using a wrong import (they're being prefixed with ../ making it fail)

iwan-uschka commented 4 years ago

I had an issue loading fonts from within CSS. But thanks to @evilebottnawi pointing out how webpack/css-loader@4+ resolves URLs i was able to fix my issues:

/font/font.woff2 never was and never can be ./font/font.woff2, please read spec about URL resolving in CSS

I use rsuite as a UI framework. To override default icon font settings you can set a less variable @icon-font-path to suit your needs. I did that in a way which worked when using webpack/css-loader@3 but needed to be changed like displayed below to avoid issues when using webpack/css-loader@4.

/src/app/styles/rsuite/index.less:

-      @import '../../../../node_modules/rsuite/lib/styles/themes/default/core';
+      @import './node_modules/rsuite/lib/styles/themes/default/core';

-      @icon-font-path: '/fonts/rsuite-icon';
+      @icon-font-path: './fonts/rsuite-icon';

My icon font is located in /public/fonts/rsuite-icon.

Maybe this helps by getting the idea of how URLs are resolved.


Edit:

Forgot to mention how @icon-font-path is actually used:

@font-face {
  font-family: @font-family-icon;
  src: url('@{icon-font-path}/rsuite-icon-font.ttf') format('truetype'),
    url('@{icon-font-path}/rsuite-icon-font.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

Edit:

Oh my, what was i thinking... I wasn't aware of a faulty configuration because of working fallback mechanisms i didn't notice. I had to update my craco.config.js like this:

module.exports = function ({ env }) {
  return {
    style: {
      css: {
        loaderOptions: {
          url: false,
        },
      },
    },
    ...
  };
};

and had to roll back like this

+      @icon-font-path: '/fonts/rsuite-icon';
-      @icon-font-path: './fonts/rsuite-icon';

This way URLs in CSS won't be handled by webpack and you can use them like you would in regular CSS & HTML, if i got that straight.

If you do not rely on webpack handling URLs in CSS this could be an option for you.

I had to remove the . from @icon-font-path: './fonts/rsuite-icon'; because otherwise the file URL would depend on the current URL (CSS works at https://domain.tld but doesn't work at https://domain.tld/path).

darioseidl commented 3 years ago

We had the same issue when trying out CRA 4. Btw. this seems to effect a lot of people, it's been reported in multiple issues: https://github.com/facebook/create-react-app/issues/9937 https://github.com/facebook/create-react-app/issues/9992 https://github.com/facebook/create-react-app/issues/10022

orassayag commented 3 years ago

I have the same issue. Upgraded to CRA4, try to run and got error: Can't resolve './animations.scss' where the line is: @import url('./animations.scss');

coyotte508 commented 3 years ago

Here's a fix using react-app-rewired for css files with absolute links. In config-override.js, do:

const getCssLoaders = config => {
  const loaderFilter = rule => rule.loader && rule.loader.includes('/css-loader')

  let loaders = config.module.rules.find(rule => Array.isArray(rule.oneOf)).oneOf

  loaders = loaders.reduce((ldrs, rule) => ldrs.concat(rule.use || []), [])

  return loaders.filter(loaderFilter)
}

/**
 * Overrides a create-react-app configuration for the given sources.
 *
 * @param src Source path of the create-react-app project.
 */
module.exports = (config, env) => {
  // Fix url('/images/....') being processed by css-loader 4 =/
  for (const loader of getCssLoaders(config)) {
    loader.options.url = url => url.startsWith('.')
  }
   return config
}
PhamNguyenHuuThien commented 3 years ago

If you care to dive into the react-scripts webpack setup, you can pass in the option to disable url routing to css-loader. In node_modules/react-scripts/config/webpack.config.js on line 121 change

options: cssOptions,

to

options: {...cssOptions, url: false},

Of course this entails all the issues that come around with modifying the config inside of node_modules, but hopefully this might help in a long term fix for the change in css-loader resolving the urls.

Great šŸ‘Æ It's worked.

catalin-enache commented 3 years ago

Having the same problem with CRA 4.0.1: paths in css/url does not resolve and break the process

@font-face { font-family: "percolate"; src: url("/icon/percolate.eot"); / here is the error / font-weight: normal; font-style: normal; }

the assets are in public folder

yanmxa commented 3 years ago

If you care to dive into the react-scripts webpack setup, you can pass in the option to disable url routing to css-loader. In node_modules/react-scripts/config/webpack.config.js on line 121 change

options: cssOptions,

to

options: {...cssOptions, url: false},

Of course this entails all the issues that come around with modifying the config inside of node_modules, but hopefully this might help in a long term fix for the change in css-loader resolving the urls.

It works, thanks!

zachwolf commented 3 years ago

Our product needs more nuanced resolution. Setting url: false will then prevent relative file paths from resolving. Best of both worlds may be adding conditional resolution, something like:

  // ...
  options: {
    ...cssOptions,
    url: url => !url.startsWith(ā€˜/ā€™)
  },
  // ...

When compiled, /example.jpg will still be /example.jpg but ./local.jpg will be <dynamic_path>/local.<hash>.jpg.

tunggad commented 3 years ago

my solution with react-app-rewired, in webpack function in config-overrides.js, paste in following lines:

// override css loader rules due to bug: https://github.com/facebook/create-react-app/issues/9870
    const cssLoaderRules = config.module.rules[1].oneOf.filter(rule => rule.use);
    cssLoaderRules.forEach(rule => {
      const cssLoader = rule.use[1];
      cssLoader.options.url = false;
    })
    process.stdout.write('**** overrided CRA webpack css loader rules **** \n')
    process.stdout.write(JSON.stringify(cssLoaderRules)+"\n");
    process.stdout.write('\n')

It just turn off url() resolving of static assets by css-loader.

sagar7993 commented 3 years ago

I'm surprised that more people haven't realised that this is a major concern for SEO.

Lets say that you have a image file within the src folder, and you're using it within your CSS file like this -

.Profile { text-align: center; background-image: url("../../images/user/profile.png"); }

If this profile.png file is inside the src > images > user directory, then while creating a build with react-scripts, the URL generated for this file will be something like this -

https://{my-domain.com}/static/media/profile.{hash}.jpg

This {hash} value changes with every build. Therefore, if you use this in a static website, and if your website is crawled by google bot, you may see 404's reported in the google search console the next time you deploy, because Google can take several weeks before indexing your site again.

This is where an image in the public folder would have helped, because that URL will never change, and can safely remain indexed in search engines.

Gatix commented 3 years ago

Does Google even index images from CSS backgrounds?

ChrisLowe-Takor commented 3 years ago

I ran into this when upgrading a large project to the latest react-scripts. All css url('/assets') imports break due to absolute path changes in css-loader. My workaround isn't ideal but it allows compilation without major refactors.

  1. Keep all your assets in /public/assets because any jsx needs eg. <img src="/assets/file.png" />
  2. Create a new directory /src/assets.
  3. Any time you are using css (or sass) url imports copy the file into the /src/assets folder
  4. Replace absolute paths with relative ones in the css import. Eg. replace url('/assets/file.png') with url('../../assets/file.png')
alexander-akait commented 3 years ago

Please update webpack to the latest version (v4)

atiastudio commented 3 years ago

Hello, guys, I've also faced this issue after updating to 4.0.0 (or actually 4.0.1).

As a workaround I use declaring background image right in JSX, like you know: <div style={{background: 'url(/img/bg/image.jpg)'}}><div>

It works, because obviously css-loader has nothing to do with JSX files.

And it works for me, because code is arranged in a way where background can be changed depending on the section of application. In other words I use 1 component with several times with different images or maybe in different projects.

As for other projects, I'd like to join collective resentment. It seems to be strange to store images in src and I certainly don't have a teeny tiny intention to mess with webpack :-)

sagar7993 commented 3 years ago

Does Google even index images from CSS backgrounds?

It does. Images show up in google image search results.

Gatix commented 3 years ago

@sagar7993 They say otherwise: https://developers.google.com/search/docs/advanced/guidelines/google-images

donal-s commented 3 years ago

Also experiencing the same issue using react-scripts 4.0.1. The comments in https://github.com/webpack-contrib/css-loader/issues/1136 are less than helpful. I have an image in <root>/public/assets I am trying to reference in the css as

background-image: url(/assets/image.jpg);

and am getting

./src/App.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/App.css)
Error: Can't resolve '/assets/image.jpg' in '<root>/src'

The options as I see it are:

  1. Move the image into src and avoid the css-loader altogether. Would prefer not to as means changing the logical structure of my project just to workaround a problem with tooling.
  2. Use root relative urls in css ie /public/assets/image.jpg. Fails with the error message
    ./src/App.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/App.css)
    Module not found: You attempted to import ../public/assets/image.jpg which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.
  3. Eject and switch off url checking in css-loader. I lose automatic updates to react-scripts (including potentially a fix to this problem), and kinda negates the point of the changes in css-loader in the first place.
  4. Use react-app-rewired to override and do the option 3 above without ejecting as described here and here. Probably the best option, but again negates the point of the css-loader changes and means adding a layer of overrides over something that should just work.

Is there any improvement on this, and what would be needed to be changed in create-react-app/react-scripts to get url() to just work with the <root>\public directory in react apps?

ChrisLowe-Takor commented 3 years ago

@donal-s

Or option 5, see @atiastudio comment. Change any css url imports to jsx

ambrosebeavers commented 3 years ago

I am no expert but I have an easy fix to this css image issue. I used react style attribute (inline) for the image path. and did the rest of the styling in css. That way you can still support styling like background-attachment: fixed and so forth

donal-s commented 3 years ago

I'd suggest there is a difference between fix and workaround. A fix would be the tooling not inhibiting the dev from using the existing css url() feature inside a css file (as opposed to inline style attributes), and being able to reference assets where many (not all of course) would think is the most logical place (the public folder). The workarounds all share one common feature - ways to switch off or bypass the new url() checks from css-loader, which is not ideal, and also all have some level of hack around what a dev would normally do here to get an image/font/whatever referenced from css. Currently, all we have are workarounds, so I guess that's what we make do with for now :)

alexander-akait commented 3 years ago

As developer of css-loader, I want to say that css-loader supports /images/image.png in url, CRA should add src to resolver.roots (and using /images/image.png will be resolved as /src/images/image.png, it is default behavior for webpack@5)

alexander-akait commented 3 years ago

Anyway we can implement:

div {
  /** webpackIgnore **/
  background: url(/images/image.png);
}

and don't touch this url, if somebody want this, feel free to open a new issue in css-loader

donal-s commented 3 years ago

As developer of css-loader, I want to say that css-loader supports /images/image.png in url, CRA should add src to resolver.roots (and using /images/image.png will be resolved as /src/images/image.png, it is default behavior for webpack@5)

Would adding public to resolver.roots mean that adding url(/assets/image.png) correctly resolves to <rootdir>/public/assets/image.png? I think that's what we want.

alexander-akait commented 3 years ago

@donal-s Yes, just add public to resolver.roots

donal-s commented 3 years ago

I had a scan of webpack, css-loader, and react-scripts. I'm still not clear on what exactly needs to be changed where in react-scripts to fix this issue. Could someone more familiar with these projects take a look at applying @alexander-akait 's suggestion please?

peterpeterparker commented 3 years ago

To the above list of workarounds, I can add the following pragmatic one if you are facing this error while trying to load local fonts from the public folder:

Add (for the time being) the style in your index.html.

<html>
  <head>
      <style>
      @font-face {
        font-family: "Open Sans";
        font-style: normal;
        font-weight: 300;
        font-display: swap;
        src: url("/assets/fonts/open-sans-v17-latin-300.eot"); /* IE9 Compat Modes */
        src: local("Open Sans Light"), local("OpenSans-Light"), url("/assets/fonts/open-sans-v17-latin-300.eot?#iefix") format("embedded-opentype"),
          /* IE6-IE8 */ url("/assets/fonts/open-sans-v17-latin-300.woff2") format("woff2"),
          /* Super Modern Browsers */ url("/assets/fonts/open-sans-v17-latin-300.woff") format("woff"),
          /* Modern Browsers */ url("/assets/fonts/open-sans-v17-latin-300.ttf") format("truetype"),
          /* Safari, Android, iOS */ url("/assets/fonts/open-sans-v17-latin-300.svg#OpenSans") format("svg"); /* Legacy iOS */
      }

      ...
konstantinblaesi commented 3 years ago

I moved svg, png, jpg and font files from /public to /src and referenced them in jsx/scss/css files as recommended here

I have no need for the public folder right now so I am fine with this solution.

// edit : ok still issues loading images from a list of paths

devanup commented 3 years ago

Unfortunately nothing has worked for me so I moved the images directory inside the src and wherever I was using the image I had to import the images one by one by doing the following:

import img2 from '../images/img-2.jpg' import img9 from '../images/img-9.jpg' ... <CardItem src={img2} ... /> <CardItem src={img9} ... /> ... and so on.

I am very new to React, I'm learning new things everyday as I go so I'm not 100% sure if this is a proper solution, but this worked for me. I'd appreciate anybody's feedback or thoughts on this solution.

chriswininger commented 3 years ago

Hello, guys, I've also faced this issue after updating to 4.0.0 (or actually 4.0.1).

As a workaround I use declaring background image right in JSX, like you know: <div style={{background: 'url(/img/bg/image.jpg)'}}><div>

It works, because obviously css-loader has nothing to do with JSX files.

And it works for me, because code is arranged in a way where background can be changed depending on the section of application. In other words I use 1 component with several times with different images or maybe in different projects.

As for other projects, I'd like to join collective resentment. It seems to be strange to store images in src and I certainly don't have a teeny tiny intention to mess with webpack :-)

Thank you! Finally something workable. You can also add a style section to the index.html which is guaranteed to bypass all the transpilation.

This is very annoying issue

alexander-akait commented 3 years ago

Just note, the latest version of css-loader supports /* webpackIgnore: true */, i.e. you can write

a {
  /* webpackIgnore: true */
  background: url('/my/strange/path/to/image.png');
}