KonstantinSimeonov / tsx-control-statements

Control flow JSX/TSX elements that get compiled to plain old javascript.
Do What The F*ck You Want To Public License
92 stars 9 forks source link

we can use it without ejecting cra #48

Open ylji1990 opened 3 years ago

ylji1990 commented 3 years ago

I haven't found any way of integrating this into create-react-app scaffold project without ejecting the scripts and modifying them


we can use @craco/craco and add craco.config.js like this

const tsxControlStatements = require("tsx-control-statements");
const path = require("path");
const fs = require("fs");

const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = (relativePath) => path.resolve(appDirectory, relativePath);
const appSrc = resolveApp("src");

// 动态修改配置
const overrideWebpackConfigPlugin = {
  plugin: {
    overrideWebpackConfig: ({ webpackConfig }) => {
      for (let _rule of webpackConfig.module.rules) {
        if (_rule.oneOf) {
          _rule.oneOf.unshift({
            test: /\.(ts|tsx)$/,
            include: appSrc,
            use: [
              {
                loader: require.resolve("ts-loader"),
                options: {
                  // disable type checker - we will use it in fork plugin
                  transpileOnly: true,
                  getCustomTransformers: () => ({
                    before: [tsxControlStatements.default()],
                  }),
                },
              },
            ],
          });
          break;
        }
      }
      //   console.log(JSON.stringify(webpackConfig.module.rules, null, 4));
      //   throw 1
      return webpackConfig;
    },
  },
};

module.exports = {
  plugins: [overrideWebpackConfigPlugin],
};

image image

KonstantinSimeonov commented 3 years ago

@ylji1990, would you like to make a PR with the info added to the readme or maybe a new demo included? This is awesome! If you don't, I'll work on adding it when I have the time!

kbzowski commented 2 years ago

Does not work:

./src/index.tsx
TypeError: loaderContext.getOptions is not a function