Skip to content

Commit

Permalink
Merge pull request #172 from codfish/eslint-changes
Browse files Browse the repository at this point in the history
Eslint changes
  • Loading branch information
codfish authored Feb 26, 2021
2 parents ad5065a + 81bd3f9 commit 4f72bf9
Show file tree
Hide file tree
Showing 19 changed files with 250 additions and 80 deletions.
5 changes: 4 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,8 @@ const { jest: jestConfig } = require('./src/config');

module.exports = Object.assign(jestConfig, {
coverageThreshold: null,
testPathIgnorePatterns: [...jestConfig.testPathIgnorePatterns, './src/scripts/test.js'],
testPathIgnorePatterns: [
...jestConfig.testPathIgnorePatterns,
'./src/scripts/test.js',
],
});
15 changes: 14 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -102,13 +102,26 @@
"no-console": "off",
"no-process-exit": "off",
"global-require": "off",
"no-prototype-builtins": "off",
"no-useless-catch": "off",
"import/no-dynamic-require": "off",
"import/no-unassigned-import": "off",
"no-nested-ternary": "off",
"no-use-before-define": "off",
"no-restricted-syntax": "off",
"no-param-reassign": "off"
"no-param-reassign": "off",
"max-len": [
"error",
80,
2,
{
"ignoreUrls": true,
"ignoreComments": true,
"ignoreRegExpLiterals": true,
"ignoreStrings": true,
"ignoreTemplateLiterals": true
}
]
}
},
"commitlint": {
Expand Down
4 changes: 3 additions & 1 deletion src/__tests__/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,9 @@ 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
43 changes: 35 additions & 8 deletions src/config/babelrc.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
const browserslist = require('browserslist');
const semver = require('semver');

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

const { BABEL_ENV, NODE_ENV, BUILD_FORMAT } = process.env;
const isTest = (BABEL_ENV || NODE_ENV) === 'test';
Expand All @@ -13,7 +20,9 @@ const isWebpack = parseEnv('BUILD_WEBPACK', false);
const treeshake = parseEnv('BUILD_TREESHAKE', isRollup || isWebpack);
const alias = parseEnv('BUILD_ALIAS', isPreact ? { react: 'preact' } : null);

const hasBabelRuntimeDep = Boolean(pkg.dependencies && pkg.dependencies['@babel/runtime']);
const hasBabelRuntimeDep = Boolean(
pkg.dependencies && pkg.dependencies['@babel/runtime'],
);
const RUNTIME_HELPERS_WARN =
'You should add @babel/runtime as dependency to your package. It will allow reusing "babel helpers" from node_modules rather than bundling their copies into your files.';

Expand Down Expand Up @@ -44,7 +53,10 @@ function getNodeVersion({ engines: { node: nodeVersion = '10.13' } = {} }) {
*
* @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' }
Expand All @@ -66,16 +78,31 @@ module.exports = () => ({
ifTypescript([require.resolve('@babel/preset-typescript')]),
].filter(Boolean),
plugins: [
[require.resolve('@babel/plugin-transform-runtime'), { useESModules: treeshake && !isCJS }],
[
require.resolve('@babel/plugin-transform-runtime'),
{ useESModules: treeshake && !isCJS },
],
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' },
],
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),
});
11 changes: 10 additions & 1 deletion src/config/eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
const prettierConfig = require('./prettierrc');
const { hasLocalConfig } = require('../utils');

const args = process.argv.slice(2);

const useBuiltinConfig =
!args.includes('--config') && !hasLocalConfig('prettier');
const ruleValue = useBuiltinConfig ? ['error', prettierConfig] : 'error';

module.exports = {
extends: [require.resolve('eslint-config-codfish')].filter(Boolean),
rules: {
'prettier/prettier': ['error', prettierConfig],
// Explicitly set prettier rules to use our built in config if no
// local prettier config is found.
'prettier/prettier': ruleValue,
},
};
21 changes: 17 additions & 4 deletions src/config/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,17 @@ const jestConfig = {
testEnvironment: ifAnyDep(['webpack', 'rollup', 'react'], 'jsdom', 'node'),
testURL: 'http://localhost',
moduleFileExtensions: ['js', 'jsx', 'json', 'ts', 'tsx'],
moduleDirectories: ['node_modules', fromRoot('src'), 'shared', fromRoot('tests')],
moduleDirectories: [
'node_modules',
fromRoot('src'),
'shared',
fromRoot('tests'),
],
collectCoverageFrom: ['src/**/*.+(js|jsx|ts|tsx)'],
testMatch: ['**/__tests__/**/*.+(js|jsx|ts|tsx)', '**/?(*.)+(spec|test).[jt]s?(x)'],
testMatch: [
'**/__tests__/**/*.+(js|jsx|ts|tsx)',
'**/?(*.)+(spec|test).[jt]s?(x)',
],
testPathIgnorePatterns: [...ignores],
coveragePathIgnorePatterns: [...ignores, 'src/(umd|cjs|esm)-entry.js$'],
transformIgnorePatterns: ['[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$'],
Expand All @@ -41,7 +49,10 @@ const jestConfig = {
};

const setupFilesAfterEnv = [
ifAnyDep('@testing-library/jest-dom', '@testing-library/jest-dom/extend-expect'),
ifAnyDep(
'@testing-library/jest-dom',
'@testing-library/jest-dom/extend-expect',
),
ifFile('jest.setup.js', fromRoot('jest.setup.js')),
ifFile('setupTests.js', fromRoot('setupTests.js')),
ifFile('setupTests.js', fromRoot('setupTests.js')),
Expand All @@ -55,7 +66,9 @@ if (setupFilesAfterEnv.length) {
}

if (useBuiltInBabelConfig) {
jestConfig.transform = { '^.+\\.(js|jsx|ts|tsx)$': here('./babel-transform') };
jestConfig.transform = {
'^.+\\.(js|jsx|ts|tsx)$': here('./babel-transform'),
};
}

if (jestConfig.testEnvironment === 'jsdom') {
Expand Down
5 changes: 4 additions & 1 deletion src/config/lintstagedrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,8 @@ module.exports = {
'*.+(json|yml|yaml|css|less|scss|ts|tsx|md|graphql|mdx|vue)': [
`${codScripts} format --no-eslint`,
].filter(Boolean),
'*.js': [`${codScripts} lint --fix`, `${codScripts} test --findRelatedTests`].filter(Boolean),
'*.js': [
`${codScripts} lint --fix`,
`${codScripts} test --findRelatedTests`,
].filter(Boolean),
};
68 changes: 44 additions & 24 deletions src/config/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ const path = require('path');
const { babel: rollupBabel } = require('@rollup/plugin-babel');
const commonjs = require('@rollup/plugin-commonjs');
const json = require('@rollup/plugin-json');
const { DEFAULTS: nodeResolveDefaults, nodeResolve } = require('@rollup/plugin-node-resolve');
const {
DEFAULTS: nodeResolveDefaults,
nodeResolve,
} = require('@rollup/plugin-node-resolve');

const replace = require('@rollup/plugin-replace');
const glob = require('glob');
Expand Down Expand Up @@ -37,33 +40,45 @@ const useSizeSnapshot = parseEnv('BUILD_SIZE_SNAPSHOT', false);
const esm = format === 'esm';
const umd = format === 'umd';

const defaultGlobals = Object.keys(pkg.peerDependencies || {}).reduce((deps, dep) => {
// eslint-disable-next-line no-param-reassign
deps[dep] = capitalize(camelcase(dep));
return deps;
}, {});
const defaultGlobals = Object.keys(pkg.peerDependencies || {}).reduce(
(deps, dep) => {
// eslint-disable-next-line no-param-reassign
deps[dep] = capitalize(camelcase(dep));
return deps;
},
{},
);

const deps = Object.keys(pkg.dependencies || {});
const peerDeps = Object.keys(pkg.peerDependencies || {});
const defaultExternal = umd ? peerDeps : deps.concat(peerDeps);

const input = glob.sync(
fromRoot(process.env.BUILD_INPUT || (hasTypescript ? 'src/index.{js,ts,tsx}' : 'src/index.js')),
fromRoot(
process.env.BUILD_INPUT ||
(hasTypescript ? 'src/index.{js,ts,tsx}' : '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}.`,
);
}

const filenameSuffix = process.env.BUILD_FILENAME_SUFFIX || '';
const filenamePrefix = process.env.BUILD_FILENAME_PREFIX || (isPreact ? 'preact/' : '');
const filenamePrefix =
process.env.BUILD_FILENAME_PREFIX || (isPreact ? 'preact/' : '');
const globals = parseEnv(
'BUILD_GLOBALS',
isPreact ? Object.assign(defaultGlobals, { preact: 'preact' }) : defaultGlobals,
isPreact
? Object.assign(defaultGlobals, { preact: 'preact' })
: defaultGlobals,
);
const external = parseEnv(
'BUILD_EXTERNAL',
Expand Down Expand Up @@ -91,7 +106,13 @@ function externalPredicate(id) {
return isDep || (!isRelative && !path.isAbsolute(id)) || isNodeModule;
}

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 @@ -116,19 +137,18 @@ const useBuiltinConfig =
!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;
}, {});

const extensions = hasTypescript
? [...nodeResolveDefaults.extensions, '.ts', '.tsx']
Expand Down
3 changes: 2 additions & 1 deletion src/run-script.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ function attemptResolve(...resolveArgs) {
}

function spawnScript() {
// get all the arguments of the script and find the position of our script commands
// get all the arguments of the script and find the position of our script
// commands
const args = process.argv.slice(2);
const scriptIndex = args.findIndex(x =>
[
Expand Down
13 changes: 11 additions & 2 deletions src/scripts/build/babel.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ const useBuiltinConfig =
!hasFile('.babelrc.js') &&
!hasFile('babel.config.js') &&
!hasPkgProp('babel');
const config = useBuiltinConfig ? ['--presets', here('../../config/babelrc.js')] : [];
const config = useBuiltinConfig
? ['--presets', here('../../config/babelrc.js')]
: [];

const extensions =
args.includes('--extensions') || args.includes('--x')
Expand All @@ -50,7 +52,14 @@ if (!useSpecifiedOutDir && !args.includes('--no-clean')) {
function go() {
let result = spawn.sync(
resolveBin('@babel/cli', { executable: 'babel' }),
[...outDir, ...copyFiles, ...ignore, ...extensions, ...config, 'src'].concat(args),
[
...outDir,
...copyFiles,
...ignore,
...extensions,
...config,
'src',
].concat(args),
{ stdio: 'inherit' },
);
if (result.status !== 0) return result.status;
Expand Down
16 changes: 12 additions & 4 deletions src/scripts/build/rollup.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,18 @@ const here = p => path.join(__dirname, p);
const hereRelative = p => here(p).replace(process.cwd(), '.');
const parsedArgs = yargsParser(args);

const useBuiltinConfig = !args.includes('--config') && !hasFile('rollup.config.js');
const useBuiltinConfig =
!args.includes('--config') && !hasFile('rollup.config.js');
// eslint-disable-next-line
const config = useBuiltinConfig
? `--config ${hereRelative('../../config/rollup.config.js')}`
: args.includes('--config')
? ''
: '--config'; // --config will pick up the rollup.config.js file

const environment = parsedArgs.environment ? `--environment ${parsedArgs.environment}` : '';
const environment = parsedArgs.environment
? `--environment ${parsedArgs.environment}`
: '';
const watch = parsedArgs.watch ? '--watch' : '';
const sizeSnapshot = parsedArgs['size-snapshot'];

Expand All @@ -47,7 +50,9 @@ const getCommand = (env, ...flags) =>
.join(' ');

const buildPreact = args.includes('--p-react');
const scripts = getConcurrentlyArgs(buildPreact ? getPReactCommands() : getCommands());
const scripts = getConcurrentlyArgs(
buildPreact ? getPReactCommands() : getCommands(),
);

const cleanBuildDirs = !args.includes('--no-clean');

Expand Down Expand Up @@ -86,7 +91,10 @@ function go() {
const [formatFile] = glob.sync(fromRoot(`dist/*.${format}.js`));
const { name } = path.parse(formatFile);
// make a .d.ts file for every generated file that re-exports index.d.ts
fs.writeFileSync(fromRoot('dist', `${name}.d.ts`), 'export * from ".";\n');
fs.writeFileSync(
fromRoot('dist', `${name}.d.ts`),
'export * from ".";\n',
);
}

// because typescript generates type defs for ignored files, we need to
Expand Down
Loading

0 comments on commit 4f72bf9

Please sign in to comment.