Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set alias path via webpack in CRA (create-react-app) and craco?

I have a problem on set webpack alias path using create-react-app and craco, already googling it but can't solve the problem.

I got an error Module not found: Can't resolve '@app/App' in 'C:\ReactSandbox\my-project\src everytime i run application using command yarn start

Steps to reproduce:

  1. create-react-app my-project
  2. cd my-project
  3. yarn add @craco/craco
  4. cat > craco.config.js (see configuration below)
  5. replace react-scripts to craco on 'script' section on package.json (craco start, craco build, etc)
  6. edit file src/index.js (replace line 4, see code below)
  7. yarn start

craco.config.js

const path = require("path");

module.exports = {
  webpack: {
    resolve: { 
      alias: {
        "@app": path.resolve(__dirname, "src/"),
      }
    }    
  }
};

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from '@app/App'; //replace './App' into '@app/App'
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

serviceWorker.unregister();

Current result

Module not found: Can't resolve '@app/App' in 'C:\ReactSandbox\my-project\src

Expected

I'm avoiding call relative path hell, instead of import module like ../../../../FilterComment.js, it would be clean to write @app/FilterComment.js

like image 534
Yasin Junet Avatar asked May 31 '19 02:05

Yasin Junet


People also ask

What is craco alias?

GitHub - risenforces/craco-alias: A craco plugin for automatic aliases generation for Webpack and Jest. Product. Actions.

Can I use webpack With create react app?

Now, anywhere on your system, you can run the create-react-app command to initiate the setup for a new Webpack-powered React app. The completed version of the code for this next section is available in heart-webpack-complete . This will create the boilerplate for the new app and install the app's dependencies.

Does CRA come with webpack?

Create React App (CRA) ships with webpack already under the hood, but usually, we would need to add more configurations as our app grows. Luckily for us, we can create a webpack. config.


2 Answers

resolve for carco:

u need install craco-alias, then will write in craco.config.js

    const CracoAlias = require('craco-alias')

    module.exports = {
      plugins: [
        {
          plugin: CracoAlias,
          options: {
            source: 'tsconfig',
            baseUrl: '.',
            tsConfigPath: './tsconfig.path.json',
          },
        },
      ],
    }

tsconfig.path.json

    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@/*": ["src/*"],
          "@svg/*": ["src/assets/svg/*"],
          "@img/*": ["src/assets/images/*"],
          "@icons/*": ["src/assets/icons/*"],
          "@shared/*": ["src/shared/*"],
          "@components/*": ["src/components/*"],
          "@hooks/*": ["src/hooks/*"],
          "@constants/*": ["src/constants/*"],
          "@layout/*": ["src/layout/*"],
          "@services/*": ["src/services/*"]
        }
      }
    }

tsconfig.json

    {
      "extends": "./tsconfig.path.json",
      "compilerOptions": {
        "target": "es5",
        "lib": [
          "dom",
          "dom.iterable",
          "esnext"
        ],
        "allowJs": true,
        "checkJs": false,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "declaration": false,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "jsx": "react-jsx",
        "noFallthroughCasesInSwitch": true,
        "removeComments": true
      },
      "include": [
        "src",
        "src/configs",
        "react-app-env.d.ts"
      ]
    }

like image 121
Paul Alexeev Avatar answered Oct 06 '22 12:10

Paul Alexeev


First - tell to IDE about aliases in tsconfig.json:

create separate file tsconfig.paths.json and add aliases:

{
   "compilerOptions": {
      "baseUrl": "./src",
      "paths": {
         "@utils/*": ["utils/*"]
      }
   }
}

Add created tsconfig.paths.json to main tsconfig.json

{
   "extends": "./tsconfig.paths.json",
   ... other staff ...
}

Second - tell to webpack about aliases:

Add aliases to config-overrides.js

const {
   override,
   addWebpackAlias
} = require('customize-cra');

const path = require("path");

module.exports = override(
   addWebpackAlias({
      "@utils": path.resolve(__dirname, "./src/utils"),
   }),
);
like image 37
Yuriy Gyerts Avatar answered Oct 06 '22 13:10

Yuriy Gyerts