如何用JavaScript打包器展开其他模块导入的函数调用?
实现函数调用内联的解决方案
完全可以用Rollup或ESBuild这类轻量打包工具实现你要的效果,下面是具体步骤:
方法一:用Rollup实现
- 安装Rollup
npm install rollup --save-dev
- 在项目根目录创建
rollup.config.js配置文件:
export default { input: 'hello.js', // 入口文件 output: { file: 'bundle.js', // 输出文件 format: 'esm', // 保持ES模块格式,方便后续导入 treeshake: { // 关闭各种副作用检测,确保纯函数被完全内联 moduleSideEffects: false, propertyReadSideEffects: false, tryCatchDeoptimization: false } } };
- 执行打包命令:
npx rollup -c
执行后生成的bundle.js就会是你想要的形式:
export function hello(name) { (function (message) { console.log(message); })(`Hello, ${name}`); }
方法二:用ESBuild实现(更快)
ESBuild是速度极快的打包工具,配置更简单:
- 安装ESBuild
npm install esbuild --save-dev
- 直接执行打包命令:
npx esbuild hello.js --bundle --format=esm --outfile=bundle.js --tree-shaking=true
或者创建配置文件esbuild.config.js:
require('esbuild').build({ entryPoints: ['hello.js'], bundle: true, format: 'esm', outfile: 'bundle.js', treeShaking: true }).catch(() => process.exit(1));
然后运行:
node esbuild.config.js
同样会生成符合要求的bundle.js。
原理说明
这类打包工具的Tree-shaking和函数内联能力,会识别出showMessage是仅被hello调用的纯函数(无外部副作用),因此会直接把showMessage的代码展开到hello函数内部,最终生成自包含的hello函数,刚好满足你传给Selenium executeScript的需求——毕竟executeScript需要序列化后的函数是完全独立的,不能依赖外部模块。
内容的提问来源于stack exchange,提问作者kumarchandresh
相关产品推荐
相关产品推荐

