1

我在 monorepo 的多个包中使用 create-react-app。每个应用程序的“公共”文件夹中都有大量重复的代码和文件,因为它们都有相同的图标、描述、字体等。

有没有办法将“public”文件夹中的部分或全部文件移动到他们自己的包中,通过handlebars.js之类的工具运行它们,最后将它们与 create-react-app 捆绑在一起,而不弹出?

4

1 回答 1

0

我找不到任何开源工具,所以我编写了自己的脚本:

prepare_cra_files.sh

#!/usr/bin/env bash

for app in apps/*/ ; do
  # Flush the files if they already exist
  if [ -d "$app"public ]; then
    rm -r "$app"public
  fi

  # Copy over the template files
  cp -r template "$app/public"
done

node templatify.js

模板化.js

const Handlebars = require("handlebars");
const fs = require("fs-extra");
const path = require("path");

const APPS_PATH = path.join(__dirname, "..", "apps");
const INDEX_HTML_TEMPLATE_PATH = path.join(__dirname, "template", "index.handlebars");

(async () => {
  const dirs = await fs.readdir(APPS_PATH);
  const indexHtmlTemplate = Handlebars.compile(await fs.readFile(INDEX_HTML_TEMPLATE_PATH, "utf-8"));

  dirs.forEach(async appName => {
    const indexHtmlContextPath = path.join(APPS_PATH, appName, "/handlebars/index.json");
    if (!fs.existsSync(indexHtmlContextPath)) {
      throw new Error(`Please provide the index.html context for the ${appName} appName`);
    }

    const indexHtmlContext = JSON.parse(await fs.readFile(indexHtmlContextPath, "utf-8"));
    const indexHtml = indexHtmlTemplate(indexHtmlContext);

    await fs.writeFile(path.join(APPS_PATH, appName, "public", "index.html"), indexHtml);
    await fs.remove(path.join(APPS_PATH, appName, "public", "index.handlebars"));
  });
})();
于 2019-11-11T20:10:06.427 回答