假設我有一個正常的反應應用程序,使用redux和一些ajax調用。 如果我想將它傳遞給別人我會給他們捆綁的js文件我用的WebPack創建,並要求他們將其納入自己的HTML +呈現一個div與ID「對myApp」的例如:導入或需要由反應應用程序創建的捆綁js文件
<div id="myApp"></div>
好吧,如果他們的網站也創建了反應,他們想要包括我的捆綁js文件在他們的組件之一,當然提供相關的div
?
我試圖用import
或require
模擬這個:
require('./path/to/myBundle.js');
import './path/to/myBundle.js';
例子:
//...
import './path/to/myBundle.js'; // the file that will render myApp to the relevant div
// ....
export function SomeApp(args){
return(
<div>
<div id="myApp"></div>
<SomeComponent />
</div>
);
};`
因爲我得到了一些錯誤,這不起作用:
Uncaught Error: Minified React error #37; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=37 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
和當我訪問這個網站我看到:
_registerComponent(...): Target container is not a DOM element.
然而,它們是否會使用這個文件(myBundle.js)及其部件外(頂層index.html
例如),它會工作得很好,當然。
編輯: 我忘了提及,我想我知道問題是什麼,應用程序沒有HTML準備好這個div
呢。但我不知道一個好的原生方式來等待它的存在。
編輯#2以下@Frxstrem的回答: 我想要遵循這個答案,但我認爲我做錯了。 我有兩份corry house slingshot demo app作爲app1和app2。 改變了「產出」的APP1的webpack.config.prod.js
到:
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: '/',
filename: 'app1Bundle.js',
library: "App1",
libraryTarget: "umd"
},
我試圖使APP1 APP2的網頁組件中。 所以我複製從APP1「已發佈」文件APP2的根源,並呼籲該文件夾APP1,然後添加一個導入電話:
import {app1} from '../../app1/app1Bundle';
和返回函數內部匹配的標籤:
const HomePage =() => {
return (
<div>
<app1 />
<h1>App 2</h1>
</div>
);
};
我收到上面發佈的同樣的錯誤。
我也嘗試過不同的組合:
import app1 from '../../app1/app1Bundle'; // without curly braces
甚至剛剛起步的腳本作爲一個正常的js腳本
import '../../app1/app1Bundle';
或 要求(」 ../ ../ APP1/app1Bundle');
,然後試圖呈現一個正常的div標籤「APP1」的ID
const HomePage =() => {
return (
<div>
<div id="app1"></div>
<h1>App 2</h1>
</div>
);
};
似乎沒有任何工作,因爲我仍然得到同樣的錯誤。 我認爲問題是腳本加載的時間和元素的渲染。當捆綁腳本正在搜索時,我認爲div還不存在。
我似乎得到相同的錯誤。你能否詳細說明我應該在代碼中更改哪些內容? –