1// Based on Next.js swc taskr file. 2// https://github.com/vercel/next.js/blob/5378db8f807dbb9ff0993662f0a39d0f6cba2452/packages/next/taskfile-swc.js 3 4const { transform } = require('@swc/core'); 5const path = require('path'); 6 7module.exports = function (task) { 8 task.plugin('swc', {}, function* (file, environment, { stripExtension } = {}) { 9 // Don't compile .d.ts 10 if (file.base.endsWith('.d.ts')) return; 11 12 const setting = { 13 output: 'build', 14 options: { 15 module: { 16 type: 'commonjs', 17 }, 18 env: { 19 targets: { 20 node: '14.17.6', 21 }, 22 }, 23 jsc: { 24 loose: true, 25 parser: { 26 syntax: 'typescript', 27 dynamicImport: true, 28 }, 29 }, 30 }, 31 }; 32 33 const filePath = path.join(file.dir, file.base); 34 const inputFilePath = path.join(__dirname, filePath); 35 const outputFilePath = path.dirname(path.join(__dirname, setting.output, filePath)); 36 37 const options = { 38 filename: path.join(file.dir, file.base), 39 sourceMaps: true, 40 sourceFileName: path.relative(outputFilePath, inputFilePath), 41 ...setting.options, 42 }; 43 44 const output = yield transform(file.data.toString('utf-8'), options); 45 const ext = path.extname(file.base); 46 47 // Replace `.ts|.tsx` with `.js` in files with an extension 48 if (ext) { 49 const extRegex = new RegExp(ext.replace('.', '\\.') + '$', 'i'); 50 // Remove the extension if stripExtension is enabled or replace it with `.js` 51 file.base = file.base.replace(extRegex, stripExtension ? '' : '.js'); 52 } 53 54 if (output.map) { 55 const map = `${file.base}.map`; 56 57 output.code += Buffer.from(`\n//# sourceMappingURL=${map}`); 58 59 // add sourcemap to `files` array 60 this._.files.push({ 61 base: map, 62 dir: file.dir, 63 data: Buffer.from(output.map), 64 }); 65 } 66 67 file.data = Buffer.from(output.code); 68 }); 69}; 70