strothj / react-app-rewire-typescript-babel-preset

Add TypeScript support to Create React App using @babel/preset-typescript
https://react-app-rewire-typescript-babel-preset.netlify.com
MIT License
52 stars 6 forks source link

TSConfig paths #11

Closed deftomat closed 6 years ago

deftomat commented 6 years ago

Is it possible to load and use paths defined in tsconfig.json ?

For example:

{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "paths": {
      "@src/*": ["packages/web/src/*"]
    }
  }
}

Then, we can use imports like this: import App from '@src/content/App';

This example is from our monorepo, where we have one common tsconfig in a root of a repo and then tsconfigs like above in each package.

strothj commented 6 years ago

You can accomplish it with something like this. You'd also need to make a corresponding version for Jest I imagine.

const {
  rewireWebpack: rewireTypescript,
  rewireJest: rewireTypescriptJest
} = require("react-app-rewire-typescript-babel-preset");

module.exports = {
  webpack: function(config, env) {
    const rewiredConfig = rewireTypescript(config);

    rewiredConfig.resolve.alias = rewiredConfig.resolve.alias || {};
    rewiredConfig.resolve.alias["@src"]: "packages/web/src";

    return rewiredConfig;
  },
  jest: function(config) {
    return rewireTypescriptJest(config);
  }
};
strothj commented 6 years ago

I keep my alias config in sync. I have a monorepo I work with that has this snippet:

    // Add monorepo path aliases, done because each package has a subdirectory
    // named "src". Using the settings from tsconfig.json so the settings can be
    // reused both in the Create React App setup and Storybook.
    const tsconfigJson = require("../../tsconfig.json");
    const alias = Object.entries(tsconfigJson.compilerOptions.paths).reduce(
      (acc, [package, mapping]) => {
        package = package.replace("/*", "");
        if (acc[package]) return acc;

        acc[package] = `${package}/src`;
        return acc;
      },
      {},
    );
    rewiredConfig.resolve.alias = {
      ...rewiredConfig.resolve.alias,
      ...alias,
    };

This assumes there are no comment lines to cause a parsing error with tsconfig.json. The typescript package has a function that parses JSON with comments.

const ts = require("typescript");

ts.parseJsonConfigFileContent(...)
deftomat commented 6 years ago

@strothj AWESOME, thanks 👍