用Preact在特定文件中为React创建别名?

huangapple go评论71阅读模式
英文:

Aliasing React with Preact on specific files?

问题

目前我的项目是基于Ruby on Rails,前端部分使用React(在应用的某些部分),同时使用Webpack。我试图在应用的某一个部分使用react-final-form(https://final-form.org/react),并将React别名为Preact(https://preactjs.com/guide/v10/getting-started#aliasing-react-to-preact)以降低页面的加载体积。我已成功将React别名为Preact,但是否可以仅在一个文件中解析别名?

在下面这个示例Node项目中,我已成功在整个应用程序中解析别名:
index.js

import React from 'react'
import { render } from 'react-dom'
import { Form, Field } from 'react-final-form'
const onSubmit = async values => {
  window.alert(JSON.stringify(values, 0, 2))
}
const App = () => (
  <div>
    <h1>React Final Form - Simple Example</h1>
    <Form
      onSubmit={onSubmit}
      initialValues={{ stooge: 'larry', employed: false }}
      render={({ handleSubmit, form, submitting, pristine, values }) => (
        <form onSubmit={handleSubmit}>
          <div>
            <label>First Name</label>
            <Field
              name="firstName"
              component="input"
              type="text"
              placeholder="First Name"
            />
          </div>
          <div className="buttons">
            <button type="submit" disabled={submitting || pristine}>
              Submit
            </button>
          </div>
          <pre>{JSON.stringify(values, 0, 2)}</pre>
        </form>
      )}
    />
  </div>
)
render(<App />, document.getElementById('root'))

package.json

{
  "name": "my-react-webpack-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack serve",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "final-form": "^4.20.9",
    "preact": "^10.15.1",
    "react": "npm:@preact/compat",
    "react-dom": "npm:@preact/compat",
    "react-final-form": "^6.5.9"
  },
  "devDependencies": {
    "@babel/core": "^7.22.1",
    "@babel/preset-env": "^7.22.4",
    "@babel/preset-react": "^7.22.3",
    "babel-loader": "^9.1.2",
    "html-webpack-plugin": "^5.5.1",
    "webpack": "^5.85.0",
    "webpack-cli": "^5.1.2",
    "webpack-dev-server": "^4.15.0"
  }
}

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: path.join(__dirname, "src", "index.js"),
  output: {
    path: path.resolve(__dirname, "dist"),
  },
  resolve: {
    alias: {
      "react": "preact/compat",
      "react-dom/test-utils": "preact/test-utils",
      "react-dom": "preact/compat", // 必须在test-utils之下
      "react/jsx-runtime": "preact/jsx-runtime"
    },
  },
  module: {
    rules: [
      {
        test: /\.js$|jsx/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react']
          }
        }
      },
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.join(__dirname, "src", "index.html"),
    }),
  ],
}

上述配置将React与Preact在整个应用程序中别名。但在实际项目中,无法将这些配置放在package.json中。是否可以将别名应用于仅一个文件/页面/入口点?

英文:

Currently my project is on Ruby on rails with React frontend(on some parts of the app). Also uses Webpack.
I am trying to use react-final-form(https://final-form.org/react) on just one part of the app, aliasing React with Preact(https://preactjs.com/guide/v10/getting-started#aliasing-react-to-preact) to lower the page weight.
I was able to resolve the alias from React to Preact on the whole app, but is it possible to resolve the alias to just 1 file?

I was able to resolve the alias on the whole app in the following sample node project:
index.js

import React from &#39;react&#39;
import { render } from &#39;react-dom&#39;
import { Form, Field } from &#39;react-final-form&#39;
const onSubmit = async values =&gt; {
  window.alert(JSON.stringify(values, 0, 2))
}
const App = () =&gt; (
  &lt;div&gt;
    &lt;h1&gt;React Final Form - Simple Example&lt;/h1&gt;
    &lt;Form
      onSubmit={onSubmit}
      initialValues={{ stooge: &#39;larry&#39;, employed: false }}
      render={({ handleSubmit, form, submitting, pristine, values }) =&gt; (
        &lt;form onSubmit={handleSubmit}&gt;
          &lt;div&gt;
            &lt;label&gt;First Name&lt;/label&gt;
            &lt;Field
              name=&quot;firstName&quot;
              component=&quot;input&quot;
              type=&quot;text&quot;
              placeholder=&quot;First Name&quot;
            /&gt;
          &lt;/div&gt;
          &lt;div className=&quot;buttons&quot;&gt;
            &lt;button type=&quot;submit&quot; disabled={submitting || pristine}&gt;
              Submit
            &lt;/button&gt;
          &lt;/div&gt;
          &lt;pre&gt;{JSON.stringify(values, 0, 2)}&lt;/pre&gt;
        &lt;/form&gt;
      )}
    /&gt;
  &lt;/div&gt;
)
render(&lt;App /&gt;, document.getElementById(&#39;root&#39;))

package.json

{
  &quot;name&quot;: &quot;my-react-webpack-app&quot;,
  &quot;version&quot;: &quot;1.0.0&quot;,
  &quot;description&quot;: &quot;&quot;,
  &quot;main&quot;: &quot;index.js&quot;,
  &quot;scripts&quot;: {
    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,
    &quot;dev&quot;: &quot;webpack serve&quot;,
    &quot;build&quot;: &quot;webpack&quot;
  },
  &quot;author&quot;: &quot;&quot;,
  &quot;license&quot;: &quot;ISC&quot;,
  &quot;dependencies&quot;: {
    &quot;final-form&quot;: &quot;^4.20.9&quot;,
    &quot;preact&quot;: &quot;^10.15.1&quot;,
**  &quot;react&quot;: &quot;npm:@preact/compat&quot;,
    &quot;react-dom&quot;: &quot;npm:@preact/compat&quot;,**
    &quot;react-final-form&quot;: &quot;^6.5.9&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@babel/core&quot;: &quot;^7.22.1&quot;,
    &quot;@babel/preset-env&quot;: &quot;^7.22.4&quot;,
    &quot;@babel/preset-react&quot;: &quot;^7.22.3&quot;,
    &quot;babel-loader&quot;: &quot;^9.1.2&quot;,
    &quot;html-webpack-plugin&quot;: &quot;^5.5.1&quot;,
    &quot;webpack&quot;: &quot;^5.85.0&quot;,
    &quot;webpack-cli&quot;: &quot;^5.1.2&quot;,
    &quot;webpack-dev-server&quot;: &quot;^4.15.0&quot;
  }
}

webpack.config.js

const path = require(&#39;path&#39;);
const HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;);

module.exports = {
  mode: &#39;development&#39;,
  entry: path.join(__dirname, &quot;src&quot;, &quot;index.js&quot;),
  output: {
    path:path.resolve(__dirname, &quot;dist&quot;),
  },
  resolve: {
    alias: {
**    &quot;react&quot;: &quot;preact/compat&quot;,
      &quot;react-dom/test-utils&quot;: &quot;preact/test-utils&quot;,
      &quot;react-dom&quot;: &quot;preact/compat&quot;,     // Must be below test-utils
      &quot;react/jsx-runtime&quot;: &quot;preact/jsx-runtime&quot;**
    },
  },
  module: {
    rules: [
      {
        test: /\.js$|jsx/,
        exclude: /node_modules/,
        use: {
          loader: &quot;babel-loader&quot;,
          options: {
            presets: [&#39;@babel/preset-env&#39;, &#39;@babel/preset-react&#39;]
          }
        }
      },
      {
        test: /\.css$/i,
        use: [&quot;style-loader&quot;, &quot;css-loader&quot;],
      },
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.join(__dirname, &quot;src&quot;, &quot;index.html&quot;),
    }),
  ],
}

The above configuration aliases React with Preact on the whole app. Although on the actual project I can't put this in the package.json.
Is it possible to apply the alias to just 1 file/page/entry point?

答案1

得分: 0

不使用Webpack,没有。别名是项目范围的。

不清楚你的需求是什么,但这可能不会起作用。React 和 Preact 组件之间没有本地互操作。你不能真正混合和匹配,尤其不能同时减少页面的权重。

英文:

Not with Webpack, no. Aliases are project-wide.

It's unclear what you're after, but this probably won't work anyways. React and Preact components have no native interop. You cannot mix and match really, certainly not while also reducing page weight.

huangapple
  • 本文由 发表于 2023年6月5日 14:54:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76404091.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定