rsnext/packages/next/build/swc/options.js
Maia Teegarden bc88831619
Add next-swc jest transform (#30993)
Co-authored-by: JJ Kasper <jj@jjsweb.site>
Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
2021-11-08 17:35:04 +01:00

126 lines
2.9 KiB
JavaScript

const nextDistPath =
/(next[\\/]dist[\\/]shared[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/
function getBaseSWCOptions({
filename,
development,
hasReactRefresh,
globalWindow,
}) {
const isTSFile = filename.endsWith('.ts')
const isTypeScript = isTSFile || filename.endsWith('.tsx')
return {
jsc: {
parser: {
syntax: isTypeScript ? 'typescript' : 'ecmascript',
dynamicImport: true,
// Exclude regular TypeScript files from React transformation to prevent e.g. generic parameters and angle-bracket type assertion from being interpreted as JSX tags.
[isTypeScript ? 'tsx' : 'jsx']: isTSFile ? false : true,
},
transform: {
react: {
runtime: 'automatic',
pragma: 'React.createElement',
pragmaFrag: 'React.Fragment',
throwIfNamespace: true,
development: development,
useBuiltins: true,
refresh: hasReactRefresh,
},
optimizer: {
simplify: false,
globals: {
typeofs: {
window: globalWindow ? 'object' : 'undefined',
},
},
},
regenerator: {
importPath: require.resolve('regenerator-runtime'),
},
},
},
}
}
export function getJestSWCOptions({ filename, esm }) {
let baseOptions = getBaseSWCOptions({
filename,
development: false,
hasReactRefresh: false,
globalWindow: false,
})
const isNextDist = nextDistPath.test(filename)
return {
...baseOptions,
env: {
targets: {
// Targets the current version of Node.js
node: process.versions.node,
},
},
module: {
type: esm && !isNextDist ? 'es6' : 'commonjs',
},
disableNextSsg: true,
disablePageConfig: true,
}
}
export function getLoaderSWCOptions({
filename,
development,
isServer,
pagesDir,
isPageFile,
hasReactRefresh,
}) {
let baseOptions = getBaseSWCOptions({
filename,
development,
globalWindow: !isServer,
hasReactRefresh,
})
const isNextDist = nextDistPath.test(filename)
if (isServer) {
return {
...baseOptions,
// Disables getStaticProps/getServerSideProps tree shaking on the server compilation for pages
disableNextSsg: true,
disablePageConfig: true,
isDevelopment: development,
pagesDir,
isPageFile,
env: {
targets: {
// Targets the current version of Node.js
node: process.versions.node,
},
},
}
} else {
// Matches default @babel/preset-env behavior
baseOptions.jsc.target = 'es5'
return {
...baseOptions,
// Ensure Next.js internals are output as commonjs modules
...(isNextDist
? {
module: {
type: 'commonjs',
},
}
: {}),
disableNextSsg: !isPageFile,
isDevelopment: development,
pagesDir,
isPageFile,
}
}
}