Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
masbaehr opened this issue Oct 23, 2020 · 71 comments
Open

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

masbaehr opened this issue Oct 23, 2020 · 71 comments

Comments

@masbaehr
Copy link

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
Copy link

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

@jrr
Copy link
Contributor

jrr commented Oct 23, 2020

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
Copy link

efeichen commented Oct 23, 2020

@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
Copy link

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
Copy link

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

@myfatemi04
Copy link

myfatemi04 commented Oct 24, 2020

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
Copy link

valtism commented Oct 25, 2020

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
Copy link

llamamoray commented Oct 26, 2020

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
Copy link

KittyGiraudel commented Oct 27, 2020

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: webpack-contrib/css-loader@bc19ddd#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
Copy link

upadmdh commented Oct 28, 2020

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
Copy link

egor-xyz commented Oct 28, 2020

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

This comment has been minimized.

@iwan-uschka
Copy link

iwan-uschka commented Oct 28, 2020

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
Copy link

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

This comment has been minimized.

@x5engine
Copy link

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
Copy link

running the same issue... waiting for clues

@ianschmitz ianschmitz added this to the 4.0.1 milestone Oct 28, 2020
@elylucas
Copy link

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
Copy link

Gatix commented Oct 30, 2020

Looking at css-loader it looks like they're not going to fix it webpack-contrib/css-loader#1136 (comment)

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
Copy link

ejose19 commented Oct 31, 2020

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)

nancy134 added a commit to nancy134/realty-app that referenced this issue Nov 1, 2020
@iwan-uschka
Copy link

iwan-uschka commented Nov 5, 2020

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).

@iansu iansu modified the milestones: 4.0.1, 4.0.2 Nov 23, 2020
@darioseidl
Copy link

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:
#9937
#9992
#10022

@orassayag
Copy link

orassayag commented Nov 29, 2020

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');

prestonlimlianjie pushed a commit to isomerpages/isomercms-frontend that referenced this issue Apr 22, 2021
In recent commits, we upgraded our react-scripts version from 3.4.4
to 4.0.3. This is because CRA (create-react-app) v3 uses an outdated
version of eslint (facebook/create-react-app#8849). This introduced
a bug related to the css-loader library, which can no longer resolve
assets in the public folder:
- facebook/create-react-app#9870 (comment)
- webpack-contrib/css-loader#1136 (comment)

This commit fixes this bug by moving the referenced image to the
relevant sub-directory in the src directory.
prestonlimlianjie added a commit to isomerpages/isomercms-frontend that referenced this issue Apr 22, 2021
* fix: outdated packages with vulnerabilities

* feat: install eslint and initiate config

* feat: install prettier and set prettier options

* feat: install eslint-config-prettier

* feat: install eslint-plugin-prettier

* chore: reformat eslint config

* feat: add @trivago/prettier-plugin-sort-imports, define preferred import order

* fix: css-loader file resolution bug introduced by CRA v4

In recent commits, we upgraded our react-scripts version from 3.4.4
to 4.0.3. This is because CRA (create-react-app) v3 uses an outdated
version of eslint (facebook/create-react-app#8849). This introduced
a bug related to the css-loader library, which can no longer resolve
assets in the public folder:
- facebook/create-react-app#9870 (comment)
- webpack-contrib/css-loader#1136 (comment)

This commit fixes this bug by moving the referenced image to the
relevant sub-directory in the src directory.

* chore: temporarily disable eslint

* chore: add more files and folders to .prettierignore

* chore: upgrade prettier-plugin-sort-imports to 2.0.2

fixes trivago/prettier-plugin-sort-imports#22

* chore: temporarily disable prettier

* chore: remove prettier config temporarily

* chore: remove jsx-a11y references temporarily

* temporarily remove import/prefer-default-export reference

Co-authored-by: jiehao <jiehao@open.gov.sg>
Co-authored-by: Preston Lim <prestonlimlianjie@gmail.com>
alexanderleegs pushed a commit to isomerpages/isomercms-frontend that referenced this issue Apr 29, 2021
* fix: outdated packages with vulnerabilities

* feat: install eslint and initiate config

* feat: install prettier and set prettier options

* feat: install eslint-config-prettier

* feat: install eslint-plugin-prettier

* chore: reformat eslint config

* feat: add @trivago/prettier-plugin-sort-imports, define preferred import order

* fix: css-loader file resolution bug introduced by CRA v4

In recent commits, we upgraded our react-scripts version from 3.4.4
to 4.0.3. This is because CRA (create-react-app) v3 uses an outdated
version of eslint (facebook/create-react-app#8849). This introduced
a bug related to the css-loader library, which can no longer resolve
assets in the public folder:
- facebook/create-react-app#9870 (comment)
- webpack-contrib/css-loader#1136 (comment)

This commit fixes this bug by moving the referenced image to the
relevant sub-directory in the src directory.

* chore: temporarily disable eslint

* chore: add more files and folders to .prettierignore

* chore: upgrade prettier-plugin-sort-imports to 2.0.2

fixes trivago/prettier-plugin-sort-imports#22

* chore: temporarily disable prettier

* chore: remove prettier config temporarily

* chore: remove jsx-a11y references temporarily

* temporarily remove import/prefer-default-export reference

Co-authored-by: jiehao <jiehao@open.gov.sg>
Co-authored-by: Preston Lim <prestonlimlianjie@gmail.com>
gweiying added a commit to isomerpages/isomercms-frontend that referenced this issue Apr 30, 2021
* Add linting and formatting tools (#378)

* fix: outdated packages with vulnerabilities

* feat: install eslint and initiate config

* feat: install prettier and set prettier options

* feat: install eslint-config-prettier

* feat: install eslint-plugin-prettier

* chore: reformat eslint config

* feat: add @trivago/prettier-plugin-sort-imports, define preferred import order

* fix: css-loader file resolution bug introduced by CRA v4

In recent commits, we upgraded our react-scripts version from 3.4.4
to 4.0.3. This is because CRA (create-react-app) v3 uses an outdated
version of eslint (facebook/create-react-app#8849). This introduced
a bug related to the css-loader library, which can no longer resolve
assets in the public folder:
- facebook/create-react-app#9870 (comment)
- webpack-contrib/css-loader#1136 (comment)

This commit fixes this bug by moving the referenced image to the
relevant sub-directory in the src directory.

* chore: temporarily disable eslint

* chore: add more files and folders to .prettierignore

* chore: upgrade prettier-plugin-sort-imports to 2.0.2

fixes trivago/prettier-plugin-sort-imports#22

* chore: temporarily disable prettier

* chore: remove prettier config temporarily

* chore: remove jsx-a11y references temporarily

* temporarily remove import/prefer-default-export reference

Co-authored-by: jiehao <jiehao@open.gov.sg>
Co-authored-by: Preston Lim <prestonlimlianjie@gmail.com>

* Fix/resource color (#430)

* fix: resource page header changed to bg-secondary

* fix: using isResourcePage to determine page header

* Fix/rearrange layout (#427)

* fix: simplify directoryFile utils for retrieve and update

* fix: update methods using directoryFile utils

* fix: introduce FolderReorderingModal

* fix: refactors FolderContent

* fix: update params for FolderContentItem

* fix: fix breadcrumb display

* fix: add propTypes for FolderReorderingModal

* fix: add Cancel button to FolderReorderingModal

* fix: updates draggable-id for React dnd

* fix: updates dropdown button behavior for reordering

* fix: updates copy text

* fix: updates copy text

* fix: updates variable naming for directory file output

* refactor: clean up ProtectedRoute and LoginContext (#431)

* refactor: clean up ProtectedRoute and LoginContext

* refactor: make LoginContext testable

create 3 exports: LoginContext itself, LoginProvider, LoginConsumer

* refactor: make route selector testable in App.jsx

* refactor: group routing components

* feat: add basic routing tests

* refactor: move __tests__ folder to correct place

Required for jest to find the test files

* style: delete unnecessary div

* refactor: make exports more obvious for LoginContext.js

* refactor: delete duplicate route

* chore: add rest of routing tests

* style: remove unused declarations

* Fix/fine-tune react-query settings (#389)

* fix: turn off refetching on window focus for useQuery

This commit sets the `refetchOnWindowFocus` flag for the useQuery
on the following layouts/components to be `false`:
- PageSettingsModal
- EditNavBar
- EditPage

The reason we turn off this flag is because these pages involve user
changes - with this flag on, any unsaved changes by the user would
be overwritten by the refetched data.

This commit also sets the
- `refetchOnReconnect`
- `refetchInterval`
- `refetchIntervalInBackground`
flags to be false for the same reasons explained above.

* fix: invalidate queries after mutation

This commit adds cache invalidation of all our GET queries
(the useQuery invocations) after we perform a mutation. This
allows us to reset our cache in a more granular manner, as opposed
to simply setting the cache time for our GET queries to be 0.

Additionally, this commit also adds a PAGE_SETTINGS_KEY constant
to replace the string literal that was being used as the query key
for the PageSettingsModal.

Refer to the following documentation for more details:
- https://react-query.tanstack.com/guides/query-invalidation
- https://react-query.tanstack.com/guides/invalidations-from-mutations

* feat: standardize output of GET API calls to return resp.data

This commit standardizes the output of our GET API functions to
return resp.data instead of just the response from the api call.
resp.data is a better choice as we are able to use that in
dependency arrays, whereas the resp object pointer always changes,
which will trigger the useEffect every time even if the object data
hasn't actually changed.

* fix: load yaml content when reading directory file

* feat: disable useQuery if component tracks local state

As per our discussion (refer to meeting minutes here:
https://docs.google.com/document/d/1br6T6wVX0KrcA3nwQEo7OhUrcT4veLnaz0vByEXjVvo/edit#heading=h.hyx8t36v9z3n)
we will be discussing our `useQuery` functions if there are changes
to the local state that are being tracked, to avoid refetching
behavior from overwriting local changes.

* fix: rebase errors

* fix: invocation of LoginContext

* Fix: rebase errors

* Fix: update resource category and resource page get calls to return data directly

* Refactor: use invalidateQueries instead of passing refetch function for CollectionPagesSection

* Fix: error when retrieving page settings

* Fix: rebase errors

* Fix: invalidate query instead of reload when changing page settings

* Feat: add success toast when changing settings

* Fix: change folder naming to use invalidation instead of reload

* Fix: invalidate correct resource folder key

* Fix: update success toast messages

* Fix: remove log statement

* Fix: add successtoast

Co-authored-by: Alexander Lee <alexander@open.gov.sg>

* fix: pass parameters to wrapped components (#439)

* fix: fixes toast popup on item select, folder deletion modal (#440)

* fix: fixes toast popup on item select, folder deletion modal

* fix: add condition for folder deletion

Co-authored-by: kwajiehao <31984694+kwajiehao@users.noreply.github.com>
Co-authored-by: jiehao <jiehao@open.gov.sg>
Co-authored-by: Preston Lim <prestonlimlianjie@gmail.com>
Co-authored-by: Alexander Lee <alexander@open.gov.sg>
Co-authored-by: Alexander Lee <alexleegs@gmail.com>
@iansu iansu modified the milestones: 4.1, 4.2 May 26, 2021
@polaroidkidd
Copy link

The separation of content between src and public

The public folder was supposed to serve files during development which

  1. Are served from a separate server during the production mode
  2. Should not be included in a production build

Is this not the case anymore?

@maciejgaciarz
Copy link

If anyone wishes to keep files in public folder (as for various reasons) see my answer on SO how to make it work with CRA 4.0.x and craco

https://stackoverflow.com/questions/65058233/cant-resolve-scss-file-after-upgrade-to-create-react-app-4-0-1/68020124#68020124

@mghazanfar
Copy link

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)

Worked for my finally after 3 days long struggle. Thanks

@polaroidkidd
Copy link

@mghazanfar this will disable all url resolving.

We wanted only to not resolve urls from /resources url so the following worked for us

...
options: {...cssOptions, url: url => !url.startsWith("/.resources")},
....

That way other urls that you use inside your scss files in components will still resolve.

@nihaltowfiq
Copy link

./src/components/Home/Header/Header.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/components/Home/Header/Header.css)
Error: Can't resolve '/images/header-bg.png' in 'C:\Users\nihal\Desktop\PlayGround\TRANSFORM\Creative-Agency\src\components\Home\Header'

I GOT THE SAME ERROR. I CAN'T ACCESS public FOLDER IMAGES FROM ANY .css FILE.
I USE THAT IMAGE IN ::before CSS SELECTOR FOR BACKGROUND IMAGE;

@tdiluzio
Copy link

having this issue with "react-scripts": "4.0.3" (not ejected), any idea if the issue is on the roadmap?

@IBTechRaj
Copy link

Thanks to chriswininger. I could resolve my issue following his advice.

I changed the syntax of quotes from url('/images/img-2.jpg') to 'url(/images/img-2.jpg)' in my App.css file

@nsdonato
Copy link

nsdonato commented Nov 16, 2021

I wanted to load a background image from Tailwind, but I got the error "./src/index.css Error: Can't resolve '/img...", CRA comes with "@craco/craco": "^6.4.0", and "react-scripts": "4.0.3", for these versions, it doesn't work to load the image with the relative path. Performing @ejose19's workaround works but it is not ideal. My solution was to downgrade the versions of "@craco/craco":"^5.6.0" and "react-scripts":"^3.3.0-next.38" and it worked without problems. What a way to waste time...

@femi-Zedev
Copy link

femi-Zedev commented Dec 2, 2021

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)

Worked for my finally after 3 days long struggle. Thanks

This works localy but if you deploy your app with netlify for instance it would crash because the node_modules is no shipped to the server before builds.
What finaly worked for me was setting url for loaderOptions to false in craco.config.js as @iwan-uschka mentionned.
Like so
module.exports = { style: { postcss: { plugins: [ require('tailwindcss'), require('autoprefixer'), ], }, css: { loaderOptions: { url: false, } } }, }
#9870 (comment)

@polaroidkidd
Copy link

I can't believe this is still an issue. Setting url: false will simply disable resolving anything from the public directory.

This will solve the issue given the following folder structure:

project
  --src
      --styles
        --main.scss // imports images or svgs from the public/resources dir
  --public
    --resources
      --images
        - my-awesome-logo.svg
  1. Install patch-package as a devDependency: yarn add -D patch-package
  2. In your node_modules folder navigate to /node_modules/react-scripts/config/webpack.config.js and find line
    options: cssOptions and replace it with
    options: {...cssOptions, url: url => !url.startsWith("/resources")},
    (This will ensure that any import which starts with /resources will get resolved from the public directory.)
  3. Navigate back to the project root and run yarn patch-package react-scripts. This will create a new directory called patches which should contain a git-patch for the react-scripts package.
  4. In your package.json add the following to the scripts block:
...
"scripts": {
  ...
  "postinstall": "patch-package"
  ...
  }
...

This will run the patches after every install. You can (and should) commit these files to the repository.

@dharmick
Copy link

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)

This worked for me. So /path-to-file in the url() will be resolved as /src/path-to-file

@gh640
Copy link

gh640 commented Dec 18, 2021

react-scripts 5.0.0 was released and this issue was not addressed.

https://github.com/facebook/create-react-app/releases/tag/v5.0.0

Some excerpts from the official docs related with this issue:

Using the Public Folder | Create React App

With webpack, using static assets like images and fonts works similarly to CSS.

You can import a file right in a JavaScript module. This tells webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the src attribute of an image or the href of a link to a PDF.

Adding Images, Fonts, and Files | Create React App

Normally we recommend importing stylesheets, images, and fonts from JavaScript. The public folder is useful as a workaround for a number of less common cases:

I used the "patch" approach in some projects for a while but finally switched to the relative path approach (by moving images into src/ directory).

@polaroidkidd
Copy link

@gh640

I used the "patch" approach in some projects for a while but finally switched to the relative path approach (by moving images into src/ directory).

Doesn't this mean that they'll be included in the production build? My understanding was that the public folder served assets which

a) are available in prod environments and thus don't need to be included in the dev build.
b) are required during the development process

@gh640
Copy link

gh640 commented Dec 21, 2021

@polaroidkidd

Doesn't this mean that they'll be included in the production build? My understanding was that the public folder served assets which

a) are available in prod environments and thus don't need to be included in the dev build.
b) are required during the development process

Thank you for your comment. Personally speaking, I don't think it's an intended use case but I'm not sure, it's just my understanding...

@Shine18
Copy link

Shine18 commented Jan 12, 2022

Moving assets (at least those read by css-loader) from public to src is not a big deal and is the "recommended way" of Adding Images, Fonts, and Files as stated in the CRA documentation: https://create-react-app.dev/docs/adding-images-fonts-and-files

Just hit this issue today, when i upgraded react-scripts in my app. I am moving forward with this one. I think this is the best way to go now, because adding more and more configurations ( which will be fixed in the near future ) would not be the best idea.
Thanks man.

@alihesari
Copy link

I followed @Gatix comment:

I just moved my assets to /src

Moving assets (at least those read by css-loader) from public to src is not a big deal and is the "recommended way" of Adding Images, Fonts, and Files as stated in the CRA documentation: https://create-react-app.dev/docs/adding-images-fonts-and-files

For example, when you import font files from src, they are seemlessly copied in the production build:

Capture d’écran 2021-04-04 à 11 37 23 Capture d’écran 2021-04-04 à 11 36 10

Note that the hash part (e.g. 504a4f4a), included in the built files name, seems to be based on the file content, so it shouldn't break assets caching after each build deployment.

This solution solved the issue for me. I think this is the best way.

@Morta1
Copy link

Morta1 commented Oct 16, 2022

This is still an issue for me

jxjj added a commit to jxjj/jjohnson.me that referenced this issue Dec 19, 2022
- Cannot import from public folder, so move to src folder

- Reorg components into folders

facebook/create-react-app#9870
@Drew-Daniels
Copy link

@alihesari 's solution worked perfectly for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests