Skip to content

Commit

Permalink
fix: upgrade deps and setup linting for klap
Browse files Browse the repository at this point in the history
  • Loading branch information
osdevisnot committed Aug 27, 2020
1 parent c50b724 commit 168c233
Show file tree
Hide file tree
Showing 9 changed files with 88 additions and 65 deletions.
4 changes: 2 additions & 2 deletions cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const defaultEnvironment = {
start: 'development',
}

;(async () => {
;(async (pkg) => {
switch (command) {
case 'init':
log(`${name}@${version} - Initializing your package...`)
Expand All @@ -23,7 +23,7 @@ const defaultEnvironment = {
case 'start':
log(`${name}@${version} - Working on ${command}...`)
process.env.NODE_ENV = process.env.NODE_ENV || defaultEnvironment[command]
const pkg = JSON.parse(await read(path.join(process.cwd(), 'package.json')))
pkg = JSON.parse(await read(path.join(process.cwd(), 'package.json')))
await klap(command, pkg)
break
case 'help':
Expand Down
22 changes: 16 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
"klap": "cli.js"
},
"files": [
"dist"
"dist",
"cli.js"
],
"scripts": {
"prebuild": "patch-package",
Expand All @@ -24,18 +25,26 @@
},
"husky": {
"hooks": {
"pre-commit": "pretty-quick --staged"
"pre-commit": "xo --fix"
}
},
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
},
"xo": {
"ignores": [
"examples"
],
"prettier": true
},
"prettier": {
"bracketSpacing": true,
"printWidth": 120,
"semi": false,
"singleQuote": true,
"trailingComma": "es5",
"useTabs": true
},
"devDependencies": {
Expand All @@ -47,14 +56,13 @@
"@babel/preset-env": "7.11.0",
"@babel/preset-react": "7.10.4",
"@babel/preset-typescript": "7.10.4",
"@osdevisnot/prettier": "6.0.0",
"@rollup/plugin-babel": "5.2.0",
"@rollup/plugin-commonjs": "15.0.0",
"@rollup/plugin-json": "4.1.0",
"@rollup/plugin-node-resolve": "9.0.0",
"@rollup/plugin-replace": "2.3.3",
"@rollup/pluginutils": "4.0.0",
"@types/node": "14.6.0",
"@types/node": "14.6.1",
"@zeit/ncc": "0.22.3",
"babel-plugin-codegen": "4.0.1",
"babel-plugin-dev-expression": "0.2.2",
Expand All @@ -71,13 +79,15 @@
"mkdirp": "1.0.4",
"patch-package": "6.2.2",
"pretty-bytes": "5.3.0",
"rollup": "2.26.5",
"rollup": "2.26.6",
"rollup-plugin-dts": "1.4.12",
"rollup-plugin-node-globals": "1.4.0",
"semantic-release": "17.1.1",
"servor": "4.0.2",
"sort-package-json": "1.44.0",
"terser": "5.2.1",
"typescript": "4.0.2"
"typescript": "4.0.2",
"xo": "0.33.0",
"xo-quick": "0.0.5"
}
}
15 changes: 8 additions & 7 deletions src/babel.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { DEFAULT_EXTENSIONS } from '@babel/core'

// babel presets
// Babel presets
import presetEnv from '@babel/preset-env'
import presetTs from '@babel/preset-typescript'
import presetReact from '@babel/preset-react'

// babel plugins
// Babel plugins
import pluginDevExpression from 'babel-plugin-dev-expression'
import pluginAsyncToPromise from 'babel-plugin-transform-async-to-promises'
import pluginDecorators from '@babel/plugin-proposal-decorators'
Expand All @@ -16,7 +16,8 @@ import pluginEmotion from 'babel-plugin-emotion'
import pluginMacros from 'babel-plugin-macros'
import pluginCodegen from 'babel-plugin-codegen'

let hasPackage = (pkg, name) =>
const hasPackage = (pkg, name) =>
// eslint-disable-next-line unicorn/no-reduce
['dependencies', 'devDependencies', 'peerDependencies'].reduce(
(last, current) => last || (pkg[current] && pkg[current][name]),
false
Expand All @@ -29,11 +30,11 @@ export const babelConfig = (command, pkg, options) => {
// Note: when using `React`, presetTs needs `React` as jsxPragma,
// vs presetReact needs `React.createElement`,
// but when using `h` as pragma, both presets needs it to be just `h`
let [jsxPragma, pragma, pragmaFrag] = hasPackage(pkg, 'react')
const [jsxPragma, pragma, pragmaFrag] = hasPackage(pkg, 'react')
? ['React', 'React.createElement', 'React.Fragment']
: ['h', 'h', 'h']

// new JSX Transform - https://github.com/reactjs/rfcs/blob/createlement-rfc/text/0000-create-element-changes.md
// New JSX Transform - https://github.com/reactjs/rfcs/blob/createlement-rfc/text/0000-create-element-changes.md
let reactPresetOptions = { runtime: 'classic', pragma, pragmaFrag }
if (runtime !== 'classic') {
reactPresetOptions = { runtime: 'automatic', importSource: runtime }
Expand All @@ -42,8 +43,8 @@ export const babelConfig = (command, pkg, options) => {
// Note: The styled component plugin effects the css prop, even if
// styled components are not being used in project. So, we enable
// this only when styled-components is a project dependency...
let useStyledComponents = hasPackage(pkg, 'styled-components')
let useEmotion = hasPackage(pkg, 'emotion')
const useStyledComponents = hasPackage(pkg, 'styled-components')
const useEmotion = hasPackage(pkg, 'emotion')

const presets = [
[
Expand Down
14 changes: 9 additions & 5 deletions src/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import merge from 'deepmerge'
import sort from 'sort-package-json'
import cli from '../package.json'
import { getDefaults, getTemplates } from './init-create'
import { error, info, log } from './logger'
import { error, info, warn } from './logger'
import { exec, exists, read, write, baseName } from './utils'

/**
Expand All @@ -17,6 +17,7 @@ const gitInfo = () => {
warn('Count not determine `repository` and `author` fields for `package.json`')
warn('Skipped generating `LICENSE` file')
}

return { user, email }
}

Expand All @@ -28,7 +29,7 @@ const writePackage = async (template, { user, email }) => {
const name = process.cwd().split('/').pop()
const source = `src/${name}.${template}`

if (await exists('./package.json')) {
if (exists('./package.json')) {
pkg = JSON.parse(await read('./package.json'))
}

Expand Down Expand Up @@ -62,10 +63,11 @@ const writePackage = async (template, { user, email }) => {
if (template === 'ts' || template === 'tsx') {
pkg = merge(pkg, {
types: `dist/${name}.d.ts`,
devDependencies: { typescript: cli.devDependencies['typescript'] },
devDependencies: { typescript: cli.devDependencies.typescript },
})
}
}

await write('./package.json', JSON.stringify(sort(pkg), null, ' '))
info('\t- wrote ./package.json')
return pkg
Expand All @@ -83,12 +85,14 @@ const writeFiles = async (pkg, template) => {
let existing = false
// If there's a range of possible extensions, check them all.
if (extensions) {
existing = (await Promise.all(extensions.map(async (ext) => await exists(baseName(file) + ext)))).includes(true)
// eslint-disable-next-line no-await-in-loop
existing = (await Promise.all(extensions.map(async (ext) => exists(baseName(file) + ext)))).includes(true)
} else {
existing = await exists(file)
existing = exists(file)
}

if (!existing) {
// eslint-disable-next-line no-await-in-loop
await write(file, content)
info(`\t- wrote ./${file}`)
}
Expand Down
39 changes: 24 additions & 15 deletions src/klap.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ const defaultOutputOptions = { esModule: false, strict: false, freeze: false }

const validateConfig = (inputOptions, outputOptions) => {
if (!inputOptions || inputOptions.length === 0 || (outputOptions && outputOptions.length === 0)) {
error('Error: Count not determine input and output options.')
error('Error: Could not determine input and output options.')
info('Are you running `klap` command in appropriate package directory ?')
process.exit(1)
throw new Error('Could not determine input and output options.')
}
}

Expand All @@ -22,7 +22,7 @@ const buildConfig = (command, pkg, options) => {
const { name, globals, source: input, main, module, browser, sourcemap } = options
const external = Object.keys({ ...dependencies, ...peerDependencies })

let inputOptions = [
const inputOptions = [
main && {
...defaultInputOptions,
external,
Expand All @@ -47,7 +47,7 @@ const buildConfig = (command, pkg, options) => {
},
].filter(Boolean)

let outputOptions = [
const outputOptions = [
main && { ...defaultOutputOptions, file: main, format: 'cjs', sourcemap },
module && { ...defaultOutputOptions, file: module, format: 'es', sourcemap },
browser && {
Expand All @@ -72,8 +72,9 @@ const buildConfig = (command, pkg, options) => {

const startConfig = async (command, pkg, options) => {
const { name, globals, example, source, module, browser, sourcemap, target } = options
const input = (await exists(example)) ? example : source
let inputOptions, outputOptions
const input = exists(example) ? example : source
let inputOptions
let outputOptions
if (target === 'es') {
inputOptions = {
...defaultInputOptions,
Expand Down Expand Up @@ -109,9 +110,11 @@ const startConfig = async (command, pkg, options) => {

const deleteDirs = async (options) => {
const dirs = {}
;['main', 'module', 'browser'].map(
(type) => options[type] && (dirs[dirname(options[type]) + '/' + basename(options[type], 'js') + '.{js,map}'] = true)
)
;['main', 'module', 'browser'].forEach((type) => {
if (options[type]) {
dirs[dirname(options[type]) + '/' + basename(options[type], 'js') + '.{js,map}'] = true
}
})
await del(Object.keys(dirs))
}

Expand All @@ -122,11 +125,11 @@ const writeBundle = async (bundle, outputOptions) => {

const build = async (options, inputOptions) => {
try {
let bundle = await rollup(inputOptions)
const bundle = await rollup(inputOptions)
await writeBundle(bundle, options)
} catch (err) {
error(err)
process.exit(1)
} catch (error_) {
error(error_)
throw new Error(error_)
}
}

Expand All @@ -138,17 +141,21 @@ const processWatcher = (event) => {
case 'END':
info(`${new Date().toLocaleTimeString('en-GB')} - Waiting for Changes...`)
break
default:
error('Unknown event code: ' + event.code)
}
}

const klap = async (command, pkg) => {
const options = getOptions(pkg, command)
await deleteDirs(options)
let config, watchOptions, watcher
let config
let watchOptions
let watcher
switch (command) {
case 'build':
config = buildConfig(command, pkg, options)
config.outputOptions.map((opts, index) => build(opts, config.inputOptions[index]))
config.outputOptions.map((options_, index) => build(options_, config.inputOptions[index]))
break
case 'watch':
config = buildConfig(command, pkg, options)
Expand All @@ -172,6 +179,8 @@ const klap = async (command, pkg) => {
config = await startConfig(command, pkg, options)
build(config.outputOptions, config.inputOptions)
break
default:
error('Unknown command :', command)
}
}

Expand Down
12 changes: 6 additions & 6 deletions src/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const getOptions = (pkg, command) => {
example = 'public/index.js',
runtime = 'classic',
} = klap
const opts = getopts(process.argv.slice(3), {
const options = getopts(process.argv.slice(3), {
boolean: ['sourcemap', 'minify'],
alias: {
name: 'n',
Expand All @@ -47,13 +47,13 @@ const getOptions = (pkg, command) => {
})

// If no specific target is given, build the standard outputs
if (!opts.main && !opts.module && !opts.browser) {
opts.main = main
opts.module = module
opts.browser = browser
if (!options.main && !options.module && !options.browser) {
options.main = main
options.module = module
options.browser = browser
}

return { ...opts, globals, runtime }
return { ...options, globals, runtime }
}

export { getOptions }
26 changes: 14 additions & 12 deletions src/packages/terser.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,22 +24,23 @@ export const terser = (options = {}) => {
resolve: false,
})

let opts = {
let options_ = {
toplevel: true,
mangle: { properties: { regex: '^_' } },
// eslint-disable-next-line camelcase
compress: { passes: 10, pure_getters: true },
}

// Read Project .terserrc if exists...
let rc = join(process.cwd(), '.terserrc'),
cache
const rc = join(process.cwd(), '.terserrc')
let cache

if (existsSync(rc)) {
cache = JSON.parse(readFileSync(rc, 'utf-8'))
opts = merge(opts, cache)
options_ = merge(options_, cache)
}

opts = merge(opts, options)
options_ = merge(options_, options)

return {
name: 'terser',
Expand All @@ -49,18 +50,19 @@ export const terser = (options = {}) => {

let result
try {
result = await transform(code, opts)
result = await transform(code, options_)
try {
if (cache && opts.nameCache) {
cache.nameCache = opts.nameCache
if (cache && options_.nameCache) {
cache.nameCache = options_.nameCache
writeFileSync(rc, JSON.stringify(cache, null, ' ') + '\n', 'utf-8')
}
} catch (e) {}
} catch (err) {
const { message, line, col: column } = err
} catch {}
} catch (error_) {
const { message, line, col: column } = error_
error(codeFrameColumns(code, { start: { line, column } }, { message }))
throw err
throw error_
}

return {
code: result.code,
map: result.map,
Expand Down
Loading

0 comments on commit 168c233

Please sign in to comment.