Home Ask Login Register

Developers Planet

Your answer is one click away!

nolexa February 2016

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

I'm trying to build a simple desktop app with NW.js. Inspired by some posts including this one, I wanted to try a pure npm approach without any bower, grunt, or gulp.

So I go ahead and use jquery and bootstrap libraries installed as npm modules. When I'm injecting the modules in my app's javascript like this:

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

I'm getting a ReferenceError: document is not defined from bootstrap. I can load bootstrap through the html document in the old-fashioned way though:

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

I'm asking myself if it's a stupid idea to load bootstrap trough require in the script file? Basically, I don't need it there. It can be loaded via a script tag in html. What are the best practices? I'm confused.

Update. The solution

Having taken the advice from @Kuf, I created a build.js script

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);

triggered by a prestart hook:

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

which allows me to access bootstrap resources by convenient paths:

<link href="vendor/cs        


Kuf February 2016

I think the error occurs because you are running the require without window context. Where are you running the include from? notice that for code running from node-main:

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

Even when importing the JS using require, you still need to include the css files.I don't think there is a 'clean' or out-of-the-box solution yet. Although what you are doing will definitely work, it will generate weird and not natural script path.

I would add a build script:

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

in package.json to copy bootstrap from node_modules into '/dist/' to make the path cleaner.

Post Status

Asked in February 2016
Viewed 3,470 times
Voted 10
Answered 1 times


Leave an answer

Quote of the day: live life