Skip to content

Commit

Permalink
fix: improve build & bundle (#47)
Browse files Browse the repository at this point in the history
* fix: improve build & bundle

* chore: remove unused deps

* chore: jest ignore /test/ folder

* ci: fetch-dept: 2 for tests

* chore: infer return types
  • Loading branch information
Meemaw authored Dec 27, 2020
1 parent 8a46ba5 commit 741fae3
Show file tree
Hide file tree
Showing 21 changed files with 355 additions and 545 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ jobs:
steps:
- name: Checkout 🛎️
uses: actions/checkout@v2
with:
fetch-depth: 2
- uses: actions/setup-node@v2
with:
node-version: '14.x'
Expand Down
25 changes: 25 additions & 0 deletions jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import type { Config } from '@jest/types';

// eslint-disable-next-line @typescript-eslint/no-var-requires
const pack = require('./package');

const config: Config.InitialOptions = {
roots: ['<rootDir>/src'],
transform: {
'.ts': 'ts-jest',
},
coveragePathIgnorePatterns: ['/node_modules/', '/test/'],
moduleDirectories: ['node_modules', 'src'],
moduleNameMapper: {
'\\.(css|less|scss)$': 'identity-obj-proxy',
},
setupFilesAfterEnv: ['<rootDir>/src/test/setup.ts'],
displayName: pack.name,
name: pack.name,
testEnvironment: 'jest-environment-jsdom-sixteen',
globals: {
'ts-jest': { tsconfig: 'tsconfig.jest.json' },
},
};

export default config;
50 changes: 10 additions & 40 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,54 +33,26 @@
"node": ">=10.22.0"
},
"scripts": {
"prebuild": "rimraf dist",
"build": "tsc --module commonjs && rollup -c rollup.config.ts && cp src/index.css dist",
"start": "yarn storybook",
"test": "jest",
"prebuild": "rimraf dist",
"build": "concurrently \"yarn build:rollup\" \"yarn build:types\" && yarn copy:css",
"build:types": "tsc --p tsconfig.build.json --declaration --outDir dist --emitDeclarationOnly",
"build:rollup": "rollup -c rollup.config.js",
"copy:css": "cp src/index.css dist",
"commit": "git-cz",
"semantic-release": "semantic-release",
"storybook": "start-storybook",
"lint": "concurrently \"npm run prettier\" \"npm run eslint\"",
"eslint": "eslint --max-warnings 0 --ext .ts 'src/**/*'",
"prettier": "prettier --config .prettierrc -l 'src/**/*.{ts,tsx}*' '__tests__/**/*.{ts,tsx}*' || (echo \nThese files are not formatted correctly && false)",
"prettier:fix": "prettier --config .prettierrc -l 'src/**/*.{ts,tsx}*' '__tests__/**/*.{ts,tsx}*' --write"
"prettier": "prettier -l 'src/**/*'",
"prettier:fix": "prettier -l 'src/**/*' --write"
},
"config": {
"commitizen": {
"path": "node_modules/cz-conventional-changelog"
}
},
"jest": {
"transform": {
"\\.(ts|tsx)$": "ts-jest",
".+\\.(css|styl|less|sass|scss)$": "jest-transform-css"
},
"setupFilesAfterEnv": [
"<rootDir>/__tests__/setup.ts"
],
"testEnvironment": "jest-environment-jsdom-sixteen",
"testRegex": "(/__tests__/.*|\\.)\\.(test|spec)\\.(ts|tsx|js)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"coveragePathIgnorePatterns": [
"/node_modules/",
"/__tests__/"
],
"coverageThreshold": {
"global": {
"branches": 90,
"functions": 90,
"lines": 90,
"statements": 90
}
},
"collectCoverageFrom": [
"src/**/*.{ts,tsx}"
]
},
"commitlint": {
"extends": [
"@commitlint/config-conventional"
Expand All @@ -97,20 +69,21 @@
"@storybook/addon-storysource": "6.1.11",
"@storybook/addons": "6.1.11",
"@storybook/react": "6.1.11",
"@storybook/storybook-deployer": "2.8.7",
"@testing-library/jest-dom": "5.11.6",
"@testing-library/react": "11.2.2",
"@testing-library/user-event": "12.6.0",
"@types/fs-extra": "^9.0.6",
"@types/jest": "26.0.19",
"@types/lodash": "^4.14.166",
"@types/node": "14.14.16",
"@types/react": "17.0.0",
"@types/react-dom": "17.0.0",
"@types/rollup-plugin-peer-deps-external": "^2.2.0",
"@typescript-eslint/eslint-plugin": "4.11.0",
"@typescript-eslint/parser": "4.11.0",
"babel-loader": "8.2.2",
"commitizen": "4.2.2",
"concurrently": "5.3.0",
"coveralls": "3.1.0",
"cz-conventional-changelog": "3.3.0",
"eslint": "7.16.0",
"eslint-config-airbnb": "18.2.1",
Expand All @@ -125,11 +98,8 @@
"husky": "4.3.6",
"jest": "26.6.3",
"jest-environment-jsdom-sixteen": "1.0.3",
"jest-transform-css": "2.1.0",
"lodash.camelcase": "4.3.0",
"prettier": "2.2.1",
"pretty-quick": "3.1.0",
"prompt": "1.1.0",
"react": "17.0.1",
"react-dom": "17.0.1",
"rimraf": "3.0.2",
Expand Down
13 changes: 13 additions & 0 deletions rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/* eslint-disable import/no-dynamic-require */
/* eslint-disable @typescript-eslint/no-var-requires */
const path = require('path');

require('ts-node').register({
compilerOptions: {
module: 'CommonJS',
},
});

const { bundle } = require(path.join(process.cwd(), 'rollup', 'builder'));

module.exports = bundle();
68 changes: 0 additions & 68 deletions rollup.config.ts

This file was deleted.

64 changes: 64 additions & 0 deletions rollup/builder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable import/no-dynamic-require */
/* eslint-disable global-require */
import path from 'path';

import { createRollupConfig, Options } from './createRollupConfig';
import { writeCjsEntryFile, getNameFromMain } from './writeCjsEntry';

type Format = 'cjs' | 'esm' | 'umd';

type FormatOptions = Pick<Options, 'env' | 'format'>;
type BaseOption = Pick<FormatOptions, 'env'>;

const OPTIONS: Record<Format, BaseOption[]> = {
cjs: [{ env: 'development' }, { env: 'production' }],
esm: [{}],
umd: [{ env: 'development' }, { env: 'production' }],
};

type Config = {
name: string;
packageName: string;
source: string;
formats: Format[];
};

const prepare = ({ name, formats, source, packageName }: Config) => {
const uniqueFormats = [...new Set(formats)];
const rollupOptions = uniqueFormats.reduce((acc: FormatOptions[], format) => {
const formatOptions = OPTIONS[format].map((o: BaseOption) => ({
...o,
format,
}));
return [...acc, ...formatOptions];
}, []);

return rollupOptions.map((option: FormatOptions) =>
createRollupConfig({
...option,
input: source,
name,
tsconfig: 'tsconfig.build.json',
packageName,
})
);
};

export const bundle = () => {
const pkg = require(path.join(process.cwd(), 'package.json'));
const formats: Format[] = ['cjs'];
const name = getNameFromMain(pkg.main);

if (pkg.module || pkg['jsnext:main']) {
formats.push('esm');
}

if (pkg['umd:main']) {
formats.push('umd');
}

writeCjsEntryFile(pkg.main);

return prepare({ name, formats, source: pkg.source, packageName: pkg.name });
};
87 changes: 87 additions & 0 deletions rollup/createRollupConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/* eslint-disable global-require */
import path from 'path';

import external from 'rollup-plugin-peer-deps-external';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from 'rollup-plugin-typescript2';
import sourcemaps from 'rollup-plugin-sourcemaps';
import replace from '@rollup/plugin-replace';
import { terser } from 'rollup-plugin-terser';
import type { ModuleFormat } from 'rollup';

import { safePackageName } from './safePackageName';
import { pascalcase } from './pascalcase';

export type Options = {
packageName: string;
input: string;
format: ModuleFormat;
name?: string;
umdName?: string;
minify?: boolean;
env?: string;
tsconfig?: string;
};

export const createRollupConfig = (options: Options) => {
const name = options.name || safePackageName(options.packageName);
const umdName =
options.umdName || pascalcase(safePackageName(options.packageName));

const shouldMinify = options.minify || options.env === 'production';
const tsconfigPath = options.tsconfig || 'tsconfig.json';

const outputName = [
path.join('dist', name),
options.format,
options.env,
shouldMinify ? 'min' : '',
'js',
]
.filter(Boolean)
.join('.');

const plugins = [
external(),
typescript({ typescript: require('typescript'), tsconfig: tsconfigPath }),
resolve({ mainFields: ['browser', 'jsnext:main', 'module', 'main'] }),
];

if (options.format === 'umd') {
plugins.push(commonjs({ include: /\/node_modules\// }));
}

if (options.env !== undefined) {
plugins.push(
replace({ 'process.env.NODE_ENV': JSON.stringify(options.env) })
);
}

plugins.push(sourcemaps());

if (shouldMinify) {
plugins.push(
terser({
format: { comments: false },
compress: { drop_console: true },
})
);
}

return {
input: options.input,
output: {
file: outputName,
format: options.format,
name: umdName,
sourcemap: true,
globals: {
react: 'React',
'react-dom': 'ReactDOM',
},
exports: 'named',
},
plugins,
};
};
29 changes: 29 additions & 0 deletions rollup/pascalcase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import isFunction from 'lodash/isFunction';
import isNil from 'lodash/isNil';

const titlecase = (input: string) =>
input[0].toLocaleUpperCase() + input.slice(1);

export const pascalcase = (value: string) => {
if (isNil(value)) {
return '';
}
if (!isFunction(value.toString)) {
return '';
}

const input = value.toString().trim();
if (input === '') {
return '';
}
if (input.length === 1) {
return input.toLocaleUpperCase();
}

const match = input.match(/[a-zA-Z0-9]+/g);
if (match) {
return match.map((m) => titlecase(m)).join('');
}

return input;
};
Loading

0 comments on commit 741fae3

Please sign in to comment.