简体   繁体   English

如何与一个普通的HTML网站共享一个反应项目的打字稿功能?

[英]How to share a typescript function from a react project with a common html website?

I want to share a complex typescript exported function to a simple HTML - javascript website 我想将一个复杂的打字稿导出函数分享到一个简单的HTML-javascript网站

I tried to use npm tsc to transform the file into javascript, but generated files have "exports" functions that creates errors in the browser console. 我尝试使用npm tsc将文件转换为javascript,但生成的文件具有“导出”功能,可在浏览器控制台中创建错误。

myFunction.ts myFunction.ts

export const getTest = (test: any) => {
    // Change test object
    return test;
};

generated myFunction.js 生成了myFunction.js

Object.defineProperty(exports, "__esModule", { value: true });
exports.getTest = function (test) {
    // Change test object
    return test;
};

Browser console actually warning me "Uncaught ReferenceError: exports is not defined" when I try to include the file with a script tag in HTML file. 当我尝试在HTML文件中包含带有脚本标记的文件时,浏览器控制台实际上警告我“未捕获的ReferenceError:导出未定义”。

What am I doing wrong? 我究竟做错了什么?

In order to use the original myFunction.ts file all you need to do is this: 为了使用原始的myFunction.ts文件,您需要做的就是:

Remove the typing and change the extension to .js : 删除键入并将扩展名更改为.js

export const getTest = (test) => {
    // Change test object
    return test;
};

And then, in your HTML file's <script> tag for that JavaScript file, make sure you set the type attibute to module like so: 然后,在该文件的HTML文件的<script>标记中,确保将type属性设置为module如下所示:

<script type="module" src="myFunction.js"></script>

Finally, you'll need to import that functionality where you intend to use it. 最后,您需要在要使用它的位置import该功能。

That should do it as long as you consider browser compatibility: 只要您考虑浏览器兼容性,就应该这样做:

ES6 Modules ES6模块

To make this ultimately clear, here is a Plunkr to demonstrate what I mean. 为了最终明确这一点,这里有一个Plunkr来展示我的意思。

The export keyword creates a module, which can only be used with a module system (such as webpack). export关键字创建一个模块,该模块只能与模块系统(如webpack)一起使用。

Either use a module system or drop export to create a normal file that creates global names. 要么使用一个模块系统或丢弃export创建一个用于创建全局名称一个正常的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM