gpt4 book ai didi

reactjs - 将 ClojureScript 添加到现有代码库

转载 作者:行者123 更新时间:2023-12-03 13:20:33 26 4
gpt4 key购买 nike

我有一个相当大的 React + Relay 代码库,正在使用 Webpack 构建。是否有可能以某种方式逐步将 ClojureScript + Reagent 引入其中?

我正在考虑从代码库中的一些较小的功能组件开始并将它们交换出来。这意味着试剂组件需要以某种方式从父组件接收 Prop 。

关于这样做有什么想法或工具吗?快速的 Google 似乎只会找到有关在 ClojureScript 应用程序中包含 JavaScript 库的文章,而不是相反。

最佳答案

您可以创建一个试剂组件,将其导出,然后将其导入到您的 JS 代码中。

由于您的 js 项目中已经有 webpack/react,因此您需要从 cljs 项目中排除它们:

:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/clojurescript "1.9.229"]
[org.clojure/core.async "0.2.391"
:exclusions [org.clojure/tools.reader]]
[reagent "0.6.0" :exclusions [cljsjs/react cljsjs/react-dom cljsjs/react-dom-server]]]

现在你必须欺骗 Reagent 让它认为你刚刚排除的那些 react 文件仍然在这里。创建这三个文件:

src/cljsjs/react.cljs

(ns cljsjs.react)

src/cljsjs/react/dom.cljs

(ns cljsjs.react.dom)

src/cljsjs/react/dom/server.cljs

(ns cljsjs.react.dom.server)

是的,每个文件中只有一行带有命名空间声明。

现在您可以编写组件了:

reagent_component/core.cljs:

(ns reagent-component.core
(:require [reagent.core :as r]))

(def counter (r/atom 5))

(def ^:export test66
(r/create-class
{:reagent-render
(fn [props]
(let [{:keys [name]} props]
[:div
{:on-click (fn [] (swap! counter inc))}
name ", I am counting " (clojure.string/join ", " (map inc (range @counter)))])
)}))

您的 cljsbuild 部分位于 project.clj可能看起来像这样:

:cljsbuild {:builds
[{:id "min"
:source-paths ["src"]
:compiler {:output-to "resources/public/js/compiled/reagent_component_min.js"
:output-dir "resources/public/js/compiled/min"
:main reagent-component.core
:optimizations :advanced
:asset-path "js/compiled/out"
}}]}

为了简洁起见,我只给了您 min cljsbuild 部分。

lein cljsbuild once min将产生resources/public/js/compiled/reagent_component_min.js文件,必须将其复制到您的 Webpack 项目中。

新条目将添加到您的 webpack.config 中主入口点之前:

 entry: [`${APP_DIR}/reagent_component_min.js`, `${APP_DIR}/main.js`],

此文件 (reagent_component_min.js) 应从 babelification 中排除:

module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components|reagent_component_min.js)/,
loader: 'babel-loader',
query: {
presets: ['latest']
}
}
]
}

在你的 JavaScript 中你可以像这样使用它:

import React from 'react';
import ReactDOM from 'react-dom';

const comp = reagent_component.core.test66;

const element = <div>Hello, world
{React.createElement(comp, {name: 'akond'})}
</div>;

ReactDOM.render(
element,
document.getElementById('app')
);

是的,babel jsx插件无法识别<comp name="..."/> 。这就是调用 React.createElement 的原因。我不知道如何让它看起来更好,但它确实有效。

关于reactjs - 将 ClojureScript 添加到现有代码库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41844343/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com