Javascript in nuxt plugins folder - how to use in component? - plugins

I have a javascript variable (var testButton) in my Nuxt plugins folder. I then added the file to my nuxt.config.js plugins. In my component, I have a Buefy button, and I'm trying to call the script:
<b-button #click="testButton">Click Me</b-button>
...
<script>
export default {
mounted () {
this.$testButton()
}
}
</script>
I import the script in my script section and have tried computed and mounted lifecycles. Not sure what I'm doing wrong. Thank you

Check the following things, you must be missing one or more:
1. Your plugin should export a method. That method should receive an 'inject' function and use it to register your 'testButton' function.
So, in your ~/plugins/testButton.js
export default (context, inject) => {
inject('testButton', () => {
console.log('testButton works!')
})
}
2. You shuold register your plugin correctly in the nuxt.conf.js file
Do it like so:
plugins: [
{ src: '~/plugins/testButton.js' },
],
3. Call it as '$testButton()' (note that Nuxt will have added a dollar sign to your method's name).
Your '$testButton' method will now be available from anywhere in your nuxt app. You don't have to import it o create any computed property.
<b-button #click="$testButton">Click Me</b-button>
<script>
export default {
}
</script>

Related

How to deploy an generate a static site on Nuxt 3

Hello I'm creating website on Nuxt and i have created a new app on Nuxt 3. But I have an probleme for the deployement, there is no 'normal' build for 'normal server' as Nuxt 2.x.
I'm using 'Lamdba' preset.
https://v3.nuxtjs.org/docs/deployment/presets/lambda
// nuxt.config.ts
import { defineNuxtConfig } from 'nuxt3'
// https://v3.nuxtjs.org/docs/directory-structure/nuxt.config
export default defineNuxtConfig({
// Global page headers: https://go.nuxtjs.dev/config-head
nitro: {
preset: 'lambda'
},
head: {
title: 'Title',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' }
],
link: [
{ rel: 'icon', type: 'image/png', href: '/favicon.png' }
],
script: [
{
type: 'text/javascript',
src: '/mana.js',
}
]
},
})
And on Nuxt 2.x I used this :
// nuxt.config.js
export default {
// Disable server-side rendering: https://go.nuxtjs.dev/ssr-mode
ssr: false,
// Target: https://go.nuxtjs.dev/config-target
target: 'static'
}
What configuration i should to use on Nuxt 3 to have 'normal' export with an index.html file at the root for all server ?
Please use generate script like yarn generate this will create the .output/public and output will depend on ssr: boolean property in nuxt.config.ts.
if ssr is true which is by default, then there will be individual html for each dynamic route and that means dynamic routes are rendered at build time and whenever there is change in data or number of dynamic routes then you will need to run this command again.
if ssr is false then rendering will be done at client side, like SPA app and dynamic routes will have only one file that will do client side rendering and data will be fetched at client side that way site will show latest data.
Check static-hosting
Static deployment is not currently available for Nuxt 3
Besides adding target: 'static' in your nuxt.config.ts
export default defineNuxtConfig({
target: 'static' // default is 'server'
})
You also need to update your build script to be nuxi generate in your package.json (which was nuxi build originally)
{
"scripts": {
"build": "nuxi generate"
}
}
References: https://v3.nuxtjs.org/bridge/overview#static-target
I managed to deploy my nuxt3 project static to gh-pages. I had to overcome two obstacles.
yarn generate did not generate static routes until I explicitly forced it by setting
generate: {routes: ['/','all','my','other','routes']} ....
in nuxt.config.js as target:"static" did not work for me.
gh-pages need an empty .nojekyll file which seems currently not being generated by nuxt generate nor gh-pages. I entered the following into my package.json:
"deploy": "touch .output/.nojekyll && gh-pages --dotfiles -d .output"
This seems ugly but works for me.

SvelteKit console error "window is not defined" when i import library

I would like to import apexChart library which using "window" property, and i get error in console.
[vite] Error when evaluating SSR module /src/routes/prehled.svelte:
ReferenceError: window is not defined
I tried use a apexCharts after mount, but the error did not disappear.
<script>
import ApexCharts from 'apexcharts'
import { onMount } from 'svelte'
const myOptions = {...myOptions}
onMount(() => {
const chart = new ApexCharts(document.querySelector('[data-chart="profit"]'), myOptions)
chart.render()
})
</script>
I tried import a apexCharts when i am sure that browser exist.
import { browser } from '$app/env'
if (browser) {
import ApexCharts from 'apexcharts'
}
But i got error "'import' and 'export' may only appear at the top level"
I tried disable ssr in svelte.config.js
import adapter from '#sveltejs/adapter-static';
const config = {
kit: {
adapter: adapter(),
prerender: {
enabled: false
},
ssr: false,
}
I tried to create a component in which I import apexChart library and I created a condition that uses this component only if a browser exists
{ #if browser }
<ProfitChart />
{ /if }
Nothing helped.
Does anyone know how to help me please?
The easiest way is to simply include apexcharts like a standalone library in your webpage like this:
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
And then simply use it in the onMount:
onMount(() => {
const chart = new ApexCharts(container, options)
chart.render()
})
You can add this line either in your app.html or include it where it's required with a <svelte:head> block.
An alternative way would be to dynamically import during onMount:
onMount(async () => {
const ApexCharts = (await import('apexcharts')).default
const chart = new ApexCharts(container, options)
chart.render()
})
As an extra: use bind:this instead of document.querySelector to get DOM elements, that would be the more 'svelte' way.
I have found the last option with the Vite plugin to work best with less code in the end but will lose intellisense in vscode and see import highlighted as error (temp workaround at end): https://kit.svelte.dev/faq#how-do-i-use-x-with-sveltekit-how-do-i-use-a-client-side-only-library-that-depends-on-document-or-window
Install vite plugin: npm i -D vite-plugin-iso-import
Add plugin to svelte.config.js:
kit: {
vite: {
plugins: [
isoImport(),
],
Add plugin to TypeScript config (if you use TS):
"compilerOptions": {
"plugins": [{ "name": "vite-plugin-iso-import" }],
Use as normal but note the "?client" on the import:
<script context="module">
import { chart } from 'svelte-apexcharts?client';
import { onMount } from 'svelte'
let myOptions = {...myOptions}
onMount(() => {
myOptions = {...updated options/data}
});
</script>
<div use:chart={myOptions} />
Debugging note:
To have import not highlighting as an error temporarily, just:
npm run dev, your project will compile fine, then test in browser to execute at least once.
remove ?client now, save and continue debugging as usual.
For all of you trying to import dynamically into a js or ts file, try the following:
Import your package during on mount in any svelte component.
onMount(async () => {
const Example = await import('#creator/examplePackage');
usePackageInJSOrTS(Example.default);
});
Use the imported package in your js/ts function. You need to pass the default value of the constructor.
export function usePackageInJsOrTs(NeededPackage) {
let neededPacakge = new NeededPackage();
}

share a method of use axios globally standard for nuxtjs?

i want use it for all components and pages and my config present :
~/plugins/axios
import axios from 'axios'
export default axios.create({
baseURL: 'http://127.0.0.1:3001/'
})
but with this way , i must import axios from '~/plugins/axios' in components and pages
i want use something choise for like this :
this.$axios.post('url',data).then(res=>{
// do something in here
}).catch({
// do something in here
})
and no need import more axios
I recommend you to use the official "Axios Module" for Nuxt.js: https://github.com/nuxt-community/axios-module
npm install #nuxtjs/axios
First, you can set your baseURL in the nuxt.config.js or in an env variable (see https://axios.nuxtjs.org/options):
modules: [
'#nuxtjs/axios'
],
axios: {
baseURL: 'http://127.0.0.1:3001/' // or, Environment variable API_URL_BROWSER can be used to override browserBaseURL.
}
Then in <page>.vue, no more import, axios is injected in the app var (see https://axios.nuxtjs.org/usage):
<script>
export default {
asyncData ({ app }) {
app.$axios.$get(`/api/users`).then(
// do something in here
);
//...
}
}
</script>
Finally, you can handle errors globally with a custom plugin (see https://axios.nuxtjs.org/extend)
$axios.onError(error => {
// do something in here
})

aurelia/skeleton-plugin cant run test on custum element

i have created an aurelia plugin using the skelton-plugin https://github.com/aurelia/skeleton-plugin i am now looking at writing unit tests for it.
i am stuggling to get a unit test running for a custom element ive added to the project. i started with the 'testing a custom element' example from http://aurelia.io/hub.html#/doc/article/aurelia/testing/latest/testing-components/3
template:
<template>
<div class="firstName">${firstName}</div>
</template>
vm
import {bindable} from 'aurelia-framework';
export class MyComponent {
#bindable firstName;
}
i added this to the src folder.
my test code is
import {StageComponent} from 'aurelia-testing';
import {bootstrap} from 'aurelia-bootstrapper';
describe('MyComponent', () => {
let component;
beforeEach(() => {
component = StageComponent
.withResources('my-component')
.inView('<my-component first-name.bind="firstName"></my-component>')
.boundTo({ firstName: 'Bob' });
});
it('should render first name', done => {
component.create(bootstrap).then(() => {
const nameElement = document.querySelector('.firstName');
expect(nameElement.innerHTML).toBe('Bob');
done();
}).catch(e => { console.log(e.toString()) });
});
afterEach(() => {
component.dispose();
});
});
i jspm installed aurelia-bootstrapper and aurelia-testing to get it running.
im now getting the error
Error{stack: '(SystemJS) XHR error (404 Not Found) loading http://localhost:9876/base/my-component.js
so it looks like karma cant find my component. i checked the karma.config file and the jspm loadFiles: ['test/setup.js', 'test/unit/**/*.js'], looks correct.
has any one run into a similar issue?
solved the issue.
in karma.config.js file needed to change
serveFiles: ['src//.']
to
serveFiles: ['src//*.js', 'src/**/*.html']

jquery in didInsertElement jshint error

when using jquery inside the component callback, the callback function for click
understands $ directly, and is working with $, but there is a jshint error
components/xxx.js: line 13, col 17, '$' is not defined.
Using this.$ inside the jquery click callback gives an error at run time
import Ember from 'ember';
export default Ember.Component.extend({
didInsertElement() {
this._super(...arguments);
this.$()
.on('click', function() {
$('.class').something(); //ok but jshint error
this.$('.class').something();//jshint ok but error at run time
});
}
});
Thanks
use this at the top of the file
/* globals $ */
Another approach is to set the following configuration to .jshintrc in the root of your app that prevents checking for the whole app which tells jshint that there are two global variables:
{
"globals": {
"$": false,
"jQuery": false
}
}
Note: If you like you can also use the jQuery version as same as Ember jQuery by changing
$('.class').something(); //ok but jshint error
to
Ember.$('.class').something();
which probably drops that error as well.