首页 > 解决方案 > 将 JS IIFE 库导出到 React 组件

问题描述

我刚开始学习 React JS。所以我有这2个JS文件:

  1. Polyfill.js -> github
  2. CustomNavbar.js -> 我的

polyfill.js 结构

export default (function(window){
...
var classy = {
   ...
}
...
})(window);

!window.addEventListener && window.Element && (function () {
...
---code---
...
})();

这是 customnavbar.js

import { cs } from "./polyfill";

(function(){
...
function openNav(){
   ...
   cs.classy.add(overlay, 'on-overlay');
   ...
}
...
})();

这是我的 component.jsx

import "./customnavbar.js"
...
...

它没有用,错误说cs没有定义。也许我在导出语法上做错了?

<script src="./polyfill.js">
<script src="./customnavbar.js">

^ 我希望它像纯 HTML 一样工作,但我不知道如何做出反应。请帮忙!

标签: javascripthtmlreactjsimportexport

解决方案


import "./customnavbar.js"

不是模块导入的有效语法。

元素集type_<script>"module"

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

returnclassy来自 IIFE的对象

“脚本.js”

export default (() => { const classy = {fn() { return 1 }}; return classy })();

import导出的 `classy 对象

“polyfill.js”

import classy from "./script.js";
// do stuff

plnkr http://plnkr.co/edit/Q0orq8Bvk6nOT8tX0qLg?p=preview


推荐阅读