SWC打包TypeScript时无法将ES6 import转为CommonJS require如何解决
问题原因
SWC的spack打包工具配置CommonJS转换不生效,核心是两个配置错误:
- 模块转换规则的配置层级写错:控制语法转换的
module.type字段不属于顶层配置项,放在顶层时不会被编译流程识别,等于没有配置模块转换规则 - 未显式声明打包产物的输出格式:spack不会根据零散的编译配置推断产物规范,需要在output字段明确指定输出格式,才会统一处理包括外部依赖在内的所有导入语句。
修正后的配置
module.exports = { options: { jsc: { target: 'es2018', parser: { syntax: 'typescript', }, }, // 模块转换规则移到options内部 module: { type: 'commonjs', // 适配ES模块默认导入的interop逻辑,和Rollup行为对齐 strict: false, noInterop: false } }, externalModules: ['xml-js'], entry: { 'loader': __dirname + '/src/loader.ts', }, output: { path: __dirname + '/dist', // 显式指定产物为CommonJS格式 format: 'cjs' }, }
配置说明
- 修正后重新执行打包,标记为external的
xml-js导入语句会被转换为const convert = require('xml-js');,和Rollup + rollup-plugin-typescript2的产物行为一致 - 原配置中注释的
isModule: true、dynamicImport: true不需要额外开启,当parser.syntax设置为typescript时,SWC会自动识别TS文件的ES模块语法,动态导入语法在target设为es2018时也会默认支持 - 如果需要自定义require的引用逻辑,可以在
options.module.commonjs配置项下调整interop、懒加载等相关参数,满足不同场景的CommonJS输出需求。
内容的提问来源于stack exchange,提问作者Sebastian
相关产品推荐
相关产品推荐

