JavaScript - 如何注入不同的函数实现,例如 alert(与 web 和 Node 共享模块.js服务器端)

JavaScript - how to inject different implementation of function e.g. alert (sharing modules with web & Node.js server side)

本文关键字:web 例如 alert Node 服务器端 js 模块 共享 函数 何注入 注入      更新时间:2023-09-26

情况:有大量的JavaScript文件。我想在 Node.js 上运行它们。

但是有几个地方,例如 使用alert(),会导致 Node.js 失败。

当然,有办法查看每个文件并添加导入,例如

alert = require('console').log

但这会阻止这些文件在INN浏览器(在客户端)工作。

有没有办法注入不同的alert实现?那是在不修改源的情况下更改/添加函数实现?

在代码的开头,写:

global.alert = console.log;

基本版本

在文件silentalert.js

if(typeof global != "undefined"){
  global.alert = typeof console != "undefined" && console.log ? console.log.bind(this) : function(){};
}

在 NodeJS 脚本中:

require('./silentalert');

此代码将在 NodeJS 中打印警报消息以console.log,但在浏览器中运行时仍将使用 alert

下一个实现提供了一种更通用的方法。


跨平台版本

在文件silentalert.js

var g           = typeof global != "undefined" ? global : (typeof window != "undefined") ? window : {};
var c           = typeof console != "undefined" && console.log ? console.log.bind(this) : function(){};
var _old        = g.alert;
var silentalert = function(activate){
  g.alert       = activate ? c : _old;
};
if(typeof module !== "undefined"){module.exports = silentalert;}

在 NodeJS 脚本中:

var silentalert = require('./silentalert');
silentalert(true); 
// or silentalert(typeof window == "undefined") if you just want to silent alert() on NodeJS
// your script...
silentalert(false);

您甚至可以直接在HTML页面中包含silentalert.js:

<script src="./silentalert.js" type="text/javascript"></script>
<script type="text/javascript">
silentalert(true);
// your script...
silentalert(false);
</script>

注意:如果您需要支持 IE8 .bind在这种情况下不可用,请替换:

var c = typeof console != "undefined" && console.log ? console.log.bind(this) : function(){};

var c = typeof console != "undefined" && console.log ? function(){console.log.apply(console, arguments);} : function(){};

这两个脚本都允许您在 NodeJS 中静默警报,同时仍然能够在客户端使用它们。