Skip to content

Commit

Permalink
Merge pull request #6 from inthepocket/feature/default-prettier-rules
Browse files Browse the repository at this point in the history
feat(prettierrc): change to itp prettier rules
  • Loading branch information
easybird authored Sep 17, 2018
2 parents 0c26a33 + 258495f commit 28a1824
Show file tree
Hide file tree
Showing 23 changed files with 186 additions and 278 deletions.
7 changes: 3 additions & 4 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
{
"printWidth": 80,
"printWidth": 100,
"tabWidth": 2,
"useTabs": false,
"semi": false,
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"bracketSpacing": false,
"jsxBracketSameLine": false
}
}
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,15 +130,15 @@ Or, for `babel`, a `.babelrc` with:
Or, for `jest`:

```javascript
const {jest: jestConfig} = require('itp-react-scripts/config')
const { jest: jestConfig } = require('itp-react-scripts/config');
module.exports = Object.assign(jestConfig, {
// your overrides here

// for test written in Typescript, add:
transform: {
'\\.(ts|tsx)$': '<rootDir>/node_modules/ts-jest/preprocessor.js',
},
})
});
```

> Note: `itp-react-scripts` intentionally does not merge things for you when you start
Expand All @@ -164,6 +164,7 @@ Thanks goes to these people ([emoji key][emojis]):
| [<img src="https://avatars.githubusercontent.com/u/1500684?v=3" width="100px;"/><br /><sub><b>Kent C. Dodds</b></sub>](https://kentcdodds.com)<br />[💻](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/commits?author=kentcdodds "Code") [📖](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/commits?author=kentcdodds "Documentation") [🚇](#infra-kentcdodds "Infrastructure (Hosting, Build-Tools, etc)") [⚠️](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/commits?author=kentcdodds "Tests") | [<img src="https://avatars2.githubusercontent.com/u/22251956?v=4" width="100px;"/><br /><sub><b>Suhas Karanth</b></sub>](https://github.com/sudo-suhas)<br />[💻](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/commits?author=sudo-suhas "Code") [🐛](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/issues?q=author%3Asudo-suhas "Bug reports") [⚠️](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/commits?author=sudo-suhas "Tests") | [<img src="https://avatars0.githubusercontent.com/u/1402095?v=4" width="100px;"/><br /><sub><b>Matt Parrish</b></sub>](https://github.com/pbomb)<br />[💻](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/commits?author=pbomb "Code") [⚠️](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/commits?author=pbomb "Tests") | [<img src="https://avatars3.githubusercontent.com/u/1319157?v=4" width="100px;"/><br /><sub><b>Mateus</b></sub>](https://github.com/mateuscb)<br />[💻](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/commits?author=mateuscb "Code") [⚠️](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/commits?author=mateuscb "Tests") | [<img src="https://avatars1.githubusercontent.com/u/2344137?v=4" width="100px;"/><br /><sub><b>Macklin Underdown</b></sub>](http://macklin.underdown.me)<br />[💻](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/commits?author=macklinu "Code") [⚠️](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/commits?author=macklinu "Tests") | [<img src="https://avatars2.githubusercontent.com/u/179534?v=4" width="100px;"/><br /><sub><b>stereobooster</b></sub>](https://github.com/stereobooster)<br />[💻](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/commits?author=stereobooster "Code") [⚠️](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/commits?author=stereobooster "Tests") | [<img src="https://avatars0.githubusercontent.com/u/410792?v=4" width="100px;"/><br /><sub><b>Dony Sukardi</b></sub>](http://dsds.io)<br />[🐛](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/issues?q=author%3Adonysukardi "Bug reports") [💻](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/commits?author=donysukardi "Code") |
| :---: | :---: | :---: | :---: | :---: | :---: | :---: |
| [<img src="https://avatars3.githubusercontent.com/u/8997319?v=4" width="100px;"/><br /><sub><b>Alexander Nanberg</b></sub>](https://alexandernanberg.com)<br />[💻](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/commits?author=alexandernanberg "Code") | [<img src="https://avatars0.githubusercontent.com/u/8142934?v=4" width="100px;"/><br /><sub><b>Easybird</b></sub>](http://easybird.be)<br />[💻](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/commits?author=easybird "Code") [📖](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/commits?author=easybird "Documentation") [🚇](#infra-easybird "Infrastructure (Hosting, Build-Tools, etc)") | [<img src="https://avatars3.githubusercontent.com/u/6213695?v=4" width="100px;"/><br /><sub><b>Thibault Maekelbergh</b></sub>](http://thibmaek.com)<br />[💻](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/commits?author=thibmaek "Code") [📖](https://github.com/kentcdodds/@inthepocket/itp-react-scripts/commits?author=thibmaek "Documentation") |

<!-- ALL-CONTRIBUTORS-LIST:END -->

This project follows the [all-contributors][all-contributors] specification.
Expand Down
4 changes: 1 addition & 3 deletions src/__tests__/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@ expect.addSnapshotSerializer({

cases(
'format',
({
snapshotLog = false, throws = false, signal = false, args = [],
}) => {
({ snapshotLog = false, throws = false, signal = false, args = [] }) => {
// beforeEach
const { sync: crossSpawnSyncMock } = require('cross-spawn');
const originalExit = process.exit;
Expand Down
8 changes: 4 additions & 4 deletions src/__tests__/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ test("resolveBin resolves to the full path when it's not in $PATH", () => {
});

test("resolveBin resolves to the binary if it's in $PATH", () => {
whichSyncMock.mockImplementationOnce(() => require.resolve('cross-env/dist/bin/cross-env').replace(process.cwd(), '.'));
whichSyncMock.mockImplementationOnce(() =>
require.resolve('cross-env/dist/bin/cross-env').replace(process.cwd(), '.'),
);
expect(require('../utils').resolveBin('cross-env')).toBe('cross-env');
expect(whichSyncMock).toHaveBeenCalledTimes(1);
expect(whichSyncMock).toHaveBeenCalledWith('cross-env');
Expand Down Expand Up @@ -80,9 +82,7 @@ test('parseEnv parses the existing environment variable', () => {

test("parseEnv returns the default if the environment variable doesn't exist", () => {
const defaultVal = { hello: 'world' };
expect(require('../utils').parseEnv('DOES_NOT_EXIST', defaultVal)).toBe(
defaultVal,
);
expect(require('../utils').parseEnv('DOES_NOT_EXIST', defaultVal)).toBe(defaultVal);
});

test('ifAnyDep returns the true argument if true and false argument if false', () => {
Expand Down
4 changes: 1 addition & 3 deletions src/config/__tests__/lintstagedrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ function hasGitAdd(linter) {
}

function getJsLinter(linters) {
const key = Object.keys(linters).find(
k => k.includes('**') && k.includes('js'),
);
const key = Object.keys(linters).find(k => k.includes('**') && k.includes('js'));
return linters[key];
}
67 changes: 26 additions & 41 deletions src/config/babelrc.js
Original file line number Diff line number Diff line change
@@ -1,78 +1,63 @@
const browserslist = require('browserslist')
const semver = require('semver')
const browserslist = require('browserslist');
const semver = require('semver');

const {ifAnyDep, parseEnv, appDirectory, pkg} = require('../utils')
const { ifAnyDep, parseEnv, appDirectory, pkg } = require('../utils');

const isTest = (process.env.BABEL_ENV || process.env.NODE_ENV) === 'test'
const isPreact = parseEnv('BUILD_PREACT', false)
const isRollup = parseEnv('BUILD_ROLLUP', false)
const isUMD = process.env.BUILD_FORMAT === 'umd'
const isWebpack = parseEnv('BUILD_WEBPACK', false)
const treeshake = parseEnv('BUILD_TREESHAKE', isRollup || isWebpack)
const alias = parseEnv('BUILD_ALIAS', isPreact ? {react: 'preact'} : null)
const isTest = (process.env.BABEL_ENV || process.env.NODE_ENV) === 'test';
const isPreact = parseEnv('BUILD_PREACT', false);
const isRollup = parseEnv('BUILD_ROLLUP', false);
const isUMD = process.env.BUILD_FORMAT === 'umd';
const isWebpack = parseEnv('BUILD_WEBPACK', false);
const treeshake = parseEnv('BUILD_TREESHAKE', isRollup || isWebpack);
const alias = parseEnv('BUILD_ALIAS', isPreact ? { react: 'preact' } : null);

/**
* use the strategy declared by browserslist to load browsers configuration.
* fallback to the default if don't found custom configuration
* @see https://github.com/browserslist/browserslist/blob/master/node.js#L139
*/
const browsersConfig = browserslist.loadConfig({path: appDirectory}) || [
'ie 10',
'ios 7',
]
const browsersConfig = browserslist.loadConfig({ path: appDirectory }) || ['ie 10', 'ios 7'];

const envTargets = isTest
? {node: 'current'}
? { node: 'current' }
: isWebpack || isRollup
? {browsers: browsersConfig}
: {node: getNodeVersion(pkg)}
const envOptions = {modules: false, loose: true, targets: envTargets}
? { browsers: browsersConfig }
: { node: getNodeVersion(pkg) };
const envOptions = { modules: false, loose: true, targets: envTargets };

module.exports = () => ({
presets: [
[require.resolve('@babel/preset-env'), envOptions],
ifAnyDep(
['react', 'preact'],
[
require.resolve('@babel/preset-react'),
{pragma: isPreact ? 'React.h' : undefined},
],
[require.resolve('@babel/preset-react'), { pragma: isPreact ? 'React.h' : undefined }],
),
].filter(Boolean),
plugins: [
require.resolve('babel-plugin-macros'),
alias
? [
require.resolve('babel-plugin-module-resolver'),
{root: ['./src'], alias},
]
: null,
alias ? [require.resolve('babel-plugin-module-resolver'), { root: ['./src'], alias }] : null,
[
require.resolve('babel-plugin-transform-react-remove-prop-types'),
isPreact ? {removeImport: true} : {mode: 'unsafe-wrap'},
isPreact ? { removeImport: true } : { mode: 'unsafe-wrap' },
],
isUMD
? require.resolve('babel-plugin-transform-inline-environment-variables')
: null,
[require.resolve('@babel/plugin-proposal-class-properties'), {loose: true}],
isUMD ? require.resolve('babel-plugin-transform-inline-environment-variables') : null,
[require.resolve('@babel/plugin-proposal-class-properties'), { loose: true }],
require.resolve('babel-plugin-minify-dead-code-elimination'),
treeshake
? null
: require.resolve('@babel/plugin-transform-modules-commonjs'),
treeshake ? null : require.resolve('@babel/plugin-transform-modules-commonjs'),
].filter(Boolean),
})
});

function getNodeVersion({engines: {node: nodeVersion = '8'} = {}}) {
function getNodeVersion({ engines: { node: nodeVersion = '8' } = {} }) {
const oldestVersion = semver
.validRange(nodeVersion)
.replace(/[>=<|]/g, ' ')
.split(' ')
.filter(Boolean)
.sort(semver.compare)[0]
.sort(semver.compare)[0];
if (!oldestVersion) {
throw new Error(
`Unable to determine the oldest version in the range in your package.json at engines.node: "${nodeVersion}". Please attempt to make it less ambiguous.`,
)
);
}
return oldestVersion
return oldestVersion;
}
9 changes: 3 additions & 6 deletions src/config/eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const {ifAnyDep} = require('../utils')
const { ifAnyDep } = require('../utils');

module.exports = {
extends: [
Expand All @@ -11,10 +11,7 @@ module.exports = {
ifAnyDep('flow-bin', 'eslint-config-prettier/flowtype'),
require.resolve('eslint-config-prettier/react'),
].filter(Boolean),
parser: ifAnyDep(
['babel-cli', 'babel-core', 'babel-eslint', 'babel-loader'],
'babel-eslint',
),
parser: ifAnyDep(['babel-cli', 'babel-core', 'babel-eslint', 'babel-loader'], 'babel-eslint'),
rules: {
'no-use-before-define': [
'error',
Expand All @@ -35,4 +32,4 @@ module.exports = {
alert: false,
__DEV__: true,
},
}
};
11 changes: 2 additions & 9 deletions src/config/jest.config.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
const path = require('path');
const {
ifAnyDep, hasFile, hasPkgProp, fromRoot,
} = require('../utils');
const { ifAnyDep, hasFile, hasPkgProp, fromRoot } = require('../utils');

const here = p => path.join(__dirname, p);

const useBuiltInBabelConfig = !hasFile('.babelrc') && !hasPkgProp('babel');

const ignores = [
'/node_modules/',
'/fixtures/',
'/__tests__/helpers/',
'__mocks__',
];
const ignores = ['/node_modules/', '/fixtures/', '/__tests__/helpers/', '__mocks__'];

const jestConfig = {
roots: [fromRoot('src')],
Expand Down
5 changes: 1 addition & 4 deletions src/config/lintstagedrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@ module.exports = {
concurrent: false,
linters: {
'README.md': [`${doctoc} --maxlevel 3 --notitle`, 'git add'],
'.all-contributorsrc': [
`${itpScripts} contributors generate`,
'git add README.md',
],
'.all-contributorsrc': [`${itpScripts} contributors generate`, 'git add README.md'],
'**/*.+(js|json|less|css|ts|tsx|md)': [
isOptedOut('autoformat', null, `${itpScripts} format`),
`${itpScripts} lint --fix`,
Expand Down
68 changes: 27 additions & 41 deletions src/config/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,23 +46,16 @@ const defaultExternal = umd ? peerDeps : deps.concat(peerDeps);

const input = glob.sync(
fromRoot(
process.env.BUILD_INPUT
|| ifFile(
`src/${format}-entry.js`,
`src/${format}-entry.js`,
'src/index.js',
),
process.env.BUILD_INPUT ||
ifFile(`src/${format}-entry.js`, `src/${format}-entry.js`, 'src/index.js'),
),
);
const codeSplitting = input.length > 1;

if (
codeSplitting
&& uniq(input.map(single => path.basename(single))).length !== input.length
) {
if (codeSplitting && uniq(input.map(single => path.basename(single))).length !== input.length) {
throw new Error(
'Filenames of code-splitted entries should be unique to get deterministic output filenames.'
+ `\nReceived those: ${input}.`,
'Filenames of code-splitted entries should be unique to get deterministic output filenames.' +
`\nReceived those: ${input}.`,
);
}

Expand All @@ -86,13 +79,7 @@ if (isPreact) {
const externalPattern = new RegExp(`^(${external.join('|')})($|/)`);
const externalPredicate = external.length === 0 ? () => false : id => externalPattern.test(id);

const filename = [
pkg.name,
filenameSuffix,
`.${format}`,
minify ? '.min' : null,
'.js',
]
const filename = [pkg.name, filenameSuffix, `.${format}`, minify ? '.min' : null, '.js']
.filter(Boolean)
.join('');

Expand All @@ -113,18 +100,19 @@ const output = [
const useBuiltinConfig = !hasFile('.babelrc') && !hasPkgProp('babel');
const babelPresets = useBuiltinConfig ? [here('../config/babelrc.js')] : [];

const replacements = Object.entries(
umd ? process.env : omit(process.env, ['NODE_ENV']),
).reduce((acc, [key, value]) => {
let val;
if (value === 'true' || value === 'false' || Number.isInteger(+value)) {
val = value;
} else {
val = JSON.stringify(value);
}
acc[`process.env.${key}`] = val;
return acc;
}, {});
const replacements = Object.entries(umd ? process.env : omit(process.env, ['NODE_ENV'])).reduce(
(acc, [key, value]) => {
let val;
if (value === 'true' || value === 'false' || Number.isInteger(+value)) {
val = value;
} else {
val = JSON.stringify(value);
}
acc[`process.env.${key}`] = val;
return acc;
},
{},
);

module.exports = {
input: codeSplitting ? input : input[0],
Expand All @@ -145,24 +133,22 @@ module.exports = {
replace(replacements),
useSizeSnapshot ? sizeSnapshot({ printInfo: false }) : null,
minify ? terser() : null,
codeSplitting
&& ((writes = 0) => ({
codeSplitting &&
((writes = 0) => ({
onwrite() {
// eslint-disable-next-line no-plusplus, no-param-reassign
if (++writes !== input.length) {
return;
}

input
.filter(single => single.indexOf('index.js') === -1)
.forEach((single) => {
const chunk = path.basename(single);
input.filter(single => single.indexOf('index.js') === -1).forEach(single => {
const chunk = path.basename(single);

writeExtraEntry(chunk.replace(/\..+$/, ''), {
cjs: `${dirpath}/cjs/${chunk}`,
esm: `${dirpath}/esm/${chunk}`,
});
writeExtraEntry(chunk.replace(/\..+$/, ''), {
cjs: `${dirpath}/cjs/${chunk}`,
esm: `${dirpath}/esm/${chunk}`,
});
});
},
}))(),
].filter(Boolean),
Expand Down
10 changes: 5 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
#!/usr/bin/env node
let shouldThrow;
try {
shouldThrow = require(`${process.cwd()}/package.json`).name
=== '@inthepocket/itp-react-scripts'
&& Number(process.version.slice(1).split('.')[0]) < 8;
shouldThrow =
require(`${process.cwd()}/package.json`).name === '@inthepocket/itp-react-scripts' &&
Number(process.version.slice(1).split('.')[0]) < 8;
} catch (error) {
// ignore
}

if (shouldThrow) {
throw new Error(
'You must use Node version 8 or greater to run the scripts within @inthepocket/itp-react-scripts '
+ 'because we dogfood the untranspiled version of the scripts.',
'You must use Node version 8 or greater to run the scripts within @inthepocket/itp-react-scripts ' +
'because we dogfood the untranspiled version of the scripts.',
);
}

Expand Down
Loading

0 comments on commit 28a1824

Please sign in to comment.