Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8691

【Node.js】tailwindcssでログインページを作成する方法

$
0
0

はじめに

今回は前回の記事の続きです。
今回はNode.js+EJS+tailwindcssでログインページを作成します。

今回のファイル構成

nodejs-tailwindcss/
  │
  ├ controllers/
  │ └ pageIndex.js
  │
  ├ puclic/
  │ └ styles/
  │     └ style.css
  │     └ tailwind.css
  │
  ├ views/
  │ └ index.ejs
  │
  ├ index.js
  ├ package.json
  ├ postcss.config.js
  ├ tailwind.config.js

それでは実際にコードを書いていきましょう!

最初に、index.jsを作成しよう

index.js
//モジュールを読み込むconstexpress=require('express');constejs=require('ejs')//コントローラーを読み込むconstpageIndexController=require('./controllers/pageIndex');//読み込んだexpressモジュールを実体化してインスタンスにするconstapp=express();//テンプレートエンジンとしてejsを用いるapp.set('view engine','ejs');//publicフォルダを使えるようにするapp.use('/public',express.static(__dirname+'/public'));//ルーティング処理app.get('/',pageIndexController);//サーバーを立ち上げるapp.listen(3000,()=>{console.log('http://localhost:3000');});

以下の記載で、publicフォルダ内のCSSが読み込めるので、
こちらの記述がない場合はCSSを使えません!
なのでこちらの記述は忘れないでくださいね。
こちらの記事を参考にしてください!

//publicフォルダを使えるようにするapp.use('/public',express.static(__dirname+'/public'));

次にルーティング処理を記述する、pageIndex.jsを作成しましょう。

次に、pageIndex.jsを作成しよう

pageIndex.js
module.exports=(req,res)=>{res.render('index');};

これだけしか記載しないので、わざわざファイルを分けるメリットは少ないですが、
運用していく中でファイルを分けておいた方が保守がしやすいので分けるようにしましょう。

最後にindex.ejsを作成しよう

index.ejs
<!DOCTYPE html><htmllang="ja"><head><metacharset="UTF-8"/><metaname="viewport"content="width=device-width, initial-scale=1.0"/><title>nodejs-tailwindcss</title><linkrel="stylesheet"href="../public/styles/style.css"/></head><body><divclass="flex flex-col h-screen"><divclass="bg-gray-100 flex-auto"><divclass="flex justify-center mt-20"><divclass="w-9/12 border bg-white"><divclass="my-16 text-center"><h2class="text-4xl font-bold">ログイン</h2><formaction="/form/login"method="POST"class="mt-12"><divclass="mb-3"><inputtype="email"placeholder="you@gmail.com"name="email"class="text-xl w-7/12 p-3 border rounded"/></div><divclass="mb-5"><inputtype="password"placeholder="パスワード"name="password"class="text-xl w-7/12 p-3 border rounded"/></div><divclass="mb-5"><labelclass="inline-flex items-center"><inputtype="checkbox"class="form-checkbox"/><spanclass="ml-2 text-sm">ログインデータを保存する</span></label></div><buttontype="submit"class="mb-3 text-xl w-4/12 bg-blue-800 text-white py-2 rounded hover:opacity-75">ログイン
                                </button></form></div></div></div></div></div></body></html>

クラスの記載が多いのでコード自体はめちゃくちゃ長いですが、
書いている内容はシンプルです!

正直たくさんコードを書かなければ覚えられないので、
公式サイトで大まかに理解した後は、
チートシートを使うのがおすすめです。

私もまだまだ覚えられていないので、
チートシートを手元においてコーディングしています!!


Viewing all articles
Browse latest Browse all 8691

Trending Articles