gpt4 book ai didi

commonjs - 有没有办法在原生 CommonJS 环境中使用 JSX?

转载 作者:行者123 更新时间:2023-12-03 13:41:19 28 4
gpt4 key购买 nike

我正在一个环境中启动一个新项目,该环境对 require 模块具有 native CommonJS 支持 - 这是一个原子 shell 项目,不可能使用预编译步骤,例如在 Browserify 或 webpack AFAIK

我能够在 index.html 上声明的 app.jsx 入口点文件上使用 JSX,这是因为 JSXTransformer code> 之前已声明:

<script src="scripts/vendor/JSXTransformer.js"></script>
<script type="text/jsx" src="scripts/app.jsx"></script>

我希望能够对在我的 app.jsx 模块中作为 CommonJS 模块导入的子模块使用 JSX 语法:

// This raises an Error, the XML-like tags are not supported
var Grid = require('./scripts/grid.jsx');

据我所知,对于通过 require 加载的任何模块,我将被迫放弃 JSX 语法并使用普通语法。在这种情况下,除了继续使用 JSX 之外,还有其他选择吗?

最佳答案

[更新]

现在 JSX 变压器 is being deprecated in favor of Babel ,你可以使用 Babel 的 require hook在类似 CommonJS 的环境中支持 JSX:

Usage

require("babel/register");

All subsequent files required by node with the extensions .es6, .es, .jsx and .js will be transformed by Babel. The polyfill is also automatically required.

NOTE: By default all requires to node_modules will be ignored. You can override this by passing an ignore regex via:

require("babel/register")({
// This will override `node_modules` ignoring - you can alternatively pass
// an array of strings to be explicitly matched or a regex / glob
ignore: false
});

[旧答案]

如果是 Node.js 环境(如atom-shell),您可以使用 node-jsx :

require('node-jsx').install()
require("./myComponent.js");

如果需要,您还可以使用 .jsx 扩展名:

require('node-jsx').install({extension: '.jsx'})
require("./myComponent.jsx");

关于commonjs - 有没有办法在原生 CommonJS 环境中使用 JSX?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26742714/

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