25.06.2018 Views

Full-Stack Vue.js 2 and Laravel 5

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Polyfills<br />

The ES2015 proposal includes new syntax, but also new APIs, such as Promise,<br />

<strong>and</strong> additions to existing APIs, such as Array <strong>and</strong> Object.<br />

The Webpack Babel plugin can transpile ES2015 syntax, but new API methods<br />

require polyfilling. A polyfill is a script that is run in the browser to cover an<br />

API or API method that may be missing.<br />

For example, Object.assign is a new API method that is not supported in Internet<br />

Explorer 11. If we want to use it in our frontend app, we have to check at the top<br />

of our script whether the API method exists, <strong>and</strong> if not, we define it manually<br />

with a polyfill: if (typeof Object.assign != 'function') { // Polyfill to define<br />

Object.assign }<br />

Speaking of which, Object.assign is a h<strong>and</strong>y way of merging objects <strong>and</strong> would be<br />

useful in our frontend app. Let's use it in our code, then add a polyfill to ensure<br />

the code will run in older browsers.<br />

Look at the data object in our entry file, resources/assets/<strong>js</strong>/app.<strong>js</strong>. We are<br />

manually assigning each property of the sample object to the data object, giving it<br />

the same property name. To save having to repeat ourselves, we can instead use<br />

Object.assign <strong>and</strong> simply merge the two objects. In practice, this doesn't do<br />

anything different, it's just more succinct code.<br />

resources/assets/<strong>js</strong>/app.<strong>js</strong>: data: Object.assign(sample, { headerImageStyle: {<br />

'background-image': 'url(/images/header.jpg)' }, contracted: true, modalOpen:<br />

false }),<br />

To polyfill Object.assign we must install a new core-<strong>js</strong> dependency, which is a<br />

library of polyfills for most new JavaScript APIs. We'll use some other core-<strong>js</strong><br />

polyfills later in the project: $ npm i --save-dev core-<strong>js</strong><br />

At the top of app.<strong>js</strong>, add this line to include the Object.assign polyfill: import<br />

"core-<strong>js</strong>/fn/object/assign";

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!