首页 > 解决方案 > 用 ReactJS.NET 构建 Esbuild?

问题描述

TL;DR我如何将esbuildReactJS.NET一起使用?


长版

ReactJS.NET 期望来自“捆绑包”的以下内容:

React.Exceptions.ReactNotInitialisedException: 'React has not been loaded correctly: missing (React, ReactDOM, ReactDOMServer). Please expose your version of React as global variables named 'React', 'ReactDOM', and 'ReactDOMServer'

我一直不清楚 Webpack 到底做了什么,但是看看这里的 ReactJS.NET Webpack 教程,设置如下:

import React from 'react';
import ReactDOM from 'react-dom';
import ReactDOMServer from 'react-dom/server';

import RootComponent from './home.jsx';

global.React = React;
global.ReactDOM = ReactDOM;
global.ReactDOMServer = ReactDOMServer;

global.Components = { RootComponent };

在此处的示例 webpack-config中,还有以下输出设置:

{
  [...]
  globalObject: 'this',
}

在 esbuild 中镜像这个将使用iifeand esbuild.globalName = 'this',但它会引发错误:

 > (global name):1:0: error: Expected identifier but found "this"
    1 │ this

Esbuild 非常严厉,因为它是一个捆绑器(而不是转译和连接器),那么我将如何调整 Esbuild 以使捆绑包将global对象更改为 React.NET 所期望的?- 甚至有可能吗?

谢谢,弗莱明

标签: javascriptreactjsreactjs.netesbuild

解决方案


找到了解决方案。

import { build } from 'esbuild'

const globalName = 'whatever'

build({
    [...]
    format: 'iife',
    globalName,
    footer: {
        // Important! Assigns the raw export of the bundle to whatever `this` is in the given context
        js: `Object.assign(this, ${globalName})`,
    },
})

推荐阅读