Nuxt: using `optional chaining operator` operator (.?) - javascript

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

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.

Try vue-template-babel-compiler
It uses Babel to enable Optional Chaining(?.), Nullish Coalescing(??) and many new ES syntax for Vue.js SFC.
Github Repo: vue-template-babel-compiler
DEMO
Usage
1. Install
npm install vue-template-babel-compiler --save-dev
2. Config
1. Vue-CLI
DEMO project for Vue-CLI
2. Nuxt.js
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+.

Related

Tailwind and storybook setup postcss config issue

I have the following postccs.config.js file:
module.exports = {
plugins: [
require("postcss-import"),
require("tailwindcss"),
require("autoprefixer"),
],
}
which allows me to run tailwind and storybook together, however when I try to run my application, I get this error:
Error: A PostCSS Plugin was passed as a function using require(), but it must be provided as a string.
Is there a way to provide a specific storybook postcss config or even a better way for the 2 to work with the same config?
you need to execute the require.
Your config should look like this:
module.exports = {
plugins: [
require('postcss-import')(),
require('tailwindcss')('./tailwind.config.js'), //This refers to your tailwind config
require('autoprefixer'),
],
};
also this was answered before #see: How to configure VueJS + PostCss + Tailwind with Storybook

How can I transpile a dependency in node_modules with Nuxt 2?

I have read of issues with transpiling node_modules with Nuxt, but the new Nuxt 2 is said to have solved this with a transpile option in the nuxt.config.js file.
https://nuxtjs.org/api/configuration-build/#transpile
Here is what I have:
export default {
router: {
base: '/',
},
build: {
transpile: [
'choices.js',
'lazysizes',
'swiper',
'vee-validate'
],
extractCSS: true
},
srcDir: 'src/',
performance: {
gzip: true
},
render: {
compressor: {
threshold: 100
}
},
dev: false
}
I removed a few things that are unrelated to make it easier to read.
When I run npm run build (nuxt build) the compiled JS files contain references to es6 and es7 code such as const and let etc when it should be var.
I have isolated this issue to be coming from Swiper. It appears to internally depend on something called Dom7 that seems to be causing the problem.
I am wanting to compile these node_modules dependencies to es5 if possible. I'm not sure my current setup is actually doing anything at all in that regard.
I believe Nuxt uses vue-app for Babel, but I even tried the following to no success:
babel: {
presets: [
'#babel/preset-env'
],
plugins: [
'#babel/plugin-syntax-dynamic-import'
]
}
Not much joy there either. Nothing appears differently in the final build.
I am using Nuxt 2.1.0
Any help appreciated. Thanks!
You also need to transpile Dom7, so the Nuxt config should have:
build: {
transpile: [
'swiper',
'dom7',
],
}
I have the exact same issue.
The vendor option under build is deprecated, so it's simply ignored I believe from what I read here https://medium.com/nuxt/nuxt-2-is-coming-oh-yeah-212c1a9e1a67#a688
I managed to isolate my case to the "swiper" library. If I remove that from my project, all references to let, const or class are gone. I've tried the transpile option too, but it does not seem to have any effect.
Will you try to exclude swiper from your project to see if we can isolate the issue?

nuxtjs/axios What is the way to initialize version 4.4.0? (nuxt.js)

I would like to use the nuxtjs/axios module.
At first, I install the module with npm
npm install nuxtjs/axios
Then I set the options in the nuxt.config.js file.
modules: [
['# nuxtjs/axios', {
baseURL: 'http://localhost: 4000',
browserBaseURL: '/api',
}],
]
When I start the app with
npm run dev
I expect the below output:
In nuxtjs/axios version 2.1.0, it is built as follows.
[AXIOS] Base URL: http: // localhost: 3000 /, Browser: /
Why can not I see the above message?
I think it might be because of a problem with asyncData () {}.
Also browserBaseURL: '/ api' does not work.
You should seperate the axios module inclusion and the options.
modules: [
'#nuxtjs/axios'
],
axios: {
baseURL: 'http://localhost: 4000',
browserBaseURL: '/api'
}
This might just be a typo but the module should be installed using the npm i -S #nuxtjs/axios command (with the #).
Also by default the browserBaseURL is set to api, so you do not have to set it manually.
Please refer to the documentation for more information: https://github.com/nuxt-community/axios-module#browserbaseurl

Uglify SyntaxError: Unexpected token: punc ())

I am trying to use gulp in order to minify a folder containing JS files. However, one of the files has the above error, preventing it from being minified.
I managed to catch and print the error, which I've partially printed here:
JS_Parse_Error {
message: 'SyntaxError: Unexpected token: punc ())',
filename: 'ex.js',
line: 189,
col: 25,
pos: 6482,
stack: Error\n at new JS_Parse_Error (eval at <anonymous> ... )
plugin: 'gulp-uglify',
fileName: '.../js/ex.js',
showStack: false
}
The file in question contains the following, shortened:
function() {
...
$.confirm({
buttons: {
confirm: function() {
$.post('/ajax-handler', {
...
})
.done( function(response) {
var data = filterResponse(response);
if (data['status'] == 'success') {
sleep(1000).then(() => {
* ...
});
sleep(5000).then(() => {
...
});
} else {
console.log('Oops!');
}
})
.fail( function(err, status, response) {
...
});
},
cancel: function() {}
}
});
...
}
I added the "*" above in order to indicate the exact position listed by JS_Parse_Error.
// Update
From the comments ~ #imolit
 v2.0.0 (2018-09-14) - BREAKING CHANGES (link)
Switch back to uglify-js (uglify-es is abandoned, if you need uglify ES6 code please use terser-webpack-plugin).
Original answer before the update...
I hope you can get inspired by this solution which works with webpack. (link below)
Simply teach UglifyJS ES6
There are two versions of UglifyJS - ES5 and ES6 (Harmony), see on git
ES5 version comes by default with all the plugins, but if you install a Harmony version explicitly, those plugins will use it instead.
package.json
"uglify-js": "git+https://github.com/mishoo/UglifyJS2.git#harmony"
or
npm install --save uglify-js#github:mishoo/UglifyJS2#harmony
yarn add git://github.com/mishoo/UglifyJS2#harmony --dev
Webpack
To use it with webpack install also the webpack plugin
npm install uglifyjs-webpack-plugin --save-dev
yarn add uglifyjs-webpack-plugin --dev
then import the manually installed plugin
var UglifyJSPlugin = require('uglifyjs-webpack-plugin');
and replace it in code
- new webpack.optimize.UglifyJsPlugin({ ... })
+ new UglifyJSPlugin({ ... })
For more webpack info (Installation/Usage) see https://github.com/webpack-contrib/uglifyjs-webpack-plugin#install
npm install uglifyjs-webpack-plugin --save-dev is not enough
The main problem is "uglifyjs-webpack-plugin": "^0.4.6" in webpack's package.json
According to semver, ^0.4.6 := >=0.4.6 <0.5.0. Because of the leading zero, webpack will never use the 1.0.0-beta.2.
So after running npm i -D uglifyjs-webpack-plugin#beta, you need to do one more step which is rm -rf node_modules/webpack/node_modules/uglifyjs-webpack-plugin. Then webpack will pick up the version from node_modules/uglifyjs-webpack-plugin instead of node_modules/webpack/node_modules/uglifyjs-webpack-plugin
Update on 2018-04-18: webpack v4 does not have this issue
Add the babel-preset-es2015 dependency to fix this.
And also add 'es2015' in .babelrc file.
json
{
"presets": ["es2015"]
}
I am having the same issue, i found a great answers here that helped me to reach the the file that was causing the error.
Go to Rails Console and Paste:
JS_PATH = "app/assets/javascripts/**/*.js";
Dir[JS_PATH].each do |file_name|
puts "\n#{file_name}"
puts Uglifier.compile(File.read(file_name))
end
Hope it helps someone!
If you got this error using Grunt (grunt-contrib-uglify) the solution is to install ES6 version of the plugin:
npm install grunt-contrib-uglify-es --save-dev
For me it had nothing to do with Uglify not working correctly, but rather a dependency (in this case empty-promise) that has not been compiled to ES5 yet. As we just imported the raw source file, but babel is only transpiling files outside of node_modules, uglify got confused by the ES6 syntax.
Simply check if any dependency you've recently added might not have a "dist" build.
Add stage-3 to presets in .babelrc file.
{
"presets": [
"stage-3"
]
}

RegeneratorRuntime is not defined

I am trying to run Karma-babel-preprocessor and a straight forward ES6 generator:
//require('babel/polyfill');
describe("how Generators work", function() {
it("will allow generator functions", function() {
/*function * numbers() {
yield 1;
yield 2;
yield 3;
};*/
let numbers = {
[Symbol.iterator]:function*(){
yield 1;
yield 2;
yield 3;
}
}
let sum = 0;
for(n of numbers){
sum += n;
}
expect(sum).toBe(6);
});
});
From this I generated my test files (ES6 => ES5) with babel:
babel src --watch --out-dir tests
Then I run karma start I get error:
ReferenceError: regeneratorRuntime is not defined".
Relevant bits in karma.conf.js:
// list of files / patterns to load in the browser
files: [
'test-main.js',
{pattern: 'tests/*.js', included: true}
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'src/*.js': ['babel']
},
'babelPreprocessor': {
options: {
sourceMap: 'inline'
},
filename: function(file) {
return file.originalPath.replace(/\.js$/, '.es5.js');
},
sourceFileName: function(file) {
return file.originalPath;
}
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
Full project on github
I am able to use many ES6 features including arrows. Just no go on Generators.
Node js Env - updated December 2015
This question has already been answered, please see accepted answer UNLESS running within NodeJS environment.
If like myself, you had the same error message: 'ReferenceError: regeneratorRuntime is not defined' but were running Babel within a NodeJS environment, then simply doing the following will likely solve your problem:
npm install babel-polyfill --save
Then insert the following require statement towards the top of the affected module to obtain required (generator) behaviour:
require("babel-polyfill");
This should be all you need, just importing the module adds required polyfill behaviour at runtime.
Similar to the post by arcseldon, I was running Babel within a NodeJS environment and getting the same error message 'ReferenceError: regeneratorRuntime is not defined'. While installing babel-polyfill does work, I went with #babel/plugin-transform-runtime instead.
#babel/plugin-transform-runtime
It needs to be installed in two ways ... first as a dev dependency:
npm install --save-dev #babel/plugin-transform-runtime
and second as a production dependency:
npm install --save #babel/runtime
And then there needs to be one simple addition to your .babelrc file:
{
"plugins": ["#babel/plugin-transform-runtime"]
}
These additions give ES6 authoring functionality without the ReferenceError.
While I'm taking a different approach** to using Karma with Babel in my project, I suspect you're having the same problem I was: the Babel polyfill is not being loaded, and so you're not getting the functionality it supports (including the custom regenerator runtime that Babel uses to make generators work).
One approach would be to find a way to include the polyfill, perhaps by feeding it to Karma via the files array:
files: [
'path/to/browser-polyfill.js', // edited: polyfill => browser-polyfill per P.Brian.Mackey's answer
...
An alternate approach may be to use Babel's runtime transformer [edit: on rereading the docs, this will not work unless you then browserify/webpack/etc. to process the require() calls created by the transformer]; per its docs,
The runtime optional transformer does three things:
Automatically requires babel-runtime/regenerator when you use generators/async functions.
Automatically requires babel-runtime/core-js and maps ES6 static methods and built-ins.
Removes the inline babel helpers and uses the module babel-runtime/helpers instead.
I have no experience with this, but I suspect you would do so by including the optional: ['runtime'] option from the Babel docs in your babelPreprocessor config, viz.:
'babelPreprocessor': {
options: {
optional: ['runtime'], // per http://babeljs.io/docs/usage/options/
sourceMap: 'inline'
},
...
(** I'm currently using jspm + jspm-karma + some config to get the Babel polyfill to load in SystemJS; ask if relevant and I'll expound.)
I modified karma.conf.js to add browser-polyfill as mentioned in the Docs Link:
files: [
'node_modules/babel/browser-polyfill.js',
'test-main.js',
{pattern: 'tests/*.js', included: true}
],
After this modification, the following unit test works in Karma:
describe("how Generators work", function() {
it("will allow generator functions", function() {
/*function* numbers(){
yield 1;
yield 2;
yield 3;
};*///Simplified syntax does not work
let numbers = {
[Symbol.iterator]:function*(){
yield 1;
yield 2;
yield 3;
}
}
let sum = 0;
for(let num of numbers){
sum += num;
}
expect(sum).toBe(6);
});
});
If you use React, adding polyfills from create-react-app worked for me.
yarn add --dev react-app-polyfill
Then add the following lines to webpack.config.js
entry: {
app: [
'react-app-polyfill/ie9', // Only if you want to support IE 9
'react-app-polyfill/stable',
'./src/index.jsx',
],
},
See more examples on the react-app-polyfill GitHub page.

Categories

Resources