Module not found, webpack alias with typescript react

Viewed 1371

I'm trying to implement some alias in webpack. What I want to do, is that instead of using this to import a component on App.js from the folder components.

./components/layout/Header/Header

I want this:

@components/layout/Header/Header

That is, in order to avoid problems when future nested folders will be created. What I've done is coding this on the webpack.config.js

module.exports = {
    context: __dirname,
    entry: './src/index.js',
    output: {
        path: path.resolve( __dirname, 'dist' ),
        filename: 'main.js',
    },
    resolve: {
        extensions: ['.js', '.ts', '.jsx', '.tsx'],
        alias: {
          src: path.resolve(__dirname, 'src'),
          assets: path.resolve(__dirname, 'src/assets'),
          components: path.resolve(__dirname, 'src/components'),
        }
    }
    .
    .
    .
};

And this on the tsconfig.json file:

{
  "compilerOptions": {
    "jsx": "react-jsx",
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "baseUrl": ".",
    "paths": {
      "@": ["./src/*"],
      "@assets": ["./src/assets/*"],
      "@components": ["./src/components/*"]
    },
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
  },
  "include": [
    "src"
  ]
}

When I run "npm run start" that is a "react-scripts start", I get the following error:

./src/App.js
Module not found: Can't resolve '@components/layout/Header/Header' in 'C:\Users\Angel\Documents\React\thermometer\src' 

Also, I've noticed that when I run "npm run start", the object "paths" that I've created on the tsconfig.json file, is deleted and the file resets. I am new creating react projects from zero. Thanks in advance!

1 Answers

Looking at the documentation of Webpack, it doesn't mention automatically prepending the alias with @. Since it isn't specified there, Webpack (and therefore react-scripts start) doesn't know what @components points to.

I actually don't know whether Webpack supports aliases starting with @ (e.g. a suffix of $ has specific meaning for Webpack, and @ is usually for scoped packages), but if it does, you'll have to alter your resolve.alias to include the @.

Related