vercel / ncc

Compile a Node.js project into a single file. Supports TypeScript, binary addons, dynamic requires.
https://npmjs.com/@vercel/ncc
MIT License
9.13k stars 287 forks source link

Require inside forEach is not working and extra files in build folder #608

Open LuisEnMarroquin opened 3 years ago

LuisEnMarroquin commented 3 years ago

Hi, I am creating an api using fastify and mongoose, I am registering the routes when the app starts inside a for each bucle

Here a simplified version of the code

const { connect } = require('mongoose')
const fastify = require('fastify')()
const PORT = 3100

export const io = require('socket.io')(fastify.server)

fastify.register(require('fastify-cors'), {})

const components:Array<String> = [
  'chats'
]

components.forEach(route => {
  fastify.register(require(`./${route}`), {
    prefix: `/api/${route}`
  })
})

let DATABASE_URL = 'mongodb://localhost:27017/mern'

connect(DATABASE_URL, { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log(`Database on ${DATABASE_URL}`)
  })
  .then(() => fastify.listen(PORT, () => {
    console.log(`Listening on ${PORT}`)
  }))
  .catch((error:any) => {
    console.error('Error at server startup', { error })
  })
async function routes (fastify:any, _:any) {

  fastify.get(`/connect`, (req:any, res:any) => {
    try {
      return res.code(200).send({ message: 'hi' })
    } catch (error) {
      return res.code(403).send({ error })
    }
  })

}

export = routes

It compiles just fine

$ npx ncc build src/test.ts -o build --minify
ncc: Version 0.24.1
ncc: Compiling file index.js
ncc: Using typescript@4.0.3 (local user-provided)
   6kB  build\package.json
 410kB  build\code-points.mem
1822kB  build\index.js
2238kB  [13587ms] - ncc 0.24.1

But when I execute, it seems that the module is not being saved in the build file

$ node build/index.js
internal/modules/cjs/loader.js:638
    throw err;
    ^

Error: Cannot find module './chats'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:692:17)

Also the fastify package.json is being copied to the build folder when I run the ncc build command and a .mem file is created

image

songkeys commented 3 years ago

Typical dynamic requiring issue. You have to your routes manually.