vercel / ncc

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

How compatible are paths that need to be dynamically loaded at ncc build time #1161

Closed npm-ued closed 5 months ago

npm-ued commented 5 months ago

in my project ` let env = process.env.NODE_ENV || 'config.dev.js';

env = env.toLowerCase();

// 载入配置文件 const file = path.resolve(__dirname, env);

try { const config = require(file); module.exports = config; console.log('Load config: [%s] %s', env, file); } catch (err) { console.error('Cannot load config: [%s] %s', env, file); throw err; } `js use ncc build how can I be compatible. now build finished throw Error: Cannot find module 'xxx/xxx/config.dev.js'

styfle commented 5 months ago

ncc doesn't evaluate code, it only performs static analysis.

So if you need to always include config.dev.js, I suggest writing the code like this:

let env = process.env.NODE_ENV;
const envPath = path.join(__dirname, env.toLowerCase());
const defaultPath = path.join(__dirname, 'config.dev.js');
try {
  const config = require(env ? envPath : defaultPath);
} catch (err) {
  throw err;
}

ncc has static analysis for path.join() and will include files that match.

npm-ued commented 5 months ago

@styfle thank you the question was resolve