在TypeScript+Webpack项目中构建ES6模块并解决imagemin引入报错问题
方案1:输出ES6格式bundle(推荐)
- package.json 保留
"type": "module"配置 - 修正
tsconfig.json配置:- 将
compilerOptions.moduleResolution从node改为node16或nodenext,匹配ESM模块解析规则
- 将
- 修正webpack配置中的
webpack-node-externals配置:
原配置默认将所有外部依赖按CommonJS格式处理,会自动把import转为require,修改为:externals: [nodeExternals({ importType: 'module' })]
修改完成后重新打包,输出的bundle会是纯ESM格式,可直接引入imagemin等纯ESM包。
方案2:在CommonJS格式bundle中使用imagemin
如果需要输出CommonJS格式的产物,按以下方式修改:
- package.json 保留
"type": "commonjs"配置 - 修正
tsconfig.json配置:- 将
compilerOptions.module改为CommonJS
- 将
- 调整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 } - 移除
- 代码中引入imagemin的方式改为动态异步引入:
// 不要用静态import语句 const imagemin = await import('imagemin') // 按需加载相关插件 const imageminPngquant = await import('imagemin-pngquant')
修改完成后打包即可在CommonJS格式产物中正常调用imagemin相关能力。
内容的提问来源于stack exchange,提问作者Amit Kumar
相关产品推荐
相关产品推荐

