简体   繁体   English

找不到“ .js”文件扩展名的引擎

[英]Engine not found for the “.js” file extension

I want to use koa-views with Koa and Koa-Router with Next.js. 我想在Koa中使用koa视图 ,在Next.js中使用Koa-Router In previous projects, I had no issues with express but in this project, I have to use Koa. 在以前的项目中,express没有任何问题,但是在这个项目中,我必须使用Koa。 Using its router, I want to render a page: /some/page/:id . 我要使用其路由器渲染页面: /some/page/:id Following the same Nextjs way: 遵循相同的Nextjs方式:

 router.get('/some/page/:id', async (ctx, next) => {
   const actualPage = '/some/page/id' // id.js (not actual name 😝)
   await ctx.render(actualPage, {/* could pass object */})
 });

That would work if I was using express. 如果我使用快递,那会起作用。 With Koa: 使用Koa:

const Koa = require('koa');
const views = require('koa-views');
// const render = require('koa-views-render'); <-- I what's this?

[..] // Making things short here
const server = new Koa();
const router = new Router();

// My issue, I'm seeing tutorials using other engines: .ejs etc
// I'm not using any, I only have .js files
server.use(views(__dirname + "/pages", { extension: 'js' }));

Using the same router.get... function as above, I get: 使用与上述相同的router.get...函数,我得到:

Error: Engine not found for the ".js" file extension 错误:找不到“ .js”文件扩展名的引擎

When I go to /some/page/123 , I'd expect it to render the file /pages/some/page/id.js . 当我转到/some/page/123 ,我希望它能够呈现文件/pages/some/page/id.js How? 怎么样?

It turns out I do not need any extra modules to achieve this 🙀 事实证明,我不需要任何额外的模块即可实现此功能🙀

Create a function called, ie, routes then pass app and router as a param 创建一个函数,即路由,然后将approuter作为参数传递

const routes = (router, app) => {

  router.get('/some/page/:id', async (ctx) => {
    const { id } = ctx.params
    const actualPage = '/some/page/id'

    // Render the page
    await app.render(ctx.req, ctx.res, actualPage, {foo: 'Bar'})
  }

}

module.exports = routes

Inside your server.js file: 在您的server.js文件中:

// const routes = require('./routes);
// const app = next({ dev }); // import other modules for this section
// app.prepare().then(() => {
//   const router = new Router();
//   [..]
//   routes(router, app)
// })

The commented out section is a slim down version to make a point in where things should be. 注释掉的部分是精简版,用于指出实际情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM