Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom webpack config with ionic v4 and react?

I have set up a project using ionic framework v4 with React and wish to add a webpack loader to allow importing graphql queries from .graphql files, as described here.

I can't find any official documentation on how to change anything relating to webpack (for example, nothing here), and existing answers on the subject seem to apply only to using Angular or v2/v3 of ionic.

The Apollo docs describe an alternative way of solving this for Create-React-App (which I may try as a workaround), but I might wish to change webpack config in other ways, so I am also asking how to solve this question more generally.

like image 837
contrebis Avatar asked Nov 16 '22 21:11

contrebis


2 Answers

You can customize webpack using react-app-rewired

If you don't use ionic cli to build and run your app, you can use a normal install of react-app-rewired.

If you use the ionic cli, there is an additional step/trick:

Ionic uses react-scripts under the hood, so you need to trick it into using react-app-rewired instead of react-scripts.

Here is a simple and low-invasive way to have Ionic cli use react-app-rewired instead of react-scripts: add this package.json postinstall script:

{
  "scripts": {
    "postinstall": "cd node_modules/.bin && mv react-scripts react-scripts-real && ln -s ../react-app-rewired/bin/index.js react-scripts",
    ...
  }
}
like image 182
bdombro Avatar answered Nov 19 '22 09:11

bdombro


Update: This fails when you run ionic build because it defaults back to using react-scripts build.

Not sure why I didn't see this before, but taking a closer look at the bootstrapped ionic project, it’s clearly using create-react-app/react-scripts.

Although CRA demands you do a one-time eject in order to configure anything relating to the build, I was able to use react-app-rewired and customizable-cra to customise the build and start scripts. As far as I can tell this works fine with ionic.

like image 36
contrebis Avatar answered Nov 19 '22 10:11

contrebis