Unverified Commit c7e2a1df authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Use SWC for Next.js core client files (#27196)



Replaces Babel with SWC for Next.js core client-side files.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes
parent 36b81f98
......@@ -18,7 +18,9 @@ declare global {
}
export const requestIdleCallback =
(typeof self !== 'undefined' && self.requestIdleCallback) ||
(typeof self !== 'undefined' &&
self.requestIdleCallback &&
self.requestIdleCallback.bind(window)) ||
function (
cb: (deadline: RequestIdleCallbackDeadline) => void
): NodeJS.Timeout {
......@@ -34,7 +36,9 @@ export const requestIdleCallback =
}
export const cancelIdleCallback =
(typeof self !== 'undefined' && self.cancelIdleCallback) ||
(typeof self !== 'undefined' &&
self.cancelIdleCallback &&
self.cancelIdleCallback.bind(window)) ||
function (id: RequestIdleCallbackHandle) {
return clearTimeout(id)
}
......@@ -141,7 +141,7 @@ export function useRouter(): NextRouter {
// Create a router and assign it as the singleton instance.
// This is used in client side when we are initilizing the app.
// This should **not** be used inside the server.
export const createRouter = (...args: RouterArgs): Router => {
export function createRouter(...args: RouterArgs): Router {
singletonRouter.router = new Router(...args)
singletonRouter.readyCallbacks.forEach((cb) => cb())
singletonRouter.readyCallbacks = []
......
......@@ -59,7 +59,6 @@
"taskr": {
"requires": [
"./taskfile-ncc.js",
"./taskfile-babel.js",
"./taskfile-swc.js"
]
},
......@@ -100,7 +99,6 @@
"pnp-webpack-plugin": "1.6.4",
"postcss": "8.2.15",
"process": "0.11.10",
"prop-types": "15.7.2",
"querystring-es3": "0.2.1",
"raw-body": "2.4.1",
"react-is": "17.0.2",
......@@ -193,7 +191,6 @@
"ast-types": "0.13.2",
"async-retry": "1.2.3",
"async-sema": "3.0.0",
"babel-plugin-dynamic-import-node": "2.3.3",
"babel-plugin-transform-define": "2.0.0",
"babel-plugin-transform-react-remove-prop-types": "0.4.24",
"bfj": "7.0.2",
......
import PropTypes from 'prop-types'
import React, { Component, ReactElement, ReactNode, useContext } from 'react'
import flush from 'styled-jsx/server'
import {
......@@ -234,11 +233,6 @@ export class Head extends Component<
> {
static contextType = DocumentComponentContext
static propTypes = {
nonce: PropTypes.string,
crossOrigin: PropTypes.string,
}
context!: React.ContextType<typeof DocumentComponentContext>
getCssLinks(files: DocumentFiles): JSX.Element[] | null {
......@@ -757,11 +751,6 @@ export function Main() {
export class NextScript extends Component<OriginProps> {
static contextType = DocumentComponentContext
static propTypes = {
nonce: PropTypes.string,
crossOrigin: PropTypes.string,
}
context!: React.ContextType<typeof DocumentComponentContext>
// Source: https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc
......
// taskr babel plugin with Babel 7 support
// https://github.com/lukeed/taskr/pull/305
const path = require('path')
// eslint-disable-next-line import/no-extraneous-dependencies
const transform = require('@babel/core').transform
const babelClientPresetEnvOptions = {
modules: 'commonjs',
targets: {
esmodules: true,
},
bugfixes: true,
loose: true,
// This is handled by the Next.js webpack config that will run next/babel over the same code.
exclude: [
'transform-typeof-symbol',
'transform-async-to-generator',
'transform-spread',
'proposal-object-rest-spread',
'proposal-dynamic-import',
],
}
const babelClientOpts = {
presets: [
'@babel/preset-typescript',
['@babel/preset-env', babelClientPresetEnvOptions],
['@babel/preset-react', { useBuiltIns: true }],
],
plugins: [
// workaround for @taskr/esnext bug replacing `-import` with `-require(`
// eslint-disable-next-line no-useless-concat
'@babel/plugin-syntax-dynamic-impor' + 't',
['@babel/plugin-proposal-class-properties', { loose: true }],
[
'@babel/plugin-transform-runtime',
{
corejs: false,
helpers: true,
regenerator: false,
useESModules: false,
},
],
],
overrides: [
{
test: /\.tsx?$/,
// eslint-disable-next-line import/no-extraneous-dependencies
plugins: [require('@babel/plugin-proposal-numeric-separator').default],
},
],
}
const babelServerOpts = {
presets: [
'@babel/preset-typescript',
['@babel/preset-react', { useBuiltIns: true }],
[
'@babel/preset-env',
{
modules: 'commonjs',
targets: {
node: '12.0',
},
loose: true,
},
],
],
plugins: [
'babel-plugin-dynamic-import-node',
['@babel/plugin-proposal-class-properties', { loose: true }],
],
overrides: [
{
test: /\.tsx?$/,
// eslint-disable-next-line import/no-extraneous-dependencies
plugins: [require('@babel/plugin-proposal-numeric-separator').default],
},
],
}
module.exports = function (task) {
// eslint-disable-next-line require-yield
task.plugin('babel', {}, function* (
file,
serverOrClient,
{ stripExtension, dev } = {}
) {
// Don't compile .d.ts
if (file.base.endsWith('.d.ts')) return
const babelOpts =
serverOrClient === 'client' ? babelClientOpts : babelServerOpts
const filePath = path.join(file.dir, file.base)
const fullFilePath = path.join(__dirname, filePath)
const distFilePath = path.dirname(path.join(__dirname, 'dist', filePath))
const options = {
...babelOpts,
compact: !dev,
babelrc: false,
configFile: false,
cwd: __dirname,
filename: path.join(file.dir, file.base),
sourceFileName: path.relative(distFilePath, fullFilePath),
sourceMaps: true,
}
const output = transform(file.data, options)
const ext = path.extname(file.base)
// Replace `.ts|.tsx` with `.js` in files with an extension
if (ext) {
const extRegex = new RegExp(ext.replace('.', '\\.') + '$', 'i')
// Remove the extension if stripExtension is enabled or replace it with `.js`
file.base = file.base.replace(extRegex, stripExtension ? '' : '.js')
}
// Workaround for noop.js loading
if (file.base === 'next-dev.js') {
output.code = output.code.replace(
/__REPLACE_NOOP_IMPORT__/g,
`import('./dev/noop');`
)
}
if (output.map) {
const map = `${file.base}.map`
output.code += Buffer.from(`\n//# sourceMappingURL=${map}`)
// add sourcemap to `files` array
this._.files.push({
base: map,
dir: file.dir,
data: Buffer.from(JSON.stringify(output.map)),
})
}
file.data = Buffer.from(setNextVersion(output.code))
})
}
function setNextVersion(code) {
return code.replace(
/process\.env\.__NEXT_VERSION/g,
`"${require('./package.json').version}"`
)
}
......@@ -16,10 +16,34 @@ module.exports = function (task) {
// Don't compile .d.ts
if (file.base.endsWith('.d.ts')) return
const options = {
filename: path.join(file.dir, file.base),
sourceMaps: true,
const isClient = serverOrClient === 'client'
const swcClientOptions = {
module: {
type: 'commonjs',
},
jsc: {
loose: true,
target: 'es2016',
parser: {
syntax: 'typescript',
dynamicImport: true,
tsx: file.base.endsWith('.tsx'),
},
transform: {
react: {
pragma: 'React.createElement',
pragmaFrag: 'React.Fragment',
throwIfNamespace: true,
development: false,
useBuiltins: true,
},
},
},
}
const swcServerOptions = {
module: {
type: 'commonjs',
},
......@@ -48,6 +72,15 @@ module.exports = function (task) {
},
}
const swcOptions = isClient ? swcClientOptions : swcServerOptions
const options = {
filename: path.join(file.dir, file.base),
sourceMaps: true,
...swcOptions,
}
const output = yield transform(file.data.toString('utf-8'), options)
const ext = path.extname(file.base)
......
......@@ -861,7 +861,7 @@ export async function nextbuild(task, opts) {
export async function client(task, opts) {
await task
.source(opts.src || 'client/**/*.+(js|ts|tsx)')
.babel('client', { dev: opts.dev })
.swc('client', { dev: opts.dev })
.target('dist/client')
notify('Compiled client files')
}
......@@ -878,14 +878,14 @@ export async function nextbuildstatic(task, opts) {
export async function pages_app(task, opts) {
await task
.source('pages/_app.tsx')
.babel('client', { dev: opts.dev })
.swc('client', { dev: opts.dev })
.target('dist/pages')
}
export async function pages_error(task, opts) {
await task
.source('pages/_error.tsx')
.babel('client', { dev: opts.dev })
.swc('client', { dev: opts.dev })
.target('dist/pages')
}
......
......@@ -127,7 +127,7 @@ describe('Build Output', () => {
expect(indexFirstLoad.endsWith('kB')).toBe(true)
// expect(parseFloat(err404Size)).toBeCloseTo(gz ? 3.17 : 8.51, 1)
expect(err404Size.endsWith('kB')).toBe(true)
expect(err404Size.endsWith('B')).toBe(true)
// expect(parseFloat(err404FirstLoad)).toBeCloseTo(gz ? 66.9 : 204, 1)
expect(err404FirstLoad.endsWith('kB')).toBe(true)
......
......@@ -5589,7 +5589,7 @@ babel-jest@^27.0.0-next.8:
graceful-fs "^4.2.4"
slash "^3.0.0"
babel-plugin-dynamic-import-node@2.3.3, babel-plugin-dynamic-import-node@^2.3.3:
babel-plugin-dynamic-import-node@^2.3.3:
version "2.3.3"
resolved "https://registry.yarnpkg.com/babel-plugin-dynamic-import-node/-/babel-plugin-dynamic-import-node-2.3.3.tgz#84fda19c976ec5c6defef57f9427b3def66e17a3"
dependencies:
......@@ -15766,7 +15766,7 @@ promzard@^0.3.0:
dependencies:
read "1"
prop-types@15.7.2, prop-types@^15.7.2:
prop-types@^15.7.2:
version "15.7.2"
resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.7.2.tgz#52c41e75b8c87e72b9d9360e0206b99dcbffa6c5"
dependencies:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment