Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamically calculate __dirname and __filename when --node is passed #1725

Merged
merged 1 commit into from Feb 7, 2018
Merged

Dynamically calculate __dirname and __filename when --node is passed #1725

merged 1 commit into from Feb 7, 2018

Commits on Dec 25, 2017

  1. Dynamically calculate __dirname and __filename when --node is passed

    When `--no-commondir` is set (as a consequence of `--node` for example),
    it will cause the final bundle to hardcode absolute values of the
    machine that generated the bundle in order to resolve `__dirname` and
    `__filename`. For example, consider a `foo.js` file containing:
    
    ```js
    console.log(__dirname);
    console.log(__filename);
    ```
    
    Calling `browserify --node` on it results in:
    
    ```js
    (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){
    (function (__filename,__dirname){
    console.log(__dirname);
    console.log(__filename);
    
    }).call(this,"/Users/jviotti/Projects/playground/node-browserify/foo.js","/Users/jviotti/Projects/playground/node-browserify")
    },{}]},{},[1]);
    ```
    
    Notice the absolute paths at the end of the bundle. This means that
    Browserify node users can't generate a bundle in one machine, and expect
    it to run without issues on another machine.
    
    As a solution, we can use the final bundle's `__dirname` to dynamically
    resolve every file's `__dirname` and `__filename`. This change only
    takes place when `--node` is set, and keeps Browserify backwards
    compatible.
    
    For example, the above output might contain the following line:
    
    ```
    }).call(this,require("path").join(__dirname,"foo.js"),require("path").join(__dirname,"."))
    ```
    
    Fixes: #1723
    See: balena-io/etcher#1429
    See: balena-io/etcher#1409
    Signed-off-by: Juan Cruz Viotti <jviotti@openmailbox.org>
    Signed-off-by: Juan Cruz Viotti <jv@jviotti.com>
    Juan Cruz Viotti authored and jviotti committed Dec 25, 2017
    Configuration menu
    Copy the full SHA
    9306a57 View commit details
    Browse the repository at this point in the history