feat: swc register (#1779)

* feat: implements esbuild and removes babel

* chore: implements esbuild-register

* chore: tests passing

* chore: implements @swc/jest for tests

* feat: implements swc

* chore: removes build and relies on swc/register only

* chore: converts some exports

* chore: flattens ts configs

* chore: allows tsx in swc

* chore: converts more exports into js

* chore: restores payload module.exports

* chore: removes unused dependency
This commit is contained in:
James Mikrut
2023-01-04 10:11:26 -05:00
committed by GitHub
parent 82501319ce
commit c11bcd1416
37 changed files with 345 additions and 2065 deletions

View File

@@ -1,21 +0,0 @@
module.exports = {
presets: [
require.resolve('@babel/preset-typescript'),
[
require.resolve('@babel/preset-env'),
{
targets: [
'defaults',
'not IE 11',
'not IE_Mob 11',
],
},
],
require.resolve('@babel/preset-react'),
],
plugins: [
require.resolve('@babel/plugin-transform-runtime'),
require.resolve('@babel/plugin-proposal-class-properties'),
require.resolve('@babel/plugin-proposal-nullish-coalescing-operator'),
],
};

View File

@@ -1,23 +1,17 @@
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable global-require */
import webpack from 'webpack';
import getWebpackProdConfig from '../webpack/getProdConfig';
import findConfig from '../config/find';
import loadConfig from '../config/load';
const configPath = findConfig();
const rawConfigPath = findConfig();
export const build = (): void => {
export const build = async (): Promise<void> => {
try {
const config = loadConfig();
const webpackProdConfig = getWebpackProdConfig({
...config,
paths: {
...(config.paths || {}),
config: configPath,
},
});
const webpackProdConfig = getWebpackProdConfig(config);
webpack(webpackProdConfig, (err, stats) => { // Stats Object
if (err || stats.hasErrors()) {
@@ -35,7 +29,7 @@ export const build = (): void => {
});
} catch (err) {
console.error(err);
throw new Error(`Error: can't find the configuration file located at ${configPath}.`);
throw new Error(`Error: can't find the configuration file located at ${rawConfigPath}.`);
}
};

View File

@@ -2,12 +2,6 @@
import minimist from 'minimist';
import { generateTypes } from './generateTypes';
import { generateGraphQLSchema } from './generateGraphQLSchema';
import babelConfig from '../babel.config';
require('@babel/register')({
...babelConfig,
extensions: ['.ts', '.tsx', '.js', '.jsx'],
});
const { build } = require('./build');

View File

@@ -0,0 +1 @@
export const clientFiles = ['.scss', '.css', '.svg', '.png', '.jpg', '.eot', '.ttf', '.woff', '.woff2'];

View File

@@ -1,36 +1,36 @@
/* eslint-disable import/no-dynamic-require */
/* eslint-disable global-require */
// eslint-disable-next-line import/no-extraneous-dependencies
import swcRegister from '@swc/register';
import path from 'path';
import pino from 'pino';
import Logger from '../utilities/logger';
import { SanitizedConfig } from './types';
import findConfig from './find';
import validate from './validate';
import babelConfig from '../babel.config';
const removedExtensions = ['.scss', '.css', '.svg', '.png', '.jpg', '.eot', '.ttf', '.woff', '.woff2'];
import { clientFiles } from './clientFiles';
const loadConfig = (logger?: pino.Logger): SanitizedConfig => {
const localLogger = logger ?? Logger();
const configPath = findConfig();
removedExtensions.forEach((ext) => {
require.extensions[ext] = () => null;
});
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('@babel/register')({
...babelConfig,
extensions: ['.ts', '.tsx', '.js', '.jsx'],
env: {
development: {
sourceMaps: 'inline',
retainLines: true,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
swcRegister({
jsc: {
parser: {
syntax: 'typescript',
tsx: true,
},
},
ignore: [
/node_modules[\\/](?!.pnpm[\\/].*[\\/]node_modules[\\/])(?!payload[\\/]dist[\\/]admin|payload[\\/]components).*/,
],
module: {
type: 'commonjs',
},
});
clientFiles.forEach((ext) => {
require.extensions[ext] = () => null;
});
// eslint-disable-next-line @typescript-eslint/no-var-requires
@@ -38,14 +38,18 @@ const loadConfig = (logger?: pino.Logger): SanitizedConfig => {
if (config.default) config = config.default;
const validatedConfig = validate(config, localLogger);
let validatedConfig = config;
if (process.env.NODE_ENV !== 'production') {
validatedConfig = validate(config, localLogger);
}
return {
...validatedConfig,
paths: {
...(validatedConfig.paths || {}),
configDir: path.dirname(configPath),
config: configPath,
rawConfig: configPath,
},
};
};

View File

@@ -165,15 +165,15 @@ export type Endpoint = {
path: string;
/** HTTP method (or "all") */
method:
| 'get'
| 'head'
| 'post'
| 'put'
| 'patch'
| 'delete'
| 'connect'
| 'options'
| string;
| 'get'
| 'head'
| 'post'
| 'put'
| 'patch'
| 'delete'
| 'connect'
| 'options'
| string;
/**
* Middleware that will be called when the path/method matches
*
@@ -285,9 +285,9 @@ export type Config = {
* Add custom components after the collection overview
*/
afterDashboard?: React.ComponentType<any>[];
/**
* Add custom components before the email/password field
*/
/**
* Add custom components before the email/password field
*/
beforeLogin?: React.ComponentType<any>[];
/**
* Add custom components after the email/password field
@@ -540,7 +540,11 @@ export type SanitizedConfig = Omit<
> & {
collections: SanitizedCollectionConfig[];
globals: SanitizedGlobalConfig[];
paths: { [key: string]: string };
paths: {
configDir: string
config: string
rawConfig: string
};
};
export type EntityDescription =

View File

@@ -248,7 +248,7 @@ export class Payload {
return restoreVersion(this, options);
}
login = async <T extends TypeWithID = any>(options: LoginOptions): Promise<LoginResult & { user: T}> => {
login = async <T extends TypeWithID = any>(options: LoginOptions): Promise<LoginResult & { user: T }> => {
const { login } = localOperations.auth;
return login(this, options);
}

View File

@@ -26,11 +26,13 @@ export default {
module: {
rules: [
{
test: /\.js$/,
test: /\.(t|j)sx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
use: [
{
loader: require.resolve('swc-loader'),
},
],
},
{
oneOf: [

View File

@@ -2,7 +2,6 @@ import path from 'path';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import webpack, { Configuration } from 'webpack';
import { SanitizedConfig } from '../config/types';
import babelConfig from '../babel.config';
const mockModulePath = path.resolve(__dirname, './mocks/emptyModule.js');
const mockDotENVPath = path.resolve(__dirname, './mocks/dotENV.js');
@@ -20,11 +19,18 @@ export default (config: SanitizedConfig): Configuration => ({
rules: [
{
test: /\.(t|j)sx?$/,
exclude: /node_modules[\\/](?!(@payloadcms[\\/]payload)[\\/]).*/,
exclude: /node_modules/,
use: [
{
loader: require.resolve('babel-loader'),
options: babelConfig,
loader: require.resolve('swc-loader'),
options: {
jsc: {
parser: {
syntax: 'typescript',
tsx: true,
},
},
},
},
],
},
@@ -47,7 +53,7 @@ export default (config: SanitizedConfig): Configuration => ({
},
modules: ['node_modules', path.resolve(__dirname, '../../node_modules')],
alias: {
'payload-config': config.paths.config,
'payload-config': config.paths.rawConfig,
payload$: mockModulePath,
'payload-user-css': config.admin.css,
dotenv: mockDotENVPath,

View File

@@ -1,12 +1,13 @@
import TerserJSPlugin from 'terser-webpack-plugin';
import MiniCSSExtractPlugin from 'mini-css-extract-plugin';
import CssMinimizerPlugin from 'css-minimizer-webpack-plugin';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import path from 'path';
import { Configuration } from 'webpack';
import { SanitizedConfig } from '../config/types';
import getBaseConfig from './getBaseConfig';
// eslint-disable-next-line import/no-extraneous-dependencies, @typescript-eslint/no-var-requires
const SwcMinifyWebpackPlugin = require('swc-minify-webpack-plugin');
export default (payloadConfig: SanitizedConfig): Configuration => {
const baseConfig = getBaseConfig(payloadConfig) as any;
@@ -21,7 +22,7 @@ export default (payloadConfig: SanitizedConfig): Configuration => {
mode: 'production',
stats: 'errors-only',
optimization: {
minimizer: [new TerserJSPlugin({}), new CssMinimizerPlugin()],
minimizer: [new SwcMinifyWebpackPlugin()],
splitChunks: {
cacheGroups: {
styles: {