Skip to content

Commit

Permalink
feat: support ts(#584)
Browse files Browse the repository at this point in the history
- add support for TS lint
- add support for transpile TS to JS
- add support for TS testing browser, node and electron
  • Loading branch information
hugomrdias authored Jun 20, 2020
1 parent ff0ea7f commit 9dc23a3
Show file tree
Hide file tree
Showing 15 changed files with 157 additions and 33 deletions.
23 changes: 16 additions & 7 deletions cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ updateNotifier({
}).notify()

const cli = require('yargs')
const { config } = require('./src/config/user')
cli
.scriptName('aegir')
.env('AEGIR')
Expand All @@ -26,24 +27,32 @@ cli
.example('$0 test -t webworker -- --browsers Firefox', 'If the command supports `--` can be used to forward options to the underlying tool.')
.example('npm test -- -- --browsers Firefox', 'If `npm test` translates to `aegir test -t browser` and you want to forward options you need to use `-- --` instead.')
.epilog('Use `$0 <command> --help` to learn more about each command.')
.middleware((yargs) => {
yargs.config = config()
})
.commandDir('cmds')
.demandCommand(1, 'You need at least one command.')
.option('D', {
.help()
.alias('help', 'h')
.alias('version', 'v')
.option('debug', {
desc: 'Show debug output.',
type: 'boolean',
default: false,
alias: 'debug'
alias: 'd'
})
// TODO remove after webpack 5 upgrade
.options('node', {
type: 'boolean',
describe: 'Flag to control if bundler should inject node globals or built-ins.',
default: false
})
.help()
.alias('h', 'help')
.alias('v', 'version')
.group(['help', 'version', 'debug'], 'Global Options:')
.options('ts', {
type: 'boolean',
describe: 'Enable support for Typescript',
default: false
})
.group(['help', 'version', 'debug', 'node', 'ts'], 'Global Options:')
.demandCommand(1, 'You need at least one command.')
.wrap(cli.terminalWidth())
.parserConfiguration({ 'populate--': true })
.recommendCommands()
Expand Down
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@
"@babel/plugin-transform-regenerator": "^7.10.1",
"@babel/plugin-transform-runtime": "^7.10.1",
"@babel/preset-env": "^7.10.2",
"@babel/preset-typescript": "^7.10.1",
"@babel/register": "^7.10.1",
"@babel/runtime": "^7.10.2",
"@commitlint/cli": "^8.3.5",
"@commitlint/config-conventional": "^8.3.4",
Expand All @@ -55,6 +57,8 @@
"@commitlint/travis-cli": "^8.3.5",
"@electron/get": "^1.10.0",
"@polka/send-type": "^0.5.2",
"@typescript-eslint/eslint-plugin": "^3.3.0",
"@typescript-eslint/parser": "^3.3.0",
"babel-loader": "^8.0.5",
"buffer": "^5.6.0",
"bytes": "^3.1.0",
Expand All @@ -67,6 +71,7 @@
"conventional-changelog": "^3.1.18",
"conventional-github-releaser": "^3.1.3",
"cors": "^2.8.5",
"cosmiconfig": "^6.0.0",
"dependency-check": "^4.1.0",
"dirty-chai": "^2.0.1",
"documentation": "^13.0.1",
Expand Down Expand Up @@ -114,6 +119,7 @@
"semver": "^7.3.2",
"simple-git": "^2.7.0",
"terser-webpack-plugin": "^3.0.5",
"typescript": "^3.9.5",
"update-notifier": "^4.0.0",
"webpack": "^4.43.0",
"webpack-bundle-analyzer": "^3.7.0",
Expand Down
14 changes: 13 additions & 1 deletion src/build/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,25 @@ module.exports = async (argv) => {
env: {
NODE_ENV: process.env.NODE_ENV || 'production',
AEGIR_BUILD_ANALYZE: argv.bundlesize,
AEGIR_NODE: argv.node
AEGIR_NODE: argv.node,
AEGIR_TS: argv.ts
},
localDir: path.join(__dirname, '../..'),
preferLocal: true,
stdio: 'inherit'
})

if (argv.ts) {
await execa('tsc', [
'--outDir', './dist/src',
'--declaration'
], {
localDir: path.join(__dirname, '../..'),
preferLocal: true,
stdio: 'inherit'
})
}

if (argv.bundlesize) {
const stats = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'dist/stats.json')))
const gzip = await gzipSize(path.join(stats.outputPath, stats.assets[0].name))
Expand Down
9 changes: 8 additions & 1 deletion src/config/babelrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ module.exports = function (opts = {}) {
const isEnvDevelopment = env === 'development'
const isEnvProduction = env === 'production'
const isEnvTest = env === 'test'
const isTSEnable = process.env.AEGIR_TS === 'true'
const targets = { browsers: pkg.browserslist || browserslist }

if (!isEnvDevelopment && !isEnvProduction && !isEnvTest) {
throw new Error(
'Using `babel-preset-env` requires that you specify `NODE_ENV` or ' +
Expand All @@ -29,9 +29,16 @@ module.exports = function (opts = {}) {
bugfixes: true,
targets
}
],
isTSEnable && [
'@babel/preset-typescript',
{
allowNamespaces: true
}
]
].filter(Boolean),
plugins: [
'@babel/plugin-proposal-class-properties',
[
require('@babel/plugin-transform-runtime').default,
{
Expand Down
13 changes: 13 additions & 0 deletions src/config/eslintrc-ts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
'use strict'
const { fromAegir } = require('../utils')
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
sourceType: 'module'
},
plugins: ['@typescript-eslint'],
extends: [
fromAegir('src/config/eslintrc.js'),
'plugin:@typescript-eslint/recommended'
]
}
3 changes: 2 additions & 1 deletion src/config/eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ module.exports = {
sourceType: 'script'
},
globals: {
self: true
self: true,
mocha: true
},
plugins: [
'no-only-tests'
Expand Down
7 changes: 6 additions & 1 deletion src/config/karma-entry.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
'use strict'
/* eslint-disable */
const testsContext = require.context(TEST_DIR, true, /\.spec\.js$/)
let testsContext
if (TS_ENABLED) {
testsContext = require.context(TEST_DIR, true, /\.spec\.ts$/)
} else {
testsContext = require.context(TEST_DIR, true, /\.spec\.js$/)
}

if (TEST_BROWSER_JS) {
require(TEST_BROWSER_JS)
Expand Down
29 changes: 25 additions & 4 deletions src/config/karma.conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@ const webpack = require('webpack')
const webpackConfig = require('./webpack.config')
const { fromRoot, hasFile } = require('../utils')
const userConfig = require('./user')()

const isTSEnable = process.env.AEGIR_TS === 'true'
const isWebworker = process.env.AEGIR_RUNNER === 'webworker'

// Env to pass in the bundle with DefinePlugin
const env = {
TS_ENABLED: process.env.AEGIR_TS,
'process.env': JSON.stringify(process.env),
TEST_DIR: JSON.stringify(fromRoot('test')),
TEST_BROWSER_JS: hasFile('test', 'browser.js')
? JSON.stringify(fromRoot('test', 'browser.js'))
TEST_BROWSER_JS: hasFile('test', isTSEnable ? 'browser.ts' : 'browser.js')
? JSON.stringify(fromRoot('test', isTSEnable ? 'browser.ts' : 'browser.js'))
: JSON.stringify('')
}

Expand All @@ -25,7 +26,27 @@ const karmaWebpackConfig = merge.strategy({ plugins: 'replace' })(webpackConfig(
},
plugins: [
new webpack.DefinePlugin(env)
]
],
module: {
rules: [
{
oneOf: [
{
test: /\.(js|ts)$/,
include: fromRoot('test'),
use: {
loader: require.resolve('babel-loader'),
options: {
presets: [require('./babelrc')()],
babelrc: false,
cacheDirectory: true
}
}
}
]
}
]
}
})

const karmaConfig = (config, argv) => {
Expand Down
7 changes: 7 additions & 0 deletions src/config/register.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
'use strict'
const { fromAegir } = require('./../utils')

require('@babel/register')({
extensions: ['.ts'],
presets: [fromAegir('src/config/babelrc.js')]
})
28 changes: 28 additions & 0 deletions src/config/user.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use strict'

const { cosmiconfigSync } = require('cosmiconfig')
const merge = require('merge-options')
const utils = require('../utils')

Expand Down Expand Up @@ -49,4 +50,31 @@ function userConfig () {
return user
}

const config = () => {
let cosmiconfig
try {
const configExplorer = cosmiconfigSync('aegir', {
searchPlaces: ['package.json', '.aegir.js']
})
const { config } = configExplorer.search()
cosmiconfig = config || {}
} catch (err) {
cosmiconfig = {}
}
const conf = merge({
webpack: {},
karma: {},
hooks: {},
entry: utils.fromRoot('src', 'index.js'),
bundlesize: {
path: './dist/index.min.js',
maxSize: '100kB'
}
},
cosmiconfig)

return conf
}

module.exports = userConfig
userConfig.config = config
6 changes: 4 additions & 2 deletions src/config/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const TerserPlugin = require('terser-webpack-plugin')
const { fromRoot, pkg, paths, getLibraryName } = require('../utils')
const userConfig = require('./user')()
const isProduction = process.env.NODE_ENV === 'production'
const isTSEnable = process.env.AEGIR_TS === 'true'

const base = (env, argv) => {
const filename = [
Expand All @@ -21,7 +22,7 @@ const base = (env, argv) => {
return {
bail: Boolean(isProduction),
mode: isProduction ? 'production' : 'development',
entry: [userConfig.entry],
entry: [isTSEnable ? fromRoot('src', 'index.ts') : fromRoot('src', 'index.js')],
output: {
path: fromRoot(paths.dist),
filename: filename,
Expand All @@ -35,7 +36,7 @@ const base = (env, argv) => {
{
oneOf: [
{
test: /\.js$/,
test: /\.(js|ts)$/,
include: fromRoot(paths.src),
use: {
loader: require.resolve('babel-loader'),
Expand Down Expand Up @@ -64,6 +65,7 @@ const base = (env, argv) => {
]
},
resolve: {
extensions: ['.wasm', '.mjs', '.js', '.json', '.ts', '.d.ts'],
alias: {
'@babel/runtime': path.dirname(
require.resolve('@babel/runtime/package.json')
Expand Down
19 changes: 10 additions & 9 deletions src/lint.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,16 @@ const userConfig = require('./config/user')
const formatter = CLIEngine.getFormatter()

const FILES = [
'*.js',
'*.{js,ts}',
'bin/**',
'config/**/*.js',
'test/**/*.js',
'src/**/*.js',
'tasks/**/*.js',
'benchmarks/**/*.js',
'utils/**/*.js',
'!**/node_modules/**'
'config/**/*.{js,ts}',
'test/**/*.{js,ts}',
'src/**/*.{js,ts}',
'tasks/**/*.{js,ts}',
'benchmarks/**/*.{js,ts}',
'utils/**/*.{js,ts}',
'!**/node_modules/**',
'!**/*.d.ts'
]

function checkDependencyVersions () {
Expand Down Expand Up @@ -82,7 +83,7 @@ function checkDependencyVersions () {
function runLinter (opts = {}) {
const cli = new CLIEngine({
useEslintrc: true,
baseConfig: require('./config/eslintrc.js'),
baseConfig: opts.ts ? require('./config/eslintrc-ts.js') : require('./config/eslintrc.js'),
fix: opts.fix
})

Expand Down
1 change: 1 addition & 0 deletions src/test/browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ module.exports = (argv, execaOptions) => {
NODE_ENV: process.env.NODE_ENV || 'test',
AEGIR_RUNNER: argv.webworker ? 'webworker' : 'browser',
AEGIR_NODE: argv.node,
AEGIR_TS: argv.ts,
IS_WEBPACK_BUILD: true,
...hook.env
},
Expand Down
7 changes: 5 additions & 2 deletions src/test/electron.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
'use strict'
const path = require('path')
const execa = require('execa')
const { hook, getElectron } = require('../utils')
const { hook, getElectron, fromAegir } = require('../utils')

module.exports = (argv) => {
const input = argv._.slice(1)
const forwardOptions = argv['--'] ? argv['--'] : []
const watch = argv.watch ? ['--watch'] : []
const files = argv.files.length ? [...argv.files] : ['test/**/*.spec.js']
const files = argv.files.length ? [...argv.files] : ['test/**/*.spec.{js,ts}']
const verbose = argv.verbose ? ['--log-level', 'debug'] : ['--log-level', 'error']
const grep = argv.grep ? ['--grep', argv.grep] : []
const progress = argv.progress ? ['--reporter=progress'] : []
const bail = argv.bail ? ['--bail', argv.bail] : []
const timeout = argv.timeout ? ['--timeout', argv.bail] : []
const renderer = argv.renderer ? ['--renderer'] : []
const ts = argv.ts ? ['--require', fromAegir('src/config/register.js')] : []

return hook('browser', 'pre')(argv.userConfig)
.then((hook = {}) => Promise.all([hook, getElectron()]))
Expand All @@ -27,6 +28,7 @@ module.exports = (argv) => {
...progress,
...bail,
...timeout,
...ts,
['--colors'],
['--full-trace'],
...renderer,
Expand All @@ -39,6 +41,7 @@ module.exports = (argv) => {
NODE_ENV: process.env.NODE_ENV || 'test',
AEGIR_RUNNER: argv.renderer ? 'electron-renderer' : 'electron-main',
ELECTRON_PATH: electronPath,
AEGIR_TS: argv.ts,
...hook.env
}
})
Expand Down
Loading

0 comments on commit 9dc23a3

Please sign in to comment.