简体   繁体   English

结合使用Browserify和gulp时未定义Navigo

[英]Navigo not defined when using Browserify with gulp

I can't get Navigo (npm package) to work with Browserify and Gulp 我无法让Navigo(npm软件包)与Browserify和Gulp一起使用

My file structure (only including relevant stuff) 我的文件结构(仅包含相关内容)

-index.html
-build
    -js
        -modules.js
        -routing.js
-js
    -modules.js

My bundle task in my gulpfile.js that uses browserify to be able to use Navigo in my actual routing.js file 我的gulpfile.js中的捆绑包任务使用browserify能够在实际的routing.js文件中使用Navigo

gulp.task('bundlemods', function() {
    var bundleMods = browserify('./js/modules.js')
    .bundle()
    .on('error', console.error)
    .pipe(source('modules.js'))
    .pipe(gulp.dest('./build/js'));
});

Which outputs the following modules.js file 输出以下modules.js文件

Then in my routing.js I'm just trying to use Navigo as following: 然后在我的routing.js中,我只是尝试使用Navigo,如下所示:

function initRouting() {
    var rootUrl = null;
    var useHash = false;
    var router = new Navigo(rootUrl, useHash);

    router.on(function () {
        runHome();
    })
    .resolve();
}

However, this yields the error Uncaught ReferenceError: Navigo is not defined 但是,这会产生错误Uncaught ReferenceError: Navigo is not defined

Also this is how my index.html file looks (relevant parts once again) 这也是我的index.html文件的外观(再次是相关部分)

<!doctype html>
<html>
<head>
/* stuff */
</head>
<body>
    <main>
        /* stuff */
    </main>
    <script src="build/js/modules.js"></script>
    <script src="build/js/routing.js"></script>
    /* other scripts */
</body>
</html>

What is the reason it is still undefined? 它仍然不确定的原因是什么? How do I actually use Navigo once I've used Browserify to generate my modules file? 使用Browserify生成模块文件后,如何实际使用Navigo? Does it have something to do with global scopes or something else I'm missing? 它与全局范围有关还是我所缺少的其他东西?

Of course browserify prevent variables to leak in global scope. 当然,browserify可以防止变量在全局范围内泄漏。 If you want to have it gloabally available you should explicitly attach it to global scope: 如果要让它全局可用,则应将其显式附加到全局范围:

Navigo = require('navigo');

not using var key will attach Navigo var to global scope and when you browserify it, your global will be window and Navigo is available from anywhere. 不使用var键会将Navigo var附加到全局作用域,当您对其进行浏览器化时,您的全局变量将是window,并且Navigo在任何地方都可用。

If you don't want pollute global scope then you could just require it in routing.js : 如果您不想污染全局范围,则可以在routing.js中要求它:

var Navigo = require('navigo');
function initRouting() {
    var rootUrl = null;
    var useHash = false;
    var router = new Navigo(rootUrl, useHash);

    router.on(function () {
        runHome();
    })
    .resolve();
}

and then browserify this file instead. 然后将其浏览器化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM