如何将 React 作为 NPM 包添加到 Apostrophe v3?

How do you add React as NPM package to Apostrophe v3?

我们正在使用 Apostrophe CMS v3,我们正在尝试使用 React 向页面添加一些自定义应用程序。我能够使用 React CND 脚本在内部添加组件,并将组件作为脚本文件加载到 views/layout.html 中。但这可能不是最佳做法。我想知道是否有一种方法可以使用 npm 包和导入将 React 应用程序添加到 Apostrophe 中。非常感谢!

这个问题似乎已交叉发布到 Github 讨论论坛:https://github.com/apostrophecms/apostrophe/discussions/3393

首席软件架构师的回应:

You can do it in two ways. Which is best depends on your needs.

If you are building a single-page React app but you need some dynamically edited CMS content, you should most likely keep building your React app just as you have been, and use Apostrophe's REST APIs to access piece and page CMS content where you need it. See the documentation on our REST APIs.

On the other hand, if you are building a pretty normal CMS-driven website but you have a few experiences inside your pages that would benefit from embedding a React application, you should carry on with your Nunjucks templates for Apostrophe as you normally would to build a website with Apostrophe, and in addition set up a webpack build of your own to build your React apps, and push the output to a ui/public/build.js file nested in any module of your Apostrophe project. Any .js file found in a ui/public subdirectory of a module is automatically included in the frontend bundle generated by Apostrophe.

In that situation, you can still use the REST APIs to access data from the React app, or you can pass data via data attributes in your markup. If you do the latter, the | jsonAttribute Nunjucks filter is helpful to turn it into a string that is safe for incorporation into a quoted attribute in your markup.

Hope that helps!