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.27k stars 291 forks source link

Fails to bundle with eslint #559

Open bradennapier opened 4 years ago

bradennapier commented 4 years ago

If eslint is a dependency this does not work. eslint cli fails to work saying it can not load config files and it creates a whole host of dependency files it loads into the dist folder

import { CLIEngine } from 'eslint';

async function run() {
  const eslintConfig = {
    extensions: ['.js', 'jsx', '.ts', '.tsx'],
    ignorePath: '.gitignore',
    ignore: true,
    useEslintrc: true,
  };

  console.log('[ESLINT] Run With Configuration: ', eslintConfig);

  const eslint = new CLIEngine(eslintConfig);

  const results = await eslint.executeOnFiles(['./src/eslint.ts']);
  console.log(results);
}

run();
npx ncc src/run.ts
node dist/index.js
(node:3673) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined
bradennapier commented 4 years ago

So I think this may be a reason for a lot of the reported issues. I just realized that the problem file is import-fresh which uses __filename.

When packaged this ends up becoming __undefined - so this makes sense that essentially any package using __dirname or __filename are potentially what break all the builds?

'use strict';
const path = require('path');
const resolveFrom = require('resolve-from');
const parentModule = require('parent-module');

module.exports = moduleId => {
    if (typeof moduleId !== 'string') {
        throw new TypeError('Expected a string');
    }

    console.log(__filename);

    const parentPath = parentModule(__filename);

    const filePath = resolveFrom(path.dirname(parentPath), moduleId);

    const oldModule = require.cache[filePath];
    // Delete itself from module parent
    if (oldModule && oldModule.parent) {
        let i = oldModule.parent.children.length;

        while (i--) {
            if (oldModule.parent.children[i].id === filePath) {
                oldModule.parent.children.splice(i, 1);
            }
        }
    }

    delete require.cache[filePath]; // Delete module from cache

    const parent = require.cache[parentPath]; // If `filePath` and `parentPath` are the same, cache will already be deleted so we won't get a memory leak in next step

    return parent === undefined ? require(filePath) : parent.require(filePath); // In case cache doesn't have parent, fall back to normal require
};
timkinsman commented 4 years ago

I'm getting the same issue, did you find any other ncc alternatives for a fix? @bradennapier

FengXianGuo commented 2 years ago

hi I'm getting the same issue, did you fix this issue ?@bradennapier