使用纯 npm 构建在 NW.js (node-webkit) 应用程序中加载 Bootstrap

Loading Bootstrap in NW.js (node-webkit) app with pure npm build

我正在尝试使用 NW.js. Inspired by some posts including this one 构建一个简单的桌面应用程序,我想尝试一种没有任何 bowergruntgulp.

所以我继续使用 jquerybootstrap 库作为 npm 模块安装。当我像这样在我的应用程序 javascript 中注入模块时:

global.jQuery = $ = require("jquery");
var bootstrap = require("bootstrap");

我从 bootstrap 收到 ReferenceError: document is not defined。我可以用老式的方式通过 html 文档加载 bootstrap

<script type="text/javascript" src="node_modules/bootstrap/dist/js/bootstrap.js"></script>

我在问自己,在脚本文件中通过 require 加载 bootstrap 是不是一个愚蠢的想法?基本上,我在那里不需要它。它可以通过 html 中的脚本标签加载。最佳做法是什么?我很困惑。

更新。解决方案

根据@Kuf 的建议,我创建了一个 build.js 脚本

var copyfiles = require('copyfiles');
copyfiles(["node_modules/bootstrap/dist/js/bootstrap.js", "vendor/js"], true, function (err) {
    if (err) return console.error(err);
});
copyfiles(["node_modules/bootstrap/dist/css/bootstrap.css", "vendor/css"], true, function (err) {
    if (err) return console.error(err);
});

prestart 钩子触发:

"scripts": {
  "build": "node build.js",
  "prestart": "npm run build"
}

它允许我通过方便的路径访问 bootstrap 资源:

<link href="vendor/css/bootstrap.css" rel="stylesheet">
<script type="text/javascript" src="vendor/js/bootstrap.js"></script>

我认为发生错误是因为您是 运行 没有 window 上下文的要求。 运行 你来自哪里?请注意,对于代码 运行 来自 node-main:

window: ... is not available at the time the script is loaded, because the script is executed before the DOM window load. (source)

即使在使用 require 导入 JS 时,您仍然需要包含 css files.I 不要认为有 'clean' 或开箱即用的解决方案然而。尽管您所做的肯定会起作用,但它会生成奇怪且不自然的脚本路径。

我会添加一个构建 script:

"scripts": {
    "build": "node build.js"
  }

in package.json 将 bootstrap 从 node_modules 复制到 '/dist/' 以使路径更清晰。