I've been attempting to incorporate the format-unicorn npm package into my Nuxt application. However, upon importing it into my Vue page, I encountered the following errors:
Client: Missing stack frames
Server: [Vue warn]: Error in render: "TypeError: this.currencyFormat.formatUnicorn is not a function"
Initial Strategy
According to the plugins documentation, the following approach should work:
Another way to use
package
without installing the module is by directly importingpackage
in the<script>
tag.
// Product.vue
<template>
<div class="product">
<p>Price: {{ localizedPrice }}</p>
</div>
</template>
<script>
require('format-unicorn')
export default {
data() {
return {
currencyFormat: '{c}{p}',
currency: '$',
price: 12.99
}
},
computed: {
localizedPrice: {
get() {
return this.currencyFormat.formatUnicorn({c: this.currency, p:this.price})
}
}
}
}
</script>
However, this approach resulted in an error:
Missing stack frames
(with no further useful information).
Additionally, in the node console:
[Vue warn]: Error in render: "TypeError: this.currencyFormat.formatUnicorn is not a function"
Interestingly, the page loads without errors if I navigate there using Nuxtlink
. But upon refreshing, the error reappears.
Using Plugins Approach
Even after creating the format-unicorn.js
file within the plugins
directory, I faced the same error:
//// plugins/format-unicorn.js
require('format-unicorn');
//// nuxt.config.js
// ...
plugins: [
'~/plugins/format-unicorn.js'
// applying mode: 'client' or 'server' doesn't help as well
],
// ...
Simple Plugins Solution
To test its functionality, I decided to paste code from the package repository directly into the plugin (and surprisingly, it worked):
//// plugins/format-unicorn.js
String.prototype.formatUnicorn = function () {
let str = this.toString()
if (arguments.length) {
const type = typeof arguments[0]
const args = type === 'string' || type === 'number' ? Array.prototype.slice.call(arguments) : arguments[0]
for (const arg in args) str = str.replace(new RegExp(`\\{${arg}\\}`, 'gi'), args[arg])
}
return str
}
//// nuxt.config.js
// ...
plugins: [
'~/plugins/format-unicorn.js'
],
// ...
Summary
It's clear that the naive approach is not sufficient for my needs, especially considering future integration of third-party packages into my app. My main question remains: What am I missing or doing wrong in trying to extend a prototype from a Nuxt plugin?