我不认为create-react-app 是这里的正确工具,因为您没有使用 React 创建完整的应用程序,而是逐步添加 React 代码。我建议单独使用 Webpack。这使您的应用程序更简洁,更易于使用其他代码进行维护。
如果您想将您的 React 代码与现有代码分开,您可以创建一个基于 webpack 的 Authoring Libraries Guide 的库。您可以使用 ReactDOM.render() (Docs) 渲染您的组件。请注意,您可以在一个页面上(几乎)无限次调用此函数,这允许您部分替换现有代码。
替换一个页面意味着创建一个根DOM元素并调用render函数:
<!-- page.html -->
<html>
<head></head>
<body>
<!-- more html -->
<div id="page-root" />
<!-- more html -->
</body>
</html>
import React from 'react'
import ReactDOM from 'react-dom'
import Page from './routes/YourPageComponent'
ReactDOM.render(<Page />, document.getElementById('page-root'));
前面的代码意味着您在新代码中呈现您的代码,这些代码由您的 webpack 加载器(例如 Babel-Loader、Typescript-Loader)转译。如果要渲染现有代码中的代码,请查看Doc's about Webpack Libraries 以将渲染函数导出到全局上下文中。以下脚本是我想出来的一个例子。
// components/PageExampleComponent.jsx
import React from 'react';
export default function({pageTitle="example"}){
return <div>
<h1>{pageTitle}</h1>
</div>
}
// libary/index.js
import PageExampleComponent from './components/PageExampleComponent';
export const MyLibrary = {
PageExampleComponent
}
前面的代码需要以下(部分)Webpack 配置来导出MyLibrary:
module.exports = {
//...
output: {
library: 'MyLibrary',
// based on a fast look into the docs, I think the following are optional:
libraryTarget: 'window',
libraryExport: 'default'
}
};
要渲染这个库的一个组件,你需要 React 和 ReactDOM 作为你网站中的脚本——当然还有你自己的库脚本。您可以使用纯 JavaScript 调用 ReactDOM.render():
ReactDOM.render(
React.createElement(window.MyLibrary.PageExampleComponent),
document.getElementById('page-root')
另一个想法是将所有内容都转移到 Webpack 中。这可能更容易,因为您没有不同 Javascript 版本和方言的障碍(例如,有和没有 JSX 支持)。您甚至可以使用两个入口点将 jQuery 代码和 React 代码分开:
module.exports = {
//...
entry: {
oldCode: './src/jqueryIndex.js',
replacement: './src/reactIndex.js'
},
output: {
filename: "[name].js"
}
};