JuniorTour / vue-template-babel-compiler

Enable Optional Chaining(?.), Nullish Coalescing(??) and many new ES syntax for Vue.js SFC based on Babel
https://www.npmjs.com/package/vue-template-babel-compiler
118 stars 9 forks source link

[Question] nullish coalescing (??) only work for Node.js version >= 14 #29

Open LYSSION opened 2 years ago

LYSSION commented 2 years ago

Current behavior

// your code goes here
<div>输出:{{info.aaa ?? 'empty'}}</div>

https://github.com/LYSSION/vue-demo

环境:nodejs12.22.1

复现步骤 1.拉取仓库代码 2.npm run serve 3.向app.vue中添加

输出:{{info.aaa ?? 'empty'}}
4.输出错误

 ERROR  Failed to compile with 1 error                                                                        3:47:11 PM

 error  in ./src/App.vue?vue&type=template&id=7ba5bd90&

Module Error (from ./node_modules/vue-loader/lib/loaders/templateLoader.js):
(Emitted value instead of an instance of Error)

  Errors compiling template:

  invalid expression: Unexpected token '?' in

    "输出:"+_s(info.aaa ?? 'empty')

  Raw expression: 输出:{{info.aaa ?? 'empty'}}

  2  |  <div id="app">
  3  |    <img alt="Vue logo" src="./assets/logo.png">
  4  |    <div>输出:{{info.aaa ?? 'empty'}}</div>
     |         ^^^^^^^^^^^^^^^^^^^^^^^^^^
  5  |    <!-- <div>输出:{{info.title ?? 'empty'}}</div> -->
  6  |    <!-- <div>输出:{{info?.title?.text}}</div> -->

 @ ./src/App.vue?vue&type=template&id=7ba5bd90& 1:0-396 1:0-396
 @ ./src/App.vue
 @ ./src/main.js
JuniorTour commented 2 years ago

感谢你的反馈,似乎确实是个 bug,

如果你有兴趣排查,定位问题,并发个MR 修复的话,可以参考这个文档:https://github.com/JuniorTour/vue-template-babel-compiler/blob/main/CONTRIBUTING.md

有任何疑问可以随时联系我😁

JuniorTour commented 2 years ago

The root cause is vue-template-compiler use new Function(("return " + exp))to detect if js expression is valid.

https://github.com/vuejs/vue/blob/6aa11872c88481dfa2da151536317176c48f226c/packages/vue-template-compiler/build.js#L4548-4551

eg: "_s(null ?? 'Nullish Coalescing enabled') will be convert to new Function and throw an error in Node.js V12

SyntaxError: Unexpected token '?'
    at new Function (<anonymous>)
    at checkExpression (build.js:4550)
    at checkNode (build.js:4508)
    at checkNode (build.js:4504)
    at checkNode (build.js:4504)
    at detectErrors (build.js:4479)
    at Object.compile (build.js:4808)
    at compileTemplate (index.js:160)
    at actuallyCompile (compileTemplate.js:72)
    at compileTemplate (compileTemplate.js:33)
    at Object.module.exports (templateLoader.js:46)
    at LOADER_EXECUTION (LoaderRunner.js:119)
    at runSyncOrAsync (LoaderRunner.js:120)
    at iterateNormalLoaders (LoaderRunner.js:232)
    at iterateNormalLoaders (LoaderRunner.js:221)
    at LoaderRunner.js:236

But actually this code snippet of code will work after this compiler.

So maybe we can disable this expression check?


Temp workaround is:

  1. update Node to v14+;
  2. Don't use Nullish coalescing;