Babel 6 preset selection to get babel working - javascript

I'm using babel 6 with the react plugin and followed the documentation instructions for setting up the transpile process. I've read to get react working I need to use es2015 and react preset. Initially everything worked fine using this both presets.
But when I've copied an example code from babel's website (Property initializers)
to test new language features I've got errors when code below was transpiled and so it wasn't possible anymore to transpile the code.
// The ES6+ way
class Video extends React.Component {
static defaultProps^= { // this is line 42 and ^ the column where error occurs
autoPlay: false,
maxLoops: 10,
}
static propTypes = {
autoPlay: React.PropTypes.bool.isRequired,
maxLoops: React.PropTypes.number.isRequired,
posterFrameSrc: React.PropTypes.string.isRequired,
videoSrc: React.PropTypes.string.isRequired,
}
state = {
loopsRemaining: this.props.maxLoops,
}
}
Warning: [...]components/sectorList.js: Unexpected token (42:24) Use --force to continue.
After a long while debuggin I've got this issue solved by loading also the stage-0 preset for babel. But it was just luck.
So my question where I can't find an answer for is:
How is the correct way to determine the correct preset collection.
Or is an unexpected token ... warning mostly a notification for an missing preset?
Thanks for any help

If you look at the babel pages for a preset, it lists all the included transformations. In this case, you're using class properties, which is currently at stage 1 and is therefore included in the stage 1 preset.
In ES2015, you'd use the constructor to set the defaults.

Related

How can I resolve Vetur/Vuelidate error "'validate' does not exist in type 'ComponentOptions<Vue [etc.]"?

QUESTION: How can I resolve error 'validations' does not exist in type 'ComponentOptions<Vue [etc.] while using Vetur with Typescript also installed, all in VSCode?
BACKGROUND: I attempted to introduce Vuelidate into a single-file Vue component (by adding a validations property as per the docs). The project containing that component has TypeScript installed so that Vetur's intellisense is improved (but the <script> sections are using JavaScript). After introducing the validations prop, Vetur was displaying an error with the message highlighted in the above question, and intellisense was breaking for methods (such as mount()) that were calling other methods.
CODE: My code basically looks like the sample below, but one would need to install TypeScript to reproduce the Vetur error:
export default {
data() {
return {
name: '',
}
},
validations: {
name: {
required,
minLength: minLength(4)
},
}
}
WHAT HAVE I TRIED: I tried adding #ts-ignore to the validations property, but intellisense is still broken for methods calling other methods.
The solution is:
run npm install --save-dev #types/vuelidate
restart VSCode

'v-slot' directive doesn't support any modifier

I am using vuetify's datatable, i this we have different slots with some props for example below
<template #header.data-table-select="{ on, props }">
<v-simple-checkbox color="purple" v-bind="props" v-on="on"></v-simple-checkbox>
</template>
I am also using vue's eslint plugin to check for any errors/bad code / or any violation , but if i use above code snippet in my file it gives me error
'v-slot' directive doesn't support any modifier
as per this docs it is right https://eslint.vuejs.org/rules/valid-v-slot.html
but it don't have any example to how we handle this case
how can i remove this warning/or make it correct way , without making it exemption
Thanks
I don't see any v-slot in the code you provided so I can show you only my usecase.
With Eslint error:
<template v-slot:item.actions="{ item }">
Without error:
<template v-slot:[`item.actions`]="{ item }">
In eslint-plugin-vue#^7.1.0, you can use allowModifiers option in vue/valid-v-slot rule.
// .eslintrc.js
'vue/valid-v-slot': ['error', {
allowModifiers: true,
}],
vue/valid-v-slot #options
For me the following Entry in settings.json fixed the problem:
"vetur.validation.template": false
EDIT: As notified by the comments and Hexodus' (correct) answer, you can work around the linting warning by using dynamic slot names that return a string(template). 'Not enabling' is no longer recommended, as this is now a standard rule. Thus, I recommend using Hexodus' method over disabling the valid v-slot rule altogether.
Original Post:
You can't really fix this linting warning.
Vue syntax for modifiers use the dot to alter the way a
directive functions (e.g. v-model.number)
The way Vuetify dynamically names their slots uses a dot in order to
select a specific part of the component (#header.data-table-select).
ESLint can't distinguish whether you're trying to set a modifier on a slot (which is impossible), or if you have a slot name that contains a dot.
The easiest thing you can do is disable the rule. Since the 'valid-v-slot' rule isn't enabled by default by any of the base configurations of eslint-plugin-vue, you should be able to find it under "rules" in your eslint config.
I tried Hexodus' answer, but the template wasn't rendering at all in my case.
I got it to work perfectly with this, without any eslint rule modification:
<template #[`item.actions`]="{ item }">
Try this:
<template v-slot:item.createdDate="{ item }">
if you use the format vetur, add this option in vscode settings:
"vetur.validation.template": false
Maybe this isn't the answer, and you also may not buy into my solution but this is what I did.
ANS: I downgraded Vetur to version 0.23! It worked! (Waiting a new version release that addresses the issue.
Open the Extensions side panel on VSCode, right click Vetur and select install other versions.
Alternatively, if your code is working fine, a line before the vue-eslint-plugin error you can try <!-- eslint-disable-next-line vue/no-v-html --> to disable eslint for next line or <!-- eslint-disable --> to disable every disable linting below it.
Worked for some people but not for me and may not work for you. Either way, prefer Vetur downgrade
I am using laravel framework, and vuetify. Previous codes suddenly reported eslint errors with red lines - vue/valid-v-slot directive, adding multiple root nodes to the template, and so on without recommending any quick fix, yet they are all working fine. Answers I got from search never yielded any result till I downgraded, any other solution will be so welcomed!
It worked for me:
in .vue
<template v-slot:[getitemcontrols()]="props">
in .js
methods: {
getitemcontrols() {
return `item.controls`;
},
For me this config added to package.json worked
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/base"
],
"rules": {},
"parserOptions": {
"parser": "babel-eslint"
}
}

Arrow functions in class throw error with webpack-encore

Configuration
I'm using webpack-encore with my symfony project to compile my reactjs project. Up till now, I've used the basic webpack.config.js setup that should work out of the box with react when enabling it:
// webpack.config.js
// ...
Encore
// ...
.enableReactPreset()
;
What I've tried:
I went ahead and added babel configurations (that I don't think are needed) in hope that it would solve the problem, but it didn't:
.configureBabel(function(babelConfig) {
// add additional presets
babelConfig.presets.push('es2017');
})
Code example:
Here is an example of what should work, but it doesn't compile and throws the following error:
Syntax Error: Unexpected token
import React, {Component} from 'react';
//This works
const someExteriorHandler = () => {};
export default class Example extends Component {
//error bad syntax, points specifically at the equal sign.
someHandler = () => {
}
render(){return(<h1>This is a test</h1>)}
}
Question
How do I get the babel compiler in webpack-encore to compile Arrow functions in javascript classes?
This problem was solved.
Having assignment of arrow functions in a class is not part of ES6. It
is part of a draft proposal for an upcoming ES version. Babel is able
to transpile it, but you will need to enable this transformation in
the babelrc file. The default babel config shipped in Encore when you
don't configure babel does not enable the transpilation of
experimental features.
Install experimental features
yarn add --dev babel-plugin-transform-class-properties babel-plugin-transform-object-rest-spread
Configure webpack.config.js
.configureBabel(function(babelConfig) {
//This is needed.
babelConfig.plugins = ["transform-object-rest-spread","transform-class-properties"]
})
It should compile now, with all JSX features as well.

How do you add external javascript libraries using ES6 style imports?

I'm having trouble understanding exactly how to use older javascript libraries within newer ES6 projects. I'm looking at a React project that's been compiled with webpack, written with ES6 and transpiled with Babel. Each component follows the import * from "" notation.
There's an external javascript library I want to use within the project: https://github.com/pchen66/panolens.js. The compiled library doesn't follow ES6 export format, and only has one global object PANOLENS.
What should I do if I want to include this into my project?
This is not the best.
Include it in your html :
<script src="js/three.min.js"></script>
<script src="js/panolens.min.js"></script>
<script src="bundle.js"></script>
<script>window.PANOLENS = PANOLENS</script>
Where bundle.js is your own builded javascript code.
Then, you will be able to use PANOLENS object anywhere.
Example component :
import react, {Component} from 'react'
export default class Test extends Component {
componentDidMount(){
var panorama, viewer;
panorama = new window.PANOLENS.ImagePanorama('asset/equirectangular.jpg' );
viewer = new window.PANOLENS.Viewer(
container: document.getelementbyid('viewer-container'), // A DOM Element container
controlBar: true, // Vsibility of bottom control bar
controlButtons: [], // Buttons array in the control bar. Default to ['fullscreen', 'setting', 'video']
autoHideControlBar: false, // Auto hide control bar
autoHideInfospot: true, // Auto hide infospots
horizontalView: false, // Allow only horizontal camera control
cameraFov: 60, // Camera field of view in degree
reverseDragging: false, // Reverse orbit control direction
enableReticle: false, // Enable reticle for mouseless interaction
dwellTime: 1500, // Dwell time for reticle selection in millisecond
autoReticleSelect: true, // Auto select a clickable target after dwellTime
passiveRendering: false, // Render only when control triggered by user input
);
viewer.add( panorama );
}
render(){
return(
<div id='viewer-container'></div>
)
}
}
It doesn't really matter if the module itself follows ES6 syntax. It will either follow commonJS or AMD, both of which webpack can handle, and at worst, you can just require/import the whole file into your bundle: https://www.npmjs.com/package/panolens.js.
EDIT: This npm module/repo does use module.exports if you look at the dist.
EDIT:
Yeah, it looks like someone has forked the library and made an NPM package out of it. Have you taken a look at https://github.com/sbolel/pano. There is an ES6 example.
Install the package:
npm install --save pano
Then import:
import Pano from 'pano'
import { Page } from 'pano'
// Pano.Page === Page
const panoPage = new Page('pano')
panoPage.init()
ORIGINAL:
You could load the script asynchronously using the method below, or if you are using a bundler, it would have a way to import external scripts. For example, Webpack has Externals for this.
After doing this, you can access the the global object PANOLENS, as per the documentation. You'll want to make sure the PANOLENS object is available before using it in your application.
Add the following to your static HTML:
<script src="https://github.com/pchen66/panolens.js" async></script>
If you are planning to only use the script in a certain React component (presuming you use React), you could use a library such as react-async-script-loader. This will allow you to lazy load a script on a particular component. It has a bunch of properties that can be used to determine when the script is ready to be used.
Again, after the script has successfully loaded, you may use the library by accessing it through the global PANOLENS variable.
So you would want some kind of module shimmer. If you are using webpack you should try this:
https://github.com/webpack/docs/wiki/shimming-modules
There are similar shims for browserify too:
https://github.com/thlorenz/browserify-shim
You could also fork the repo and shim it manually something like this, the implementations may vary though.
/**
* Panolens.js
* #author pchen66
* #namespace PANOLENS
*/
var PANOLENS = { REVISION: '3' };
module.exports = PANOLENS;

Cannot use decorators in Node/BabelJS application

I have a Node application, which specifies babel with transform options and register in a main file, like so:
require('babel').transform('code', { stage: 1 });
require('babel/register')({ ignore: false });
require('../src/index');
Which does an excellent job of allowing me to use ES6 in ../src/index, and all subsequent files, but does not seem to allow me to use Decorators, as it should by declaring level 1 transform. I get instead a syntax error. Why is this not enabling decorator support? The actual decorator I'm trying to use is:
#test1
test Class() {
constructor() {
this.test = 'test';
}
}
function test1(obj) {
obj.test1 = 'test1';
}
That's not how you specify options, that first like does nothing. It compiles the JavaScript code code and does nothing with the result of the compilation.
require('babel/register')({
ignore: false,
stage: 1
});
require('../src/index');
Also generally ignore: false is a bad idea because some files should ignored.
Update
If you are using Babel 6, you'll want to download babel-plugin-transform-decorators-legacy rather than enabling stage: 1.
It's worth noting that the newest version of babel (v6) (over 1 month old) does not support decorators and the babeljs team has identified that they do not consider decorators to be a priority to fix -
https://twitter.com/sebmck/status/661501967412301824
As #jdanyow has mentioned in other answers you can track the issue here but beware if you choose to use Babeljs v6 that there is functionality from the previous release which is broken in the released v6 at the moment.
As #loganfsmyth points out in comments there is a plugin available babel-plugin-transform-decorators-legacy although it does mention that there are differences in the implementation, however I am not aware of them.

Categories