<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>React</title>
	<atom:link href="https://www.hu365.dev/blog/tag/react/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.hu365.dev</link>
	<description>Justin Woo（吴晓虎）的个人博客，生命不息，学习不止</description>
	<lastBuildDate>Sun, 18 Feb 2024 01:34:24 +0000</lastBuildDate>
	<language>zh-CN</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.4.3</generator>

<image>
	<url>https://www.hu365.dev/wp-content/uploads/2022/10/cropped-logo-正矩形.blue_-32x32.png</url>
	<title>React</title>
	<link>https://www.hu365.dev</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>在wordpress页面中嵌入React页面应用</title>
		<link>https://www.hu365.dev/blog/2022/12/215/</link>
		
		<dc:creator><![CDATA[Justin]]></dc:creator>
		<pubDate>Mon, 19 Dec 2022 12:05:22 +0000</pubDate>
				<category><![CDATA[前端笔记]]></category>
		<category><![CDATA[React]]></category>
		<category><![CDATA[wordpress]]></category>
		<guid isPermaLink="false">https://www.hu365.dev/?p=215</guid>

					<description><![CDATA[想实现一个“技术题库”的专栏，用来收藏一些经典题型、不太熟悉的面试题/技术题，采局部React应用的方式实现 一：XAMPP环境 本地启用wordpress，还原现网主题与配置，启用本地测试域名 1.1：本地wordpress XAMPP是免费的集成安装包（下 <a href="https://www.hu365.dev/blog/2022/12/215/" class="cosmoswp-btn">阅读更多</a>]]></description>
										<content:encoded><![CDATA[
<p>想实现一个“技术题库”的专栏，用来收藏一些经典题型、不太熟悉的面试题/技术题，采局部<code>React</code>应用的方式实现</p>



<h2 class="wp-block-heading">一：XAMPP环境</h2>



<p>本地启用<code>wordpress</code>，还原现网主题与配置，启用本地测试域名</p>



<h3 class="wp-block-heading">1.1：本地wordpress</h3>



<p><code>XAMPP</code>是免费的集成安装包（<a href="https://www.apachefriends.org/">下载地址</a>），集成了<code>Apache</code>、<code>php8</code>、<code>mysql</code>、<code>phpMyAdmin</code></p>



<ul>
<li>下载<code>wordpress</code>解压到自己想要放的位置，我选择在<code>/xampp/apps/www.hu365.test</code></li>



<li>把线上使用的<code>主题</code>完整下载并在本地主题使用</li>



<li>通过<code>phpMyAdmin</code>，创建数据库并导入线上的备份数据</li>



<li>配置<code>xampp/apache/conf/extra/httpd-vhosts.conf</code>文件，添加本地测试域名：<code>www.hu365.test</code></li>



<li>本地<code>host</code>文件，将<code>www.hu365.test</code>指向<code>127.0.0.1</code></li>
</ul>



<p>此时，就可以通过<code>www.hu365.test</code>访问和线上环境一样的页面了</p>



<h3 class="wp-block-heading">1.2：wordpress页面</h3>



<p>新建页面<code>技术题库</code>，使用<code>代码编辑器</code>，引入最新的<code>react.js</code>、以及生产<code>js</code>、<code>css</code></p>



<pre class="EnlighterJSRAW" data-enlighter-language="html" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;!-- 所有额外引入的js、css -->
&lt;div>
	&lt;script src="/wp-content/apps/topic-bank/static/js/react.production.min.js" crossorigin>&lt;/script>
	&lt;script src="/wp-content/apps/topic-bank/static/js/react-dom.production.min.js" crossorigin>&lt;/script>
	&lt;script defer="defer" src="/wp-content/apps/topic-bank/static/js/main.js">&lt;/script>
	&lt;link href="/wp-content/apps/topic-bank/static/css/main.css" rel="stylesheet">
&lt;/div>
&lt;!-- 这是react渲染节点 -->
&lt;div id="react_root">&lt;/div></pre>



<ul>
<li>这里有进行<code>格式化</code>排版，实际代码为了减少多余换行，去掉了所有换行与空格</li>



<li>引入路径都是用<code>绝对路径</code>引入</li>



<li>路径<code>/wp-content/apps/topic-bank</code>是<code>react</code>指定的生产目录</li>



<li><code>main.js</code>、<code>main.css</code>为生产环境<code>不含hash</code>的最终文件，此举是为了测试，异步加载主<code>js</code></li>



<li>页面访问路径（<code>URL</code>），需在路由配置中配置为<code>basename</code>，此处配置为<code>/topic-bank</code></li>
</ul>



<h2 class="wp-block-heading">二：React应用</h2>



<p>使用<code>create-react-app</code>构建<code>react app</code>，配置生产文件名、生产路径、静态资源等</p>



<h3 class="wp-block-heading">2.1：替换index.html</h3>



<p>访问本地页面：技术题库，右键另存为页面得到<code>index.html</code>页面和资源文件夹</p>



<ul>
<li>把资源文件夹重命名：<code>static</code>，并在<code>static</code>下新建文件夹：<code>js</code>、<code>css</code></li>



<li><code>js</code>文件移动到<code>js</code>文件夹，<code>css</code>文件移动到<code>css</code>文件夹，并同步修改相关引用路径</li>



<li>下载<code>react.production.min.js</code>、<code>react-dom.production.min.js</code>到<code>js</code>文件夹</li>
</ul>



<p>此举是为了实现测试环境的样式和线上相同，方便直接使用<code>react</code>进行调试开始</p>



<h3 class="wp-block-heading">2.2：生产配置</h3>



<p>因为<code>create-react-app</code>构建应用无法直接修改webpack，这里需要安装使用<code>react-app-rewired</code>，可以同步安装<code>customize-cra</code></p>



<pre class="EnlighterJSRAW" data-enlighter-language="powershell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">npm install react-app-rewired --save-dev</pre>



<p>创建文件<code>config-overrides.js</code>，在其中修改配置：</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">module.exports = function override(config, env) {
	// 仅修改生产配置
	if (env !== 'production') return config;
	const paths = require('react-scripts/config/paths');

	// 额外引入的
	// react.production.min.js、react-dom.production.min.js
	// 不参与打包
	config.externals = {
		'react': 'React',
		'react-dom': 'ReactDOM',
	}

	// 生产输出目录
	// 与"页面"中路径一致：/wp-content/apps/topic-bank
	config.output.path = "C:/xampp/apps/www.hu365.dev/wp-content/apps/topic-bank";
	paths.appBuild = "C:/xampp/apps/www.hu365.dev/wp-content/apps/topic-bank";

	// Get rid of hash for js files
	// 方便测试，脚本文件去除hash
	config.output.filename = "static/js/[name].js";
	config.output.chunkFilename = "static/js/[name].chunk.js";

	// Get rid of hash for css files
	// 方便测试，样式文件去除hash
	const miniCssExtractPlugin = config.plugins.find(element => element.constructor.name === "MiniCssExtractPlugin");
	miniCssExtractPlugin.options.filename = "static/css/[name].css";
	miniCssExtractPlugin.options.chunkFilename = "static/css/[name].css";

	// Get rid of hash for media files
	// 方便测试，其他文件去除hash
	config.module.rules[1].oneOf.forEach(oneOf => {
		if (!oneOf.options || oneOf.options.name !== "static/media/[name].[hash:8].[ext]") {
			return;
		}
		oneOf.options.name = "static/media/[name].[ext]";
	});
	return config;
}</pre>



<h3 class="wp-block-heading">2.3：添加路由</h3>



<p>新建<code>router/index.tsx</code></p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// 列表页、和详情页
import TopicList from "../views/TopicList";
import TopicContent from "../views/TopicContent";
import {
	createBrowserRouter,
	RouterProvider,
} from "react-router-dom";

const router = createBrowserRouter([
	{
		path: "/",
		element: &lt;TopicList />,
	},
	{
		path: "/topicName",
		element: &lt;TopicContent />,
	},
], {
	// 通过环境变量配置基础路径
	basename: process.env.REACT_APP_ROUTER_BASE_NAME
});

export default function Router() {
	return (
		&lt;RouterProvider router={router} />
	)
}</pre>



<p>环境变量配置：</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// 测试环境：.env.development
// 随意填写
REACT_APP_ROUTER_BASE_NAME = /

// 生产环境：.env.production
// 该路径必须和"页面"访问URL相同，否则无法访问（/topic-bank）
REACT_APP_ROUTER_BASE_NAME = /topic-bank</pre>



<h3 class="wp-block-heading">2.4：配置别名</h3>



<p>正在开发中，忽然发现<code>../../*</code>的书写格式还是太丑了，赶紧把别名加上<br><code>webpack</code>的<code>alias</code>配置，同样在<code>config-override.js</code>中配置：</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const path = require("node:path");

module.exports = function override(config, env) {
    // 相对路径别名
    config.resolve.alias = {
        '@': path.resolve(__dirname, 'src'),
        '@Pages': path.resolve(__dirname, 'src/pages'),
        '@Style': path.resolve(__dirname, 'src/style'),
        '@Components': path.resolve(__dirname, 'src/components'),
    };

    // 其他内容
    
    return config;
}</pre>



<p><code>TS</code>配置，<code>tsconfig.json</code>文件：</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
  "compilerOptions": {
    ...
    "paths": {
      "@/*": ["./*"],
      "@Pages/*": ["./pages/*"],
      "@Style/*": ["./style/*"],
      "@Components/*": ["./components/*"]
    }
  },
  ...
}
</pre>



<h2 class="wp-block-heading">三：开发中</h2>



<p>完成以上工作后，启动测试服务，访问的页面和线上“技术题库”页面样式一致<br>这样就可以脱离<code>wordpress</code>进行本地开发<br>待到一定阶段，需要看最终效果时；直接<code>build</code>一下，再在本地环境访问“技术题库”即可</p>



<p>好了，可以开始接下来开发工作了！</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
