从Express服务器以编程方式构建Nuxt.js时出错

Anž*_*Mur 5 node.js express vue.js nuxt.js nuxt

我正在尝试从Express服务器以编程方式运行Nuxt,但是在构建应用程序并打开浏览器控制台后出现一些错误:

控制台错误

网络错误

我的nuxt.config.ts看起来像:

import NuxtConfiguration from '@nuxt/config';

/**
 * Nuxt.js admin console app config.
 */
export const config: NuxtConfiguration =  {
  /**
   * Directory paths options. Remove `rootDir` and `modulesDir` properties if you want to run/build admin console Nuxt app.
   */
  rootDir: 'src/admin-console',
  modulesDir: ['../../node_modules'],
  mode: 'universal',
  /*
  ** Headers of the page.
  */
  head: {
    title: process.env.npm_package_name || '',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: process.env.npm_package_description || '' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },
  /*
  ** Customize the progress-bar color.
  */
  loading: { color: '#fff' },
  /*
  ** Global CSS.
  */
  css: [
  ],
  /*
  ** Plugins to load before mounting the App.
  */
  plugins: [
  ],
  /*
  ** Nuxt.js modules.
  */
  modules: [
    // Doc: https://bootstrap-vue.js.org/docs/
    'bootstrap-vue/nuxt',
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
  ],
  /*
  ** Axios module configuration.
  ** See https://axios.nuxtjs.org/options
  */
  axios: {
  },
};

export default config;
Run Code Online (Sandbox Code Playgroud)

我开始将Nuxt构建为Express中间件:

import { Application } from 'express';
import { Nuxt, Builder } from 'nuxt';
import config from '../admin-console/nuxt.config';

/**
 * Builds admin console Nuxt app.
 * @param app Express application instance.
 */
export async function buildAdminConsoleNuxtApp(app: Application) {
  const nuxt = new Nuxt(config);
  try {
    await new Builder(nuxt).build();
  } catch (error) {
    throw new Error(error);
  }

  app.use('/admin', nuxt.render);
}
Run Code Online (Sandbox Code Playgroud)

并像这样注册:

await buildAdminConsoleNuxtApp(this.app);
Run Code Online (Sandbox Code Playgroud)

在我发现的所有示例中,这是构建Nuxt的唯一方法,因此我不知道我做错了什么。内置的应用程序无法检测点击事件等,因此无法正常运行。

Anž*_*Mur 1

问题不在于设置属性,以编程方式运行 Nuxt 时应按照文档config.dev中所述使用该属性。

我现在工作的代码如下所示:

import { Application } from 'express';
import { Nuxt, Builder, Generator } from 'nuxt';
import config from '../admin-console/nuxt.config';
import { EnvType } from '../config/types';

/**
 * Builds admin console Nuxt.js/Vue.js application.
 * @param app Express application instance.
 */ 
export async function buildAdminConsoleNuxtApp(app: Application) {
  config.dev = process.env.NODE_ENV === EnvType.PRODUCTION;
  const nuxt = new Nuxt(config);
  try {
    const builder = await new Builder(nuxt);
    await new Generator(nuxt, builder).generate({ build: true, init: true });
  } catch (error) {
    throw new Error(error);
  }

  app.use('/', nuxt.render);
}
Run Code Online (Sandbox Code Playgroud)