From 9f79d71ff6261f9d24dc8f375ae0c54186a139af Mon Sep 17 00:00:00 2001 From: Sam Verschueren Date: Wed, 6 Oct 2021 19:24:41 +0200 Subject: [PATCH] fix: use Function instead of eval to dynamically import config files --- packages/vite/src/node/config.ts | 10 +++++----- packages/vite/src/node/utils.ts | 7 +++++++ 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts index 853e15b119de68..5e40c30a63d0d6 100644 --- a/packages/vite/src/node/config.ts +++ b/packages/vite/src/node/config.ts @@ -14,7 +14,8 @@ import { isExternalUrl, isObject, lookupFile, - normalizePath + normalizePath, + dynamicImport } from './utils' import { resolvePlugins } from './plugins' import chalk from 'chalk' @@ -819,16 +820,15 @@ export async function loadConfigFromFile( const bundled = await bundleConfigFile(resolvedPath, true) dependencies = bundled.dependencies fs.writeFileSync(resolvedPath + '.js', bundled.code) - userConfig = (await eval(`import(fileUrl + '.js?t=${Date.now()}')`)) + userConfig = (await dynamicImport(`${fileUrl}.js?t=${Date.now()}`)) .default fs.unlinkSync(resolvedPath + '.js') debug(`TS + native esm config loaded in ${getTime()}`, fileUrl) } else { - // using eval to avoid this from being compiled away by TS/Rollup + // using Function to avoid this from being compiled away by TS/Rollup // append a query so that we force reload fresh config in case of // server restart - userConfig = (await eval(`import(fileUrl + '?t=${Date.now()}')`)) - .default + userConfig = (await dynamicImport(`${fileUrl}?t=${Date.now()}`)).default debug(`native esm config loaded in ${getTime()}`, fileUrl) } } diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index c904d562e8cdf5..b23c774058572b 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -568,3 +568,10 @@ export function toUpperCaseDriveLetter(pathName: string): string { export const multilineCommentsRE = /\/\*(.|[\r\n])*?\*\//gm export const singlelineCommentsRE = /\/\/.*/g + +/** + * Dynamically import files. It will make sure it's not being compiled away by TS/Rollup. + * + * @param file File path to import. + */ +export const dynamicImport = new Function('file', 'return import(file)')