Unexpected token: name (hook):loader中同時(shí)設(shè)置include與exclude引發(fā)的血案

背景

某日,項(xiàng)目中jenkins構(gòu)建之后,構(gòu)建輸出中顯示有錯(cuò)誤,輸出如下

ERROR in static/js/hotTemplateManage.1bbbc115c41b7f7ccd26.js from UglifyJs
Unexpected token: name (hook) [static/js/hotTemplateManage.1bbbc115c41b7f7ccd26.js:17404,8]

ERROR in static/js/templateManage.e90b3eb370ff27ea8d3c.js from UglifyJs
Unexpected token: name (hook) [static/js/templateManage.e90b3eb370ff27ea8d3c.js:17404,8]

分析

從輸出上看,是UglifyJs報(bào)錯(cuò)了, 還是語法錯(cuò)誤

先找打包后的代碼看看 dist/static/js/hotTemplateManage.1bbbc115c41b7f7ccd26.js 第17404行

    let hook; // 就是這行報(bào)錯(cuò)
    if (moduleIdentifier) {
        // server build
        hook = function (context) {
            // 2.3 injection
            context =
                context || // cached call
                    (this.$vnode && this.$vnode.ssrContext) || // stateful
                    (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext); // functional
            // 2.2 with runInNewContext: true
            if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
                context = __VUE_SSR_CONTEXT__;
            }
            // inject component styles
            if (style) {
                style.call(this, createInjectorSSR(context));
            }
            // register component module identifier for async chunk inference
            if (context && context._registeredComponents) {
                context._registeredComponents.add(moduleIdentifier);
            }
        };
        // used by ssr in case component is cached and beforeCreate
        // never gets called
        options._ssrRegister = hook;
    }
    else if (style) {
        hook = shadowMode
            ? function (context) {
                style.call(this, createInjectorShadow(context, this.$root.$options.shadowRoot));
            }
            : function (context) {
                style.call(this, createInjector(context));
            };
    }
    if (hook) {
        if (options.functional) {
            // register for functional component in vue file
            const originalRender = options.render;
            options.render = function renderWithStyleInjection(h, context) {
                hook.call(context);
                return originalRender(h, context);
            };
        }
        else {
            // inject component registration as beforeCreate hook
            const existing = options.beforeCreate;
            options.beforeCreate = existing ? [].concat(existing, hook) : [hook];
        }
    }
    return script;
}

/* script */
const __vue_script__ = script;
/* template */
var __vue_render__ = function() {
  var _obj, _obj$1;
  var _vm = this;
  var _h = _vm.$createElement;
  var _c = _vm._self._c || _h;
  return _c(
    "div",
    {
      directives: [
        {
          name: "observe-visibility",
          rawName: "v-observe-visibility",
          value: _vm.handleVisibilityChange,
          expression: "handleVisibilityChange"
        }
      ],
      staticClass: "vue-recycle-scroller",
      class:
        ((_obj = {
          ready: _vm.ready,
          "page-mode": _vm.pageMode
        }),
        (_obj["direction-" + _vm.direction] = true),
        _obj),
      on: {
        "&scroll": function($event) {
          return _vm.handleScroll($event)
        }
      }
    },
    [
      _vm.$slots.before
        ? _c(
            "div",
            { staticClass: "vue-recycle-scroller__slot" },
            [_vm._t("before")],
            2
          )
        : _vm._e(),
      _vm._v(" "),
      _c(
        "div",
        {
          ref: "wrapper",
          staticClass: "vue-recycle-scroller__item-wrapper",
          style:
            ((_obj$1 = {}),
            (_obj$1[_vm.direction === "vertical" ? "minHeight" : "minWidth"] =
              _vm.totalSize + "px"),
            _obj$1)
        },
        _vm._l(_vm.pool, function(view) {

代碼可以看出:

  • 1 不是開發(fā)者寫的代碼,更像是某個(gè)包打包后的代碼

  • 2 項(xiàng)目中有配置babel-loader, 為啥這里的 let未轉(zhuǎn)換為 var,推測(cè)是不是babel打包有什么問題

  • 3 對(duì)比其他打包后的js發(fā)現(xiàn),UglifyJs報(bào)錯(cuò)之后 hotTemplateManage.jstemplateManage.js 均未壓縮,其他未報(bào)錯(cuò)的js中 let 均轉(zhuǎn)換為 var,看來babel語法轉(zhuǎn)換沒問題

  • 4 從未壓縮js上下文中,看到有調(diào)用 vue-recycle-scroller__item-wrapper這樣一個(gè)樣式類,查到這個(gè)樣式類是vue-virtual-scroller這個(gè)包運(yùn)行時(shí)給節(jié)點(diǎn)添加的

  • 5 于是在 node_modules/vue-virtual-scroller/dist/vue-virtual-scroller.umd.js中找到了,跟上述代碼一模一樣的代碼,確定問題出在這個(gè)包中,這個(gè)包中的代碼 let語法并未轉(zhuǎn)換為var

綜合以上

A => babel語法轉(zhuǎn)換沒問題, babel的本身配置沒問題

B => 打包有問題

C => 問題出在 node_modules/vue-virtual-scroller 這個(gè)包的代碼上

解決問題

既然是因?yàn)?code>node_modules/vue-virtual-scroller的let語法并未轉(zhuǎn)換為var, 那直接把這個(gè)包納入babel-loader打包范圍應(yīng)該就好了

  • 1 先找babel-loader配置
{
    test: /\.js$/,
    use: isProduction ? {
        loader: 'babel-loader',
        options: {
            cacheDirectory: true
        }
    } : [{
        loader: 'cache-loader',
        options: {
            cacheDirectory: resolve('.cache-loader')
        }
    }, {
        loader: 'babel-loader',
        options: {
            cacheDirectory: true
        }
    }],
    include: [
        resolve('/node_modules/vue-virtual-scroller'),
        resolve('/node_modules/css-vars-ponyfill'),
        isProduction ? resolve('/node_modules/highlight.js') : [],
        resolve('src')
    ],
    exclude: /(node_modules\/(?!vue-virtual-scroller))|(node_modules\/(?!css-vars-ponyfill))|(node_modules\/(?!highlight.js))/
}

可以發(fā)現(xiàn)其實(shí)include已經(jīng)包含了vue-virtual-scroller,但是 exclude中也配置了/node_modules/vue-virtual-scroller,此時(shí)exclude的優(yōu)先級(jí)比include的優(yōu)先級(jí)高,故打包時(shí)/node_modules/vue-virtual-scroller是不會(huì)被babel-loader處理的。

解決方式

直接干掉exclude配置就好

{
    test: /\.js$/,
    use: isProduction ? {
        loader: 'babel-loader',
        options: {
            cacheDirectory: true
        }
    } : [{
        loader: 'cache-loader',
        options: {
            cacheDirectory: resolve('.cache-loader')
        }
    }, {
        loader: 'babel-loader',
        options: {
            cacheDirectory: true
        }
    }],
    include: [
        resolve('/node_modules/vue-virtual-scroller'),
        resolve('/node_modules/css-vars-ponyfill'),
        isProduction ? resolve('/node_modules/highlight.js') : [],
        resolve('src')
    ],
    //exclude: /(node_modules\/(?!vue-virtual-scroller))|(node_modules\/(?!css-vars-ponyfill))|(node_modules\/(?!highlight.js))/
}

最后npm run build 錯(cuò)誤圓滿解決

【注】若引用,請(qǐng)注明出處哈,版權(quán)我所有哈

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容