nuxtとexpressでSSRする





環境


  • nodejs 12.16.1


package.json


package.json
{
  "scripts": {
    "dev": "nuxt dev"
  },
  "devDependencies": {
    "express": "^4.17.1",
    "nuxt": "^2.12.2"
  }
}


pages/index.vue


pages/index.vue
<template>
  <div class="container">
    <h1>{{ str }}</h1>
  </div>
</template>

<script>
const func = () => {
  return new Promise(resolve => {
    setInterval(() => {
      resolve('index');
    }, 500);
  });
};

export default {
  // 本来ここでAPIたたく
  async asyncData({ params }) {
    const str = await func();
    return {
      str
    };
  },
  head() {
    return {
      title: 'SSR home',
      meta: [
        { hid: 'description', name: 'description', content: 'description' }
      ]
    };
  }
};
</script>

app.js


app.js
const express = require('express');
const { Nuxt, Builder } = require('nuxt');
const app = express();

const start = async () => {
  const nuxt = new Nuxt({
    buildDir: '.nuxt',
    build: {
      publicPath: '/assets/'
    }
  });

  const builder = new Builder(nuxt);
  await builder.build();

  // nuxt.ready();

  app.use(nuxt.render);
  app.listen(3000);
  console.log('express');
};

start();


コマンド


bash
$ node app


ホームへ