Search code examples
typescriptenumsstatic-typing

How can I import an enum through an intermediate TS file?


I file A I have:

export enum MyFluffyEnum { Beauty, Courage, Love }

In file B I have:

import { MyFluffyEnum } from "./A";

export type { MyFluffyEnum };

In file C I have:

import { MyFluffyEnum } from "./B";

Compile-time error:

'MyFluffyEnum' cannot be used as a value because it was exported using 'export type'.

If I put a separate export { MyFluffyEnum }; in the file B (the intermediate file) I get the error "Module not found: Can't resolve 'B.tsx' in 'my-project/path/here'".

If I import the file with the enum as named export directly, then there is no error.

Links that may be relevant:

  1. Export enum from user defined typescript path result in Module not found

  2. https://github.com/dividab/tsconfig-paths-webpack-plugin/issues/78


Solution

  • This answer solved the problem:

    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:

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