typescriptwebpackvisual-studio-codecreate-react-appwebpack-3

Why does VS Code consider an import valid but WebPack does not?


I am pretty sure it is all about the version of WebPack I use ("webpack-cli": "3.3.11") but I want to be sure I am right before going on another journey of debugging for upgrading WebPack (I tried to upgrade it to 5 but it does not work without a config file, I am just stretching the limit against the read-the-manual instruction).

In the tsconfig.base.js I have this:

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

(The reason for using a separate tsconfig.base.json is in the question I linked to below.)

Then there is this:

import { RegistrationStepManager } from "@/helpers";

in file ./src/some/path/RegistrationStepper.tsx.

Running npm start with CRA and react-scripts v4.0.3 shows an error without crashing:

Failed to compile.

./src/some/path/RegistrationStepper.tsx
Module not found: Can't resolve '@/helpers' in '/my-path/my-project/src/some/other/path'.

VS Code tooltips and autocompletion show everything is imported well, no red squiggles, just some ignoreable warnings.

I think that the alias for "@/*" is not working well but, because VS Code works well with it, I think it might be a bug.

How does TS work with WebPack when it comes to this failure? Do I have to upgrade to WebPack 5?

Another question from the same day, from me, on the same code, maybe it is relevant here too: How can I import an enum through an intermediate TS file?.

Thanks.

Update 1

I read this and I am going to migrate from CRA to WebPack without CRA since the project I am working on is not just for playing. Please, if you can, suggest me a guide to migrate from CRA to WebPack. I think the issue at the start of this question is about some missing WebPack configuration. I already have an old WebPack config file that might be causing a part of the issue.


Solution

  • I was having a WebPack config file that was not actually used. I was actually using CRA. So I started using react-app-rewired and WebPack v4 as an intermediate solution till I start using "pure" WebPack. In config-overrides.js I put:

    const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin");
    
    module.exports = {
      webpack: function(config, env) {
        return {
          ...config,
          resolve: {
            ...config.resolve,
            plugins: [
              ...config.resolve.plugins,
              new TsconfigPathsPlugin({
                extensions: [".js", ".jsx", ".ts", ".tsx"],
              }),
            ],
          },
        };
      },
    };
    

    After migrating to react-app-rewired and making this change, the Failed to compile. error is gone. This also solves the issue in How can I import an enum through an intermediate TS file?.