Skip to content
This repository has been archived by the owner on Jun 8, 2021. It is now read-only.

manual build via rollup #109

Merged
merged 5 commits into from
Dec 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/dist
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/dist
52 changes: 43 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@
"public": true,
"author": "Lenz Weber",
"main": "dist/index.js",
"module": "dist/rtk-query.esm.js",
"module": "dist/esm/index.js",
"sideEffects": false,
"types": "dist/index.d.ts",
"types": "dist/ts/index.d.ts",
"typesVersions": {
">=4.1": {
"dist": [
"dist/min-4.1/index.d.ts"
"dist/ts-4.1/index.d.ts"
],
"dist/*": [
"dist/min-4.1/*"
"dist/ts/*": [
"dist/ts-4.1/*"
]
}
},
Expand All @@ -31,7 +31,7 @@
},
"scripts": {
"start": "tsdx watch",
"build": "tsdx build && node typesversions.js",
"build": "rollup -c && node post-build.js",
"test": "tsdx test",
"lint": "tsdx lint",
"prepare": "yarn build",
Expand Down Expand Up @@ -62,15 +62,43 @@
},
"size-limit": [
{
"path": "dist/rtk-query.cjs.production.min.js",
"limit": "25 KB"
"name": "ESM full",
"path": "dist/esm/index.js",
"limit": "15 KB"
},
{
"name": "createPureApi + setupListeners",
"path": "dist/esm/index.js",
"import": "{ createPureApi, setupListeners }"
},
{
"name": "createApi + setupListeners",
"path": "dist/esm/index.js",
"import": "{ createApi, setupListeners }"
Copy link
Collaborator

@markerikson markerikson Dec 13, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh wow, I had no idea this was a thing! That's really cool!

Can we set this up for RTK too?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will, as soon as I recreate the changes I did here over there ;)

},
{
"name": "fetchBaseQuery",
"path": "dist/esm/index.js",
"import": "{ fetchBaseQuery }"
},
{
"name": "retry",
"path": "dist/esm/index.js",
"import": "{ retry }"
},
{
"name": "ApiProvider",
"path": "dist/esm/index.js",
"import": "{ ApiProvider }"
},
{
"path": "dist/rtk-query.esm.js",
"name": "CJS minfied",
"path": "dist/index.cjs.production.min.js",
"limit": "25 KB"
}
],
"dependencies": {
"@babel/runtime": "^7.12.5",
"immer": ">=8.0.0"
},
"peerDependencies": {
Expand All @@ -96,7 +124,11 @@
}
},
"devDependencies": {
"@babel/plugin-transform-runtime": "^7.12.10",
"@reduxjs/toolkit": "^1.5.0",
"@rollup/plugin-babel": "^5.2.2",
"@rollup/plugin-replace": "^2.3.4",
"@rollup/plugin-typescript": "^8.0.0",
"@size-limit/preset-small-lib": "^4.6.0",
"@testing-library/react": "^11.1.0",
"@testing-library/react-hooks": "^3.4.2",
Expand All @@ -113,6 +145,8 @@
"react-dom": "^16.14.0 || 17.0.0",
"react-redux": "^7.2.1",
"react-test-renderer": "^17.0.1",
"rollup": "^2.34.2",
"rollup-plugin-terser": "^7.0.2",
"shelljs": "^0.8.4",
"size-limit": "^4.6.0",
"ts-node": "^9.0.0",
Expand Down
29 changes: 29 additions & 0 deletions post-build.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const fs = require('fs');
const { cp, rm } = require('shelljs');

if (fs.existsSync('dist/ts-4.1')) {
rm('-r', 'dist/ts-4.1');
}

cp('-r', 'dist/ts/', 'dist/ts-4.1');

const stubTs41Types = `
import { EndpointDefinitions } from './endpointDefinitions';
export declare type TS41Hooks<Definitions extends EndpointDefinitions> = unknown;
export {};
`;

fs.writeFileSync('dist/ts/ts41Types.d.ts', stubTs41Types);

fs.writeFileSync(
'dist/index.js',
`
'use strict'

if (process.env.NODE_ENV === 'production') {
module.exports = require('./index.cjs.production.min.js')
} else {
module.exports = require('./index.cjs.development.js')
}
`
);
99 changes: 99 additions & 0 deletions rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import babel from '@rollup/plugin-babel';
import typescript from '@rollup/plugin-typescript';
import { terser } from 'rollup-plugin-terser';
import replace from '@rollup/plugin-replace';

/** @type {import("rollup").RollupOptions} */
const defaultConfig = {
input: 'src/index.ts',
external: [/@babel\/runtime/, /@reduxjs\/toolkit/, /react$/, /react-redux/, /immer/, /tslib/],
treeshake: {
propertyReadSideEffects: false,
},
};

const defaultTerserOptions = {
output: { comments: false },
compress: {
keep_infinity: true,
pure_getters: true,
passes: 10,
},
ecma: 5,
warnings: true,
};

const defaultTsConfig = { declaration: false, declarationMap: false, target: 'ESNext', module: 'esnext' };

/** @type {import("rollup").RollupOptions} */
const configs = [
// ESM
{
...defaultConfig,
output: [
{
dir: 'dist/esm',
format: 'es',
sourcemap: true,
preserveModules: true,
},
],
plugins: [
typescript(defaultTsConfig),
babel({
exclude: 'node_modules/**',
extensions: ['.js', '.ts'],
babelHelpers: 'runtime',
presets: [
[
'@babel/preset-env',
{
targets: { node: true, browsers: ['defaults', 'not IE 11', 'maintained node versions'] },
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So this now has two builds: an ESM build that does not bundle up the transpiled files, so just a file-for-file transpilation. This should help modern bundlers with tree-shaking quite a lot.
The target I chose for that is "all non-dead browsers, last 2 versions, no IE, maintained node versions".

The CJS build includes IE as well and builds only one file.

Do you think that's sensible @markerikson ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For reference: including IE there bumps the bundle sizes for the ESM module up to

  ESM full
  Size limit: 15 KB
  Size:       13.8 KB with all dependencies, minified and gzipped
  
  createApi + setupListeners
  Size: 12.55 KB with all dependencies, minified and gzipped
  
  fetchBaseQuery
  Size: 3.23 KB with all dependencies, minified and gzipped
  
  retry
  Size: 2.79 KB with all dependencies, minified and gzipped
  
  ApiProvider
  Size: 387 B with all dependencies, minified and gzipped

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, fine by me.

bugfixes: true,
loose: true,
},
],
],
plugins: [['@babel/plugin-transform-runtime', { useESModules: true }]],
}),
],
},
// CJS:
...withMinify((minified) => ({
...defaultConfig,
output: [
{
dir: 'dist',
format: 'cjs',
sourcemap: true,
entryFileNames: minified ? '[name].cjs.production.min.js' : '[name].cjs.development.js',
},
],
plugins: [
typescript(
minified
? defaultTsConfig
: { ...defaultTsConfig, declarationDir: 'dist/ts', declaration: true, declarationMap: true }
),
replace({
values: {
'process.env.NODE_ENV': JSON.stringify(minified ? 'production' : 'development'),
},
}),
babel({
exclude: 'node_modules/**',
extensions: ['.js', '.ts'],
babelHelpers: 'runtime',
presets: [['@babel/preset-env', { targets: { node: true, browsers: ['defaults'] } }]],
plugins: [['@babel/plugin-transform-runtime', { useESModules: false }]],
}),
...(minified ? [terser({ ...defaultTerserOptions, toplevel: true })] : []),
],
})),
];

function withMinify(build) {
return [build(false), build(true)];
}

export default configs;
3 changes: 3 additions & 0 deletions src/HandledError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export class HandledError {
constructor(public readonly value: any) {}
}
5 changes: 1 addition & 4 deletions src/core/buildThunks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { Patch, isDraftable, produceWithPatches, enablePatches } from 'immer';
import { AnyAction, createAsyncThunk, ThunkAction, ThunkDispatch, AsyncThunk } from '@reduxjs/toolkit';

import { PrefetchOptions } from '../react-hooks/buildHooks';
import { HandledError } from '../HandledError';

import { ApiEndpointQuery } from './module';

Expand Down Expand Up @@ -125,10 +126,6 @@ export type UpdateQueryResultThunk<Definitions extends EndpointDefinitions, Part

type PatchCollection = { patches: Patch[]; inversePatches: Patch[] };

export class HandledError {
constructor(public readonly value: any) {}
}

export function buildThunks<
BaseQuery extends BaseQueryFn,
ReducerPath extends string,
Expand Down
3 changes: 1 addition & 2 deletions src/core/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import { buildMiddleware } from './buildMiddleware';
import { buildSelectors } from './buildSelectors';
import { buildInitiate } from './buildInitiate';
import { assertCast, Id, safeAssign } from '../tsHelpers';
import { IS_DEV } from '../utils';
import { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';
import { SliceActions } from './buildSlice';
import { BaseQueryFn } from '../baseQueryTypes';
Expand Down Expand Up @@ -114,7 +113,7 @@ export const coreModule: Module<CoreModule> = {
assertCast<InternalSerializeQueryArgs<any>>(serializeQueryArgs);

const assertEntityType: AssertEntityTypes = (entity) => {
if (IS_DEV()) {
if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {
if (!entityTypes.includes(entity.type as any)) {
console.error(`Entity type '${entity.type}' was used, but not specified in \`entityTypes\`!`);
}
Expand Down
3 changes: 1 addition & 2 deletions src/createApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import type { Api, Module, ModuleName } from './apiTypes';
import type { BaseQueryArg, BaseQueryFn } from './baseQueryTypes';
import { defaultSerializeQueryArgs, SerializeQueryArgs } from './defaultSerializeQueryArgs';
import { DefinitionType, EndpointBuilder, EndpointDefinitions } from './endpointDefinitions';
import { IS_DEV } from './utils';

export interface CreateApiOptions<
BaseQuery extends BaseQueryFn,
Expand Down Expand Up @@ -62,7 +61,7 @@ export function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(
});

for (const [endpoint, definition] of Object.entries(evaluatedEndpoints)) {
if (IS_DEV()) {
if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {
if (!inject.overrideExisting && endpoint in context.endpointDefinitions) {
console.error(
`called \`injectEndpoints\` to override already-existing endpoint ${endpoint} without specifying \`overrideExisting: true\``
Expand Down
2 changes: 1 addition & 1 deletion src/retry.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BaseQueryEnhancer } from './baseQueryTypes';
import { HandledError } from './core/buildThunks';
import { HandledError } from './HandledError';

async function defaultBackoff(attempt: number = 0, maxRetries: number = 5) {
const attempts = Math.min(attempt, maxRetries);
Expand Down
1 change: 0 additions & 1 deletion src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ export * from './flatten';
export * from './shallowEqual';
export * from './useShallowStableValue';
export * from './capitalize';
export * from './isDev';
export * from './isOnline';
export * from './isDocumentVisible';
export * from './copyWithStructuralSharing';
1 change: 0 additions & 1 deletion src/utils/isDev.ts

This file was deleted.

5 changes: 3 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
{
// see https://www.typescriptlang.org/tsconfig to better understand tsconfigs
"include": ["src", "test/flatten.test.ts"],
"include": ["src"],
"compilerOptions": {
"target": "ESnext",
"module": "esnext",
"lib": ["dom", "esnext"],
"importHelpers": true,
Expand Down Expand Up @@ -31,6 +32,6 @@
"forceConsistentCasingInFileNames": true,
// `tsdx build` ignores this option, but it is commonly used when type-checking separately with `tsc`
"noEmit": true,
"downlevelIteration": true
"downlevelIteration": false
}
}
23 changes: 0 additions & 23 deletions typesversions.js

This file was deleted.

Loading