2016-05-26 33 views
0

我已经定义了自激功能。JS + Browserify:在Browserify构建后无法访问/定义的功能

'use strict' 

var test = (function(){ 
    console.log('This should log to console immediately.') 
    function testMe() { 
     console.log('Test successful!') 
    } 
    return { 
     testMe: testMe 
    } 
})() 

当浏览器加载脚本时,该函数触发并将输出记录到控制台。同样,test.testMe()会导致日志记录到cosole。

但是,我想包括一些NPM模块是我的项目。为了做到这一点,我使用了Browserify。

问题是,Browserify构建的代码不能以相同的方式工作。外部函数立即触发,但内部函数不能通过test.testMe()访问。我得到一个错误,而不是:

index.html:32 Uncaught ReferenceError: test is not defined

为什么?我如何使功能可以像以前一样可用?为什么代码在经过Browserify后会有不同的表现?

仅供参考,这里是browserified代码:

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ 
// main.js 
var test = (function(){ 
    console.log('This should log to console immediately.') 
    function testMe() { 
     console.log('Test successful!') 
    } 
    return { 
     testMe: testMe 
    } 
})() 

},{}]},{},[1]); 

回答

0

为什么?

正如你可以在browserified代码中看到的,现在您的代码是一个函数,这意味着test声明本地该函数内。您不能在控制台中访问它,因为它不是全局的。

如何使功能可以像以前一样可用?

您可以选择explicitly create a global variable或导出对象和configure browserify to expose that export

为什么通过Browserify后代码的行为不同?

浏览代码与您的代码不同。另见第一段。