You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Parcel构建npm库后出现TypeError:‘function name’不是函数

解决Parcel打包Node.js库时的「TypeError: 'function name' is not a function」问题

问题场景回顾

你的项目结构如下:

  • dist
    • demo.js
    • demo.map
  • src
    • lib
      • lib1.js
    • demo.js
  • run.js

src/demo.js 代码:

const {lib1} = require('./lib/lib1')
module.exports = { lib1: lib1 }

src/lib/lib1.js 代码:

exports.lib1 = function() { return 'hi' }

run.js 代码:

const {lib1} = require('./dist/demo')
console.log(lib1())

执行构建命令:

parcel build src/demo.js -d dist

打包完成后运行node run.js,触发错误:TypeError: 'function name' is not a function


问题根源

Parcel的默认打包目标是浏览器环境,它会把代码包裹成自执行函数(IIFE),并将导出内容挂载到全局对象(比如window)上。但在Node.js环境中,这种打包结构不会正确设置module.exports,导致你通过require('./dist/demo')拿到的不是预期的导出对象,解构出来的lib1要么是undefined,要么不是函数,最终触发错误。


解决方案:指定打包目标为Node.js

你需要明确告诉Parcel,这次打包是针对Node.js环境的,有两种实现方式:

方式1:命令行直接指定target

修改构建命令,添加--target node参数:

parcel build src/demo.js -d dist --target node

方式2:在package.json中配置持久化target

如果需要固定打包规则,可以在项目根目录的package.json中添加以下配置:

"targets": {
  "main": {
    "source": "src/demo.js",
    "distDir": "dist",
    "context": "node"
  }
}

之后直接运行parcel build即可,Parcel会自动读取配置并按Node.js规范打包。


验证效果

重新执行打包命令后,运行node run.js,控制台会正常输出hi,错误彻底消失。

这是因为Parcel在Node.js目标模式下,会遵循CommonJS模块规范打包代码,正确设置module.exports,让你的require调用能获取到预期的导出内容。

内容的提问来源于stack exchange,提问作者Kenzo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:39:27