Showing posts with label Nuxtjs. Show all posts
Showing posts with label Nuxtjs. Show all posts

Friday, 31 March 2023

Setup nuxtjs with typescript

>> Url source on Github

1. Three packages Nuxt Typescript support

- @nuxt/types: contains Nuxt Typescript type definition

- @nuxt/typescript-build: for use Typescript in pages, layouts, comopents, plugins, middlewares.

- @nuxt/typescript-runtime: to provide Typescript runtime support for nuxt.config.js file, local modules and serverMiddlewares (^Nuxt 2.15 no longer needed)

2. Install Typescript for Nuxtjs

- with "nuxt": "^2.15.8", using: "@nuxt/types": "^2.15.8", "@nuxt/typescript-build": "^2.1.0",

yarn add --dev @nuxt/typescript-build@2.1.0
yarn add --dev @nuxt/types@2.15.8
 

3. Configuration

- edit nuxt.config.js to add module that are used during the build process, Nuxt.js will install the necessary dependencies (including TypeScript itself) and configure the build process to include TypeScript files

import type { NuxtConfig } from '@nuxt/types'

export default {
.....
buildModules: ['@nuxt/typescript-build']
.....
}

- add tsconfig.json to configure the TypeScript compiler, which is used to transpile TypeScript code into JavaScript

{
"compilerOptions": {
"target": "ES2018",
"module": "ESNext",
"moduleResolution": "Node",
"lib": [
"ESNext",
"ESNext.AsyncIterable",
"DOM"
],
"esModuleInterop": true,
"allowJs": true,
"sourceMap": true,
"strict": true,
"noEmit": true,
"baseUrl": ".",
"paths": {
"~/*": [
"./*"
],
"@/*": [
"./*"
]
},
"types": [
"@nuxt/types",
"@nuxt/typescript-build",
"@types/node"
]
},
"exclude": [
"node_modules"
]
}

-  add vue-shim.d.ts to provide TypeScript type information for Vue.js components

declare module "*.vue" {
import Vue from 'vue'
export default Vue
}

Thank you

Reference:

- https://typescript.nuxtjs.org/guide/setup/



Wednesday, 29 March 2023

Two ways to call Api in Nuxtjs

* Notice: this post apply for nuxtjs with typescipt

1. Method 1: using axios directly

- Install axios

yarn add @nuxtjs/axios

- Create file ./plugins/axios.ts

import axios from 'axios'

const api = axios.create({
baseURL: 'http://api.example.com',
headers: {
'Content-Type': 'application/json'
}
})

export default api

- Using to call Api

<template>
<div class="container">
<h1>Call Api</h1>
</div>
</template>

<script lang="ts">
import Vue from 'vue'
import api from '@/plugins/axios'

export default Vue.extend({
name: 'IndexPage',
created() {
this.asyncData();
},

methods: {
async asyncData() {
const response = await api.get('/products')
console.log(response)
}
}
})
</script>

2. Method 2: create plugin inject to context

- Install axios

yarn add @nuxtjs/axios

- Create file ./plugins/axios.ts

import { Plugin } from '@nuxt/types'
import axios from 'axios'

const axiosPlugin: Plugin = (context, inject) => {
// Set baseURL for Axios
axios.defaults.baseURL = process.env.API_URL || 'http://api.example.com'

// Inject axios instance to the context as $axios
inject('axios', axios)
}

export default axiosPlugin

- Edit file nuxt.config.js

plugins:
'~/plugins/axios.ts'
],

- Using to call Api

<template>
<div class="container">
<h1>Call API</h1>
</div>
</template>

<script lang="ts">
import Vue from 'vue'

export default Vue.extend({
name: 'IndexPage',
created() {
this.fetchData();
},

methods: {
async fetchData() {
try {
const response = await this.$axios.get('/products')
console.log(response.data)
} catch (error) {
console.error(error)
}
}
}
})
</script>

3. Change config when call API

- example change baseUrl

const response = await this.$axios.get('/members/products',{
  baseURL: 'https://localhost/api' 
})

Thank you


Thursday, 23 March 2023

Deployment Node.js Nuxt App with Nginx, SSL with Lets Encrypt

1. Access your Vps

ssh user@ip

2.Install nodejs, npm, yarn

sudo apt update

# select node version
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -

# install nodejs
sudo apt install nodejs

# check nodejs
node --version
npm --version

# install yarn
npm install -g yarn

3. Clone, build and run Nuxt app

git clone [your-url-project-on-github]
cd your-project
yarn install
yarn build
yarn start

4. Run Nuxt app using pm2 (process manager for Node.js)

- create file ecosystem.config.js in root Nuxt app

# create file
touch ecosystem.config.js
# with content
module.exports = {
apps: [
{
name: 'NuxtAppName',
exec_mode: 'cluster',
instances: 'max', // Or a number of instances
script: './node_modules/nuxt/bin/nuxt.js',
args: 'start'
}
]
}

- Build and run Nuxt app using pm2

# intall pm2
npm install pm2 -g

# run nuxt app
pm2 start
 
# check pm2
pm2 ls
pm2 logs (Show log stream)
pm2 flush (Clear logs)  
 
# stop nuxt app
pm2 stop [app_name_or_id]
 
# delete all process managed
pm2 delete all
 

- To make sure app starts when reboot

pm2 startup ubuntu
# test reboot server
reboot

5. Setup ufw firewall

# setup ufw
sudo ufw enable
sudo ufw allow http
sudo ufw allow https
sudo ufw allow 'Nginx Full'
sudo ufw delete allow 'Nginx HTTP'
# check ufw status
sudo ufw status

# output:
sudo ufw allow ssh (Port 22)
sudo ufw allow http (Port 80)
sudo ufw allow https (Port 443)

6. Install NGINX and configure

- Install nginx

# install nginx
sudo apt update
sudo apt install nginx

# check nginx working
sudo systemctl status nginx
sudo systemctl enable nginx
sudo systemctl stop nginx
sudo systemctl restart nginx

- Errors (if happen): unknow host Ubuntu-20.04

# open /ect/host
sudo nano /etc/hosts

# update line become
127.0.0.1 Ubuntu-20.04 localhost

- Set Up Nginx Server Blocks (Virtual Hosts) for example.com

sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/example.com
sudo nano /etc/nginx/sites-available/example.com

- Config for /etc/nginx/sites-available/example.com

server {
listen 80 default_server;
listen [::]:80
default_server;
 
# Add the following to the location part of the server block
server_name example.com www.example.com;

location / {
proxy_pass http://localhost:3000; #whatever port your app runs on
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}

* Now that we have our server block file, we need to enable it. We can do this by creating symbolic link from this file to the sites-enabled directory, which Nginx reads from during startup.

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/  
# to delete symbolic link
cd /etc/nginx/sites-enabled/
rm site_want_delete

- Check nginx config status

# Check NGINX config
sudo nginx -t

# Restart NGINX
sudo service nginx restart

7. Add record for domain

Host Type Value TTL
  @
 A
 your-ip-vps  3600 
 www 
 CNAME 
 example.com 
 3600

8. Add SSL with LetsEncrypt

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com
 
# check certbot auto renew  
sudo systemctl status certbot.timer  
 
# or manually renew ssl (90 day will expired)
sudo certbot renew --dry-run 

Thank you.


Friday, 17 March 2023

How codes run in a Nuxt.js with plugins

1. The nuxt.config.js file is loaded and parsed, and the configuration options are applied.

2. The Nuxt.js server is started, and the middleware functions are loaded.

3. The server listens for incoming HTTP requests, and when a request is received, it passes it through the middleware stack.

4. The middleware stack runs in the order in which the middleware functions are defined in the middleware array in nuxt.config.js.

5. Each middleware function can perform some operations on the request and response objects, or it can pass the request to the next middleware function in the stack by calling next().

6. When the middleware stack completes, the appropriate page component is loaded based on the requested route.

7. The page component can fetch data from an API or perform any other necessary operations, and then it is rendered on the server.

8. Before the page component is rendered, any plugins that have been defined in the plugins array in nuxt.config.js are loaded and initialized.

9. The plugin code can perform any necessary operations, such as registering global components, adding instance properties to Vue.js, inject plugin to vue context, or installing third-party libraries.

10. Once the plugins have been loaded and initialized, the page component is rendered and sent to the client.

11.
Once the client receives the response, it rehydrates the page, which means that it turns the static HTML into a dynamic, interactive page by attaching event listeners and updating the DOM as necessary.

12. The client can then interact with the page, and any subsequent requests are handled by the client-side router and Vue.js components, rather than being passed through the middleware stack on the server.


 

Publish npm package

  Để publish   pav-kit  lên NPM, bạn hãy làm theo các bước dưới đây. Tôi đã tạo thêm file  index.js  để đảm bảo gói tin hợp lệ. Bước 1: Tạo ...