Javascript 如何将opening_hours.js包含到node.js脚本中?
我想在node.js shell脚本中使用。该库及其依赖项在本地可用:Javascript 如何将opening_hours.js包含到node.js脚本中?,javascript,node.js,Javascript,Node.js,我想在node.js shell脚本中使用。该库及其依赖项在本地可用: js/suncalc.js js/opening_hours.js 我想在脚本中使用opening_hours.js,如下所示: #!/usr/bin/env node // TODO: load libraries var oh = new opening_hours('We 12:00-14:00'); 感兴趣的可能是javascript文件的以下摘录: 从opening_hours.js开始: 从suncal
- js/suncalc.js
- js/opening_hours.js
#!/usr/bin/env node
// TODO: load libraries
var oh = new opening_hours('We 12:00-14:00');
感兴趣的可能是javascript文件的以下摘录:
从opening_hours.js开始:
从suncalc.js:
问题在于
opening_hours.js
希望SunCalc作为NPM模块安装。您需要更新发布代码中的require
语句,以指向本地SunCalc文件:
// make the library accessible for the outside world {{{
if (typeof exports === 'object') {
var moment, SunCalc, i18n;
// For Node.js.
SunCalc = root.SunCalc || require('./suncalc'); // CHANGED
try { // as long as it is an optional dependency
moment = root.moment || require('moment');
} catch (error_pass) { error_pass }
try { // as long as it is an optional dependency
i18n = require('./locales/core');
} catch (error_pass) { error_pass }
module.exports = factory(SunCalc, moment, i18n, holiday_definitions, word_error_correction, lang);
} else {
// For browsers.
root.opening_hours = factory(root.SunCalc, root.moment, root.i18n, holiday_definitions, word_error_correction, lang);
}
//* }}} */
require('./js/opening_hours')
有什么问题吗?这引发了:错误:找不到模块'suncalc'
。我看到了问题,我将添加一个答案require('./js/suncalc')require('./js/opening_hours')
引发相同的错误。它们可以在本地用于项目的其他部分。这样以前的错误就消失了。我的方法调用时出现新错误:ReferenceError:未定义开放时间
。除此之外:在不更改库的情况下解决此问题的任何方法-请记住,它仍然必须用于项目的“浏览器”部分。您可以将开放时间安装为npm模块,而无需将其保存在本地Lyokay,谢谢。我将在脚本中使用NPM模块。您在库中所做的更改是一个主题吗?NPM模块将SunCalc安装为一个依赖项,这样在您使用模块后就不需要进行更改:我现在将这两个库都安装为NPM模块。那么这里就不需要改变了。
// export as AMD module / Node module / browser variable
if (typeof define === 'function' && define.amd) define(SunCalc);
else if (typeof module !== 'undefined') module.exports = SunCalc;
else window.SunCalc = SunCalc;
// make the library accessible for the outside world {{{
if (typeof exports === 'object') {
var moment, SunCalc, i18n;
// For Node.js.
SunCalc = root.SunCalc || require('./suncalc'); // CHANGED
try { // as long as it is an optional dependency
moment = root.moment || require('moment');
} catch (error_pass) { error_pass }
try { // as long as it is an optional dependency
i18n = require('./locales/core');
} catch (error_pass) { error_pass }
module.exports = factory(SunCalc, moment, i18n, holiday_definitions, word_error_correction, lang);
} else {
// For browsers.
root.opening_hours = factory(root.SunCalc, root.moment, root.i18n, holiday_definitions, word_error_correction, lang);
}
//* }}} */