简体   繁体   中英

JS + Browserify: Function not accessible/defined after Browserify build

I have defined a self firing function.

'use strict'

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

When the browser loads the script, the function fires and the output is logged to the console. Likewise, test.testMe() results in a log to the cosole.

However, I want to include a number of NPM modules is my project. To to do this, I am using Browserify.

The problem is, that the Browserify built code doesn't work the same way. The outer function fires immediately but the inner funcion cannot be accessed with test.testMe() . I get an error instead:

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

Why? How can I make the function available as before? Why does the code behave differently after going through Browserify?

For reference, here is the browserified code:

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

Why?

As you can see in the browserified code, your code is now inside a function, which means that test is declared locally to that function. You cannot access it in the console because it is not global.

How can I make the function available as before?

You can either explicitly create a global variable or export the object and configure browserify to expose that export .

Why does the code behave differently after going through Browserify?

The browserfied code is different than your code. Also see the first paragraph.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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