Using babel-register in my cli npm app works locally, but not globally after publish

前端 未结 1 1245
生来不讨喜
生来不讨喜 2021-01-03 04:57

I have developed a javascript CLI app that is using ES2015 code with babel as compiler. (babel-require hook)

The app works perfectly locally, but when I pu

1条回答
  •  攒了一身酷
    2021-01-03 05:12

    Ok, I figured out what was the issue. I was on the right track thinking there was something forbidding the compilation to happen.

    TL;DR

    babel-register hook does not take ignore and only options from the .babelrc file, but it does from its arguments.

    The fix in ./bootstrap.js:

    require('babel-register')({
      ignore: [],
      only: [/src/],
    });
    require('./src/app.js');
    
    • The ignore switch will disable ignoring files which match node_modules in their path, which is the case for every global module.
    • The only switch then enables compilation of the files of my project src directory.

    Now, if you're interested, I will describe the steps I took to resolve the issue, because I think I did it right (this time :))...

    Story of the troubleshooting:

    • First, I needed to install node-debug commandline tool

      $ sudo npm install -g node-inspector
      
    • Then launch my app with it (--debug-brk switch asks to stop execution at first line)

      $ node-debug --debug-brk myapp
      
    • Open my browser at the local URL provided by node-debug, and voila see my app code

    • Place a breakpoint the line just above the require('./scr/app.js'); statement
    • Click 'play' to continue process execution until that line
    • Here starts the tedious task of climbing the error trace using 'step over' and 'step inside' buttons : when the next statement is 'outside' of your error trace (see the one above in the question), I could 'step over'. If the next statement is one of the functions of the trace, 'step in'.
    • I then realized, by looking at the 'scope variable' watches, when in the Object.require.extension method, in file babel-register/lib/node.js, that ignore and only variables were undefined, despite I wanted them to be defined!
    • I stepped inside the method shouldIgnore of the same file, which confirmed my fears : this function checks for node_modules in the path, if !ignore && !only and returns true (ignore file) if it matches. This is ultimately what caused my ES2015 files to not compile.

      babel-register/lib/node.js:120:
      function shouldIgnore(filename) {
        if (!ignore && !only) {  // here `ignore` and `only` were null, despite .babelrc values
          return getRelativePath(filename).split(_path2["default"].sep).indexOf("node_modules") >= 0;
        } else {
          return _babelCore.util.shouldIgnore(filename, ignore || [], only);
        }
      }
      
    • I then guessed that I would have to specify thoses switches directly in babe-register arguments.

    0 讨论(0)
提交回复
热议问题