3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

DockerでNuxt.jsとExpressの環境構築を行うよ

Last updated at Posted at 2021-08-29

はじめに

今回はNuxt.jsとExpressの環境をDockerで作成した記事です。

環境

今回は、Nuxt.jsにTypeScriptを導入し、Composition-APIの書き方を採用します。
また、バックエンドにはORMとしてPrismaを採用します。

Prismaの導入に関してものすごく手間取りました。
Qiitaで質問にお答えいただいた2名の方に感謝申し上げます。

Dockerfile

  • MySQL (5.7)
  • Node.js (【Express】14.15.3-alpine)
  • Node.js (【Nuxt.js】14.15.3-alpine)

Frontend

採用する技術は以下の通りです。

  • Nuxt.js
  • TypeScript
  • Vue3.0(Composition-API)

Composition-APIに関して全く知識がない方は以下の記事をご覧ください。

Backend

採用する技術は以下の通りです。

  • Express
  • TypeScript
  • Prisma

Github

コードはこちらです。

READMEに環境構築の方法を書いてますが、Qiitaにまとめてみます。

それでは環境を作りましょう〜!

①クローンしてディレクトリを移動する

ターミナル
$ git clone git@github.com:ssk9597/Docker-Nuxt-TypeScript-Express-Prisma.git

$ cd Docker-Nuxt-TypeScript-Express-Prisma

②作成するテーブルを記載する

api/prisma/schema.prismaに現在デフォルトで以下が記載されています。

api/prisma/schema.prisma
model User {
  id    Int    @id @default(autoincrement())
  name  String
  email String @unique
}

上記の意味は、以下の通りです
Userテーブルを作成
②カラムは3つ
idというカラムは数値型で、オートインクリメントになっている
nameというカラムは文字列型になっている
emailというカラムは文字列型でユニークになっている

リレーションなどもできるので詳しくは公式サイトを確認しましょう。

make nuxtを実行して、Nuxt.jsの作成とDockerの起動を行う

Nuxt.jsの作成では、必ずTypeScriptを選択してください。

ターミナル
$ make nuxt

> npx create-nuxt-app frontend

create-nuxt-app v3.6.0
✨  Generating Nuxt.js project in frontend
? Project name: nuxt-typescript
? Programming language: TypeScript
? Package manager: Npm
? UI framework: None
? Nuxt.js modules: (Press <space> to select, <a> to toggle all, <i> to invert selection)
? Linting tools: (Press <space> to select, <a> to toggle all, <i> to invert selection)
? Testing framework: None
? Rendering mode: Universal (SSR / SSG)
? Deployment target: Server (Node.js hosting)
? Development tools: (Press <space> to select, <a> to toggle all, <i> to invert selection)
? What is your GitHub username? XXXXX
? Version control system: Git

nuxt.config.js.envを修正する

nuxt.config.js

frontend/nuxt.config.js
require('dotenv').config();
const { API_URL, API_URL_BROWSER } = process.env;

export default {
  head: {
    title: 'frontend',
    htmlAttrs: {
      lang: 'ja',
    },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' },
    ],
    link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
  },

  css: [],

  plugins: [],

  components: true,

  buildModules: ['@nuxt/typescript-build'],

  watchers: {
    webpack: {
      poll: true,
    },
  },

  modules: ['@nuxtjs/axios', '@nuxtjs/proxy', '@nuxtjs/dotenv'],

  env: {
    API_URL,
    API_URL_BROWSER,
  },

  proxy: {
    '/api': process.env.API_URL,
  },

  axios: {
    baseURL: process.env.API_URL,
    browserBaseURL: process.env.API_URL_BROWSER,
  },

  build: {},
};

.env

frontend/.env
API_URL = "http://app:18080"
API_URL_BROWSER = "http://localhost:18080"

make migratePrismaのマイグレーションを行う

ターミナル
$ make migrate

こちらの実行でマイグレーションとGUIでデータベース上のデータを閲覧・編集できるPrisma studioが使用できるようになります。

スクリーンショット 2021-08-29 13.51.07.png

これがめちゃんこ便利です!

make typescriptでTypeScriptを導入する

まずはターミナルで必要なパッケージをインストールしましょう。

ターミナル
$ make typescript

次に必要なファイルに追記を行います。

shims-vue.d.ts

frontend/shims-vue.d.ts
declare module '*.vue' {
  import Vue from 'vue';
  export default Vue;
}

tsconfig.json

frontend/tsconfig.json
{
  "compilerOptions": {
    "target": "ES2018",
    "module": "ESNext",
    "moduleResolution": "Node",
    "lib": ["ESNext", "ESNext.AsyncIterable", "DOM"],
    "esModuleInterop": true,
    "allowJs": true,
    "sourceMap": true,
    "strict": true,
    "noEmit": true,
    "experimentalDecorators": true,
    "baseUrl": ".",
    "paths": {
      "~/*": ["./*"],
      "@/*": ["./*"]
    },
    "types": ["@nuxt/types", "@types/node"]
  },
  "files": ["shims-vue.d.ts"],
  "include": [
    "components/**/*.ts",
    "components/**/*.vue",
    "layouts/**/*.ts",
    "layouts/**/*.vue",
    "pages/**/*.ts",
    "pages/**/*.vue"
  ],
  "exclude": ["node_modules", ".nuxt", "dist"]
}

これでTypeScriptが使えます。

make composition-apiでComposition-APIを導入する

まずはターミナルで必要なパッケージをインストールしましょう。

ターミナル
$ make composition-api

次に必要なファイルに追記を行います。

nuxt.config.js

frontend/nuxt.config.js
require('dotenv').config();
const { API_URL, API_URL_BROWSER } = process.env;

export default {
  head: {
    title: 'frontend',
    htmlAttrs: {
      lang: 'ja',
    },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' },
    ],
    link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
  },

  css: [],

  plugins: [],

  components: true,

  buildModules: ['@nuxt/typescript-build', '@nuxtjs/composition-api/module'],

  generate: {
    interval: 2000,
  },

  watchers: {
    webpack: {
      poll: true,
    },
  },

  modules: ['@nuxtjs/axios', '@nuxtjs/proxy', '@nuxtjs/dotenv'],

  env: {
    API_URL,
    API_URL_BROWSER,
  },

  proxy: {
    '/api': process.env.API_URL,
  },

  axios: {
    baseURL: process.env.API_URL,
    browserBaseURL: process.env.API_URL_BROWSER,
  },

  build: {},
};

pages/index.vueを修正してバックエンドとの通信を図る

では、バックエンドとの通信ができているか確認しましょう。

frontend/pages/index.vue
<template>
  <div>
    <h1>
      {{ data }}
    </h1>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, useAsync, useContext } from '@nuxtjs/composition-api';
import axios from '@nuxtjs/axios';

export default defineComponent({
  setup() {
    const data = ref({});
    const { $axios } = useContext();
    useAsync(async () => {
      const result = await $axios.$get('/api');
      data.value = result;
    });
    return { data };
  },
});
</script>

このように表示されていれば問題なく通信ができています!

スクリーンショット 2021-08-29 14.04.24.png

また、Prismaのクエリに関してはこちらを確認してください。
基本のCRUDに関してはまとめてあるのでこれを使いこなせれば問題ないと思います。

ここからは任意です

UI開発用ツールのStorybookを使いたい方は以下も行うようにしましょう。

ちなみに、Storybookが何か分からない方は以下の記事を確認されてください。

コマンド1つでStorybookが実行できます。

ターミナル
$ make storybook

// 再起動したいとき
$ make re-storybook

終わりに

ここまでできればNuxt.jsとExpressの環境構築はばっちりです👍
あとは作りたいものを作っていきましょう!

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?