[英]How to include JS file from npm package to separate page in Nuxt.js
[英]Nuxt npm js package [Missing stack frames]
我正在尝试在我的 Nuxt 应用程序中使用格式独角兽npm package。 但是在我的 Vue 页面中导入它后,我收到以下错误:
Client: Missing stack frames
Server: [Vue warn]: Error in render: "TypeError: this.currencyFormat.formatUnicorn is not a function"
以下方法应根据插件文档起作用:
在不安装模块的情况下使用
package
的另一种方法是在<script>
标签中直接导入package
。
// 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>
不幸的是,这种方法给了我一个错误: Missing stack frames
(并且没有其他有用的信息)。
并且在节点控制台中: [Vue warn]: Error in render: "TypeError: this.currencyFormat.formatUnicorn is not a function"
但奇怪的是,如果我在那里使用Nuxtlink
导航,这个页面实际上打开时没有任何错误。 但是一旦我点击刷新,错误仍然存在。
通过在plugins
目录中创建format-unicorn.js
文件,我仍然遇到相同的错误:
//// 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
],
// ...
我想知道它是否会起作用,所以我只是将 package 存储库中的代码粘贴到那里(它起作用了) :
//// 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'
],
// ...
至此,您可能意识到我对幼稚的方法并不满意,因为我想在将来使用 3rd 方包扩展我的应用程序。 我的问题是我做错了什么? 尝试从 Nuxt 插件扩展原型是否有什么特别之处,或者我只是遗漏了一些东西?
我的 nuxt 错误消息“缺少堆栈帧”因停止而消失了
npm run dev
使用Control-C并重新开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.