![](/img/trans.png)
[英]Can I run my Node.js/Express backend and React.js frontend together in the same file structure?
[英]How can I use a function in a separate js file in my node.js-Backend as well as in my frontend?
在我的Web應用程序中,我在一些js文件中具有一些數學函數。 為了能夠在我的Node.js后端中要求它,我必須使用module.exports在所述文件中導出該函數。
//Needed for Usage in the Back-end module.exports = { calculate: calculate };
現在,當我想在前端使用此文件時,它仍然包含上面的代碼段,雖然不是致命的,但有點不方便。
有沒有更好的方法可以在前面和后面使用js文件而不重復代碼?
此致Claas M.
您始終可以檢查自己是否在Node.js中,如果不是,則僅以不同的方式使用該函數
if(typeof process !== 'undefined' && process.argv[0] === "node") {
// this is node
}
只需檢查是否存在module.exports
就可以了
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
calculate: calculate
};
} else {
window.calculate = calculate;
}
在腳本文件末尾使用此命令:
var Ducky = {
quak: function quak() {
return "Quack!";
}
};
if (exports !== undefined && exports !== null) {
exports.Ducky = Ducky;
} else if (module !== undefined && module !== null &&
module.exports !== undefined && module.exports !== null) {
module.exports.Ducky = Ducky;
} else if (window !== undefined && window !== null) {
window.Ducky = Ducky;
}
編輯:
您可能希望將這些內容打包在(function(){})()
表達式中,因此Ducky不會是全局變量。
如果服務器端模塊中沒有任何require
,而只有module.exports
,則可以在加載任何此類模塊之前將服務器端代碼保留為原樣,並在客戶端頁面中放一個小片段:
客戶端JavaScript
window.module = {
set exports (obj) {
for(p in obj) {
obj.hasOwnProperty(p) && (window[p] = obj[p]);
}
}
};
此代碼段會將服務器端代碼中定義的所有導出函數以及與module.exports
一起導出的函數module.exports
window
。 這樣,您無需通過添加冗余內容來修改所有共享代碼,而只需將一小段代碼僅添加到客戶端一次。
Plunker
http://plnkr.co/edit/2fWlNN5w7R4Mcdv9VJ5T?p=preview
從IE9開始的所有現代瀏覽器均支持:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.