Nuxt 2.12.2 throw error on build when trying to use 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.
In another project, I just put .bablelrc
{
"presets": [
["env", {
"targets": {
"browsers": ["last 2 Chrome versions"]
}
}]
]
}
but in Nuxt .bablelrc
are disabled. so how can I make optional chaining operator
work ?
by telling Nuxt to support just modern browsers. or added the @babel/plugin-proposal-optional-chaining
You can use optional chaining when attempting to call a method which may not exist. This can be helpful, for example, when using an API in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device.
To enable optional chaining, you need to install a package. At the time of writing, optional chaining is not natively supported in Javascript, it is a new feature introduced in ES2020. Until it is fully adopted we can get all the optional goodness by installing a package!
It's also known as the ternary conditional operator because it combines some of what the ternary operator does together with the chaining operator, normally called dot notation. It's similar to the traditional dot syntax which lets you access an object and its properties.
The optional chaining ?. is a safe way to access nested object properties, even if an intermediate property doesn't exist.
Try vue-template-babel-compiler
It uses Babel
to enable Optional Chaining(?.)
, Nullish Coalescing(??)
and many new ES syntax for Vue.js SFC
.
npm install vue-template-babel-compiler --save-dev
DEMO project for Vue-CLI
DEMO project for 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
Support for Vue-CLI, Nuxt.js, Webpack
, any environment use vue-loader v15+
.
As Nuxtjs Doc describe, .babelrc
is ignored by default.
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
npm i -D @babel/plugin-proposal-optional-chaining
I hope it helps you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With