简体   繁体   English

Nuxt:使用“可选链接运算符”运算符 (.?)

[英]Nuxt: using `optional chaining operator` operator (.?)

Nuxt 2.12.2 throw error on build when trying to use object?.key . Nuxt 2.12.2 在尝试使用object?.key时在构建时抛出错误。

Module parse failed: Unexpected token (311:25)                                                                                                                                                 friendly-errors 10:36:40
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file

So it because babel in Nuxt configured to support older browsers like IE9 that I did not need in my project.所以这是因为 Nuxt 中的babel配置为支持我的项目中不需要的旧浏览器,例如IE9

In another project, I just put .bablelrc在另一个项目中,我只是把.bablelrc

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 2 Chrome versions"]
      }
    }]
  ]
}

but in Nuxt .bablelrc are disabled.但在 Nuxt .bablelrc中被禁用。 so how can I make optional chaining operator work?那么如何使optional chaining operator工作?

by telling Nuxt to support just modern browsers.通过告诉 Nuxt 只支持现代浏览器。 or added the @babel/plugin-proposal-optional-chaining或添加@babel/plugin-proposal-optional-chaining

As Nuxtjs Doc describe, .babelrc is ignored by default.正如Nuxtjs Doc描述的那样,默认情况下会忽略.babelrc

I solved this question by the below config.我通过以下配置解决了这个问题。

// in nuxt.config.js
{
  // ...
  build: {
    // ....
    babel: {
      plugins: [
        '@babel/plugin-proposal-optional-chaining'
      ]
    }
  }
}

Of course, before that, you should install @babel/plugin-proposal-optional-chaining当然,在此之前,你应该安装@babel/plugin-proposal-optional-chaining

npm i -D @babel/plugin-proposal-optional-chaining

I hope it helps you.我希望它对你有帮助。

Try vue-template-babel-compiler试试vue-template-babel-compiler

It uses Babel to enable Optional Chaining(?.) , Nullish Coalescing(??) and many new ES syntax for Vue.js SFC .它使用BabelVue.js SFC启用Optional Chaining(?.)Nullish Coalescing(??)和许多新的 ES 语法。

Github Repo: vue-template-babel-compiler Github 回购:vue-template-babel-compiler

DEMO演示

演示图像

Usage用法

1. Install 1.安装

npm install vue-template-babel-compiler --save-dev

2. Config 2. 配置

1. Vue-CLI 1.Vue-CLI

DEMO project for Vue-CLI Vue-CLI 的 DEMO 项目

2. Nuxt.js 2. Nuxt.js

DEMO project for Nuxt.js Nuxt.js 的演示项目

// nuxt.config.js
export default {
  // Build Configuration: https://go.nuxtjs.dev/config-build
  build: {
    loaders: {
      vue: {
        compiler: require('vue-template-babel-compiler')
      }
    },
  },
  // ...
}

Please refer to REAMDE for detail usage 详细使用请参考 REAMDE

Support for Vue-CLI, Nuxt.js, Webpack , any environment use vue-loader v15+ .支持Vue-CLI, Nuxt.js, Webpack ,任何环境使用vue-loader v15+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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