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

在TypeScript+Webpack项目中构建ES6模块并解决imagemin引入报错问题

方案1:输出ES6格式bundle(推荐)

  1. package.json 保留 "type": "module" 配置
  2. 修正tsconfig.json配置:
    • 将 compilerOptions.moduleResolution 从node改为node16或nodenext,匹配ESM模块解析规则
  3. 修正webpack配置中的webpack-node-externals配置:
    原配置默认将所有外部依赖按CommonJS格式处理,会自动把import转为require,修改为:
    externals: [nodeExternals({
      importType: 'module'
    })]
    

修改完成后重新打包,输出的bundle会是纯ESM格式,可直接引入imagemin等纯ESM包。

方案2:在CommonJS格式bundle中使用imagemin

如果需要输出CommonJS格式的产物,按以下方式修改:

  1. package.json 保留 "type": "commonjs" 配置
  2. 修正tsconfig.json配置:
    • 将 compilerOptions.module 改为CommonJS
  3. 调整webpack配置:
    • 移除 experiments.outputModule: true 配置
    • 将 output.library.type 改为commonjs2
    • 调整webpack-node-externals配置,指定imagemin相关依赖按ESM方式引入:
    externals: [nodeExternals({
      importType: (moduleName) => {
        if (moduleName.includes('imagemin')) {
          return `import ${moduleName}`
        }
        return `commonjs ${moduleName}`
      }
    })]
    
    • 新增实验性配置支持顶层await:
    experiments: {
      topLevelAwait: true
    }
    
  4. 代码中引入imagemin的方式改为动态异步引入:
    // 不要用静态import语句
    const imagemin = await import('imagemin')
    // 按需加载相关插件
    const imageminPngquant = await import('imagemin-pngquant')
    

修改完成后打包即可在CommonJS格式产物中正常调用imagemin相关能力。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 14:06:04