在 Nuxt 2.0 使用 AdonisJs 4.0 框架

前言

Nuxt 將 Adonis 進行整合,成為 Adonuxt

安裝

1
npx create-nuxt-app adonuxt
  • 選擇 Adonis 作為後端框架。

安裝 SQLite

1
npm install --save sqlite3

更新套件

執行遷移時會出現警告:

1
Knex:warning - .returning() is not supported by sqlite3 and will not have any effect.
  • lucid 套件需要更新。

更新套件到最新版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"dependencies": {
"@adonisjs/ace": "^5.0.8",
"@adonisjs/auth": "^3.0.7",
"@adonisjs/bodyparser": "^2.0.5",
"@adonisjs/cors": "^1.0.7",
"@adonisjs/fold": "^4.0.9",
"@adonisjs/framework": "^5.0.9",
"@adonisjs/ignitor": "^2.0.8",
"@adonisjs/lucid": "^6.1.3",
"@adonisjs/session": "^1.0.27",
"@adonisjs/shield": "^1.0.8"
}
}

新增路由

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
'use strict';

/*
|--------------------------------------------------------------------------
| Routes
|--------------------------------------------------------------------------
|
| Http routes are entry points to your web application. You can create
| routes for different URL's and bind Controller actions to them.
|
| A complete guide on routing is available here.
| http://adonisjs.com/guides/routing
|
*/

const Route = use('Route');

Route.get('api/users', 'UserController.index');

Route.any('*', 'NuxtController.render'); // 前端渲染
  • 後端路由必須建立在前端渲染之前。

後端開發

前後端同時編譯相當耗時,因此新增一列命令,在開發後端時不對前端程式碼編譯。

1
"dev:server": "cross-env NODE_NO_CLIENT=true nodemon --watch app --watch bootstrap --watch config --watch .env -x node server.js",

修改 app\Controllers\Http\NuxtController.js 檔:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
'use strict';

const Env = use('Env');
const Config = use('Config');
const { Nuxt, Builder } = require('nuxt');

class NuxtController {
constructor() {
// 停止運行
if (process.env.NODE_NO_CLIENT) {
return;
}
const config = Config.get('nuxt');
config.dev = Env.get('NODE_ENV') === 'development';
this.nuxt = new Nuxt(config);
// Start build process (only in development)
if (config.dev) {
new Builder(this.nuxt).build();
}
}

async render({ request: { request: req }, response: { response: res } }) {
await new Promise((resolve, reject) => {
this.nuxt.render(req, res, (promise) => {
promise.then(resolve).catch(reject);
});
});
}
}

module.exports = new NuxtController();

執行。

1
npm run dev:server

前端開發

前端編譯比較不會耗時,直接執行以下命令。

1
npm run dev

處理解析錯誤

遇到 Parsing error: Unexpected token 的錯誤訊息,確保 babel-eslint 套件有被安裝,並修改 .eslintrc.js 檔為:

1
2
3
4
5
6
7
parserOptions: {
parser: 'babel-eslint',
ecmaFeatures: {
jsx: true,
modules: true,
},
},

程式碼