Skip to content

Commit

Permalink
fix: use ES Modules by default for config files
Browse files Browse the repository at this point in the history
BREAKING CHANGE:
drop ts-node, coffee and live script for config
  • Loading branch information
anthony-redFox committed Apr 30, 2024
1 parent 9884819 commit c1cb3ae
Show file tree
Hide file tree
Showing 17 changed files with 107 additions and 376 deletions.
3 changes: 0 additions & 3 deletions .codeclimate.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,12 @@
engines:
rubocop:
enabled: false
coffeelint:
enabled: true
eslint:
enabled: true
csslint:
enabled: true
ratings:
paths:
- "**.coffee"
- "**.js"
- "**.css"
exclude_paths:
Expand Down
1 change: 0 additions & 1 deletion .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ karma-integration-tests

TODO.md
CONTRIBUTING.md
Gruntfile.coffee
credentials
Karma.sublime-*

Expand Down
71 changes: 0 additions & 71 deletions config.tpl.coffee

This file was deleted.

38 changes: 5 additions & 33 deletions docs/config/01-configuration-file.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,12 @@ is by using the `karma init` command. This page lists all of the available confi
Note: Most of the framework adapters, reporters, preprocessors and launchers need to be loaded as [plugins].


The Karma configuration file can be written in JavaScript, CoffeeScript, or TypeScript and is loaded as a regular Node.js module.
The Karma configuration file can be written in JavaScript and is loaded as a regular Node.js module.

Unless provided as argument, the Karma CLI will look for a configuration file at

* `./karma.conf.js`
* `./karma.conf.coffee`
* `./karma.conf.ts`
* `./.config/karma.conf.js`
* `./.config/karma.conf.coffee`
* `./.config/karma.conf.ts`

in that order.

Expand All @@ -33,24 +29,15 @@ module.exports = function(config) {
};
```

```coffeescript
# karma.conf.coffee
module.exports = (config) ->
config.set
basePath: '../..'
frameworks: ['jasmine']
# ...
```

```typescript
// karma.conf.ts
module.exports = (config) => {
```javascript
// karma.conf.js
exports default function(config) {
config.set({
basePath: '../..',
frameworks: ['jasmine'],
//...
});
}
};
```

Alternatively, you can use an `async` function instead (since v6.3).
Expand All @@ -66,21 +53,6 @@ module.exports = async (config) => {
};
```


### Customized TypeScript Configuration
Under the hood Karma uses ts-node to transpile TypeScript to JavaScript. If the resolved `tsconfig.json` has `module` configured as `ES` formats. You might get errors like `SyntaxError: Unexpected token`. This is due that in Node `ES` module formats are not supported. To overcome this issue you need to configure ts-node to use `commonjs` module format.

Create a JavaScript configuration file that overrides the module format.
```javascript
// karma.conf.js
require('ts-node').register({
compilerOptions: {
module: 'commonjs'
}
});
require('./karma.conf.ts');
```

## File Patterns
All of the configuration options, which specify file paths, use the [minimatch][minimatch] library to facilitate flexible
but concise file expressions so you can easily list all of the files you want to include and exclude.
Expand Down
5 changes: 1 addition & 4 deletions docs/intro/02-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,12 @@ Press tab to list possible options.
Config file generated at "/Users/vojta/Code/karma/my.conf.js".
```

The configuration file can be written in CoffeeScript as well.
In fact, if you execute `karma init` with a `*.coffee` extension such as `karma init karma.conf.coffee`, it will generate a CoffeeScript file.

Of course, you can write the config file by hand or copy-paste it from another project ;-)

## Starting Karma
When starting Karma, the configuration file path can be passed in as the first argument.

By default, Karma will look for `karma.conf.js` or `karma.conf.coffee` in the current directory.
By default, Karma will look for `karma.conf.js` in the current directory.
```bash
# Start Karma using your configuration:
$ karma start my.conf.js
Expand Down
4 changes: 0 additions & 4 deletions lib/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,14 +102,10 @@ function processArgs (argv, options, fs, path) {
// default config file (if exists)
if (fs.existsSync('./karma.conf.js')) {
configFile = './karma.conf.js'
} else if (fs.existsSync('./karma.conf.coffee')) {
configFile = './karma.conf.coffee'
} else if (fs.existsSync('./karma.conf.ts')) {
configFile = './karma.conf.ts'
} else if (fs.existsSync('./.config/karma.conf.js')) {
configFile = './.config/karma.conf.js'
} else if (fs.existsSync('./.config/karma.conf.coffee')) {
configFile = './.config/karma.conf.coffee'
} else if (fs.existsSync('./.config/karma.conf.ts')) {
configFile = './.config/karma.conf.ts'
}
Expand Down
39 changes: 3 additions & 36 deletions lib/config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict'

const path = require('path')
const url = require('url')
const assert = require('assert')

const logger = require('./logger')
Expand All @@ -10,27 +11,6 @@ const constant = require('./constants')

const _ = require('lodash')

let COFFEE_SCRIPT_AVAILABLE = false
let LIVE_SCRIPT_AVAILABLE = false
let TYPE_SCRIPT_AVAILABLE = false

try {
require('coffeescript').register()
COFFEE_SCRIPT_AVAILABLE = true
} catch {}

// LiveScript is required here to enable config files written in LiveScript.
// It's not directly used in this file.
try {
require('LiveScript')
LIVE_SCRIPT_AVAILABLE = true
} catch {}

try {
require('ts-node')
TYPE_SCRIPT_AVAILABLE = true
} catch {}

class Pattern {
constructor (pattern, served, included, watched, nocache, type, isBinary, integrity) {
this.pattern = pattern
Expand Down Expand Up @@ -391,32 +371,19 @@ async function parseConfig (configFilePath, cliOptions = {}) {
throw new Error(args.join(' '))
}

let configModule
let configModule = () => {} // if no config file path is passed, we define a dummy config module.
if (configFilePath) {
try {
if (path.extname(configFilePath) === '.ts' && TYPE_SCRIPT_AVAILABLE) {
require('ts-node').register()
}
configModule = require(configFilePath)
configModule = await import(url.pathToFileURL(configFilePath))
if (typeof configModule === 'object' && typeof configModule.default !== 'undefined') {
configModule = configModule.default
}
} catch (e) {
const extension = path.extname(configFilePath)
if (extension === '.coffee' && !COFFEE_SCRIPT_AVAILABLE) {
log.error('You need to install CoffeeScript.\n npm install coffeescript --save-dev')
} else if (extension === '.ls' && !LIVE_SCRIPT_AVAILABLE) {
log.error('You need to install LiveScript.\n npm install LiveScript --save-dev')
} else if (extension === '.ts' && !TYPE_SCRIPT_AVAILABLE) {
log.error('You need to install TypeScript.\n npm install typescript ts-node --save-dev')
}
return fail('Error in config file!\n ' + e.stack || e)
}
if (!helper.isFunction(configModule)) {
return fail('Config file must export a function!\n' + CONFIG_SYNTAX_HELP)
}
} else {
configModule = () => {} // if no config file path is passed, we define a dummy config module.
}

const config = new Config()
Expand Down
16 changes: 2 additions & 14 deletions lib/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
const readline = require('readline')
const path = require('path')
const { globSync } = require('glob')
const { minimatch: mm } = require('minimatch')
const exec = require('child_process').exec

const helper = require('./helper')
Expand Down Expand Up @@ -115,7 +114,7 @@ var questions = [{
}, {
id: 'generateTestMain',
question: 'Do you wanna generate a bootstrap file for RequireJS?',
hint: 'This will generate test-main.js/coffee that configures RequireJS and starts the tests.',
hint: 'This will generate test-main.js that configures RequireJS and starts the tests.',
options: ['no', 'yes'],
boolean: true,
condition: (answers) => answers.requirejs
Expand Down Expand Up @@ -185,12 +184,6 @@ function processAnswers (answers, basePath, testMainFile) {
}
}

const allPatterns = answers.files.concat(answers.includedFiles || [])
if (allPatterns.some((pattern) => mm(pattern, '**/*.coffee'))) {
installPackage('karma-coffee-preprocessor')
processedAnswers.preprocessors['**/*.coffee'] = ['coffee']
}

return processedAnswers
}

Expand All @@ -217,17 +210,12 @@ exports.init = function (config) {
sm.process(questions, function (answers) {
const cwd = process.cwd()
const configFile = config.configFile || 'karma.conf.js'
const isCoffee = path.extname(configFile) === '.coffee'
const testMainFile = isCoffee ? 'test-main.coffee' : 'test-main.js'
const testMainFile = 'test-main.js'
const formatter = formatters.createForPath(configFile)
const processedAnswers = processAnswers(answers, getBasePath(configFile, cwd), testMainFile)
const configFilePath = path.resolve(cwd, configFile)
const testMainFilePath = path.resolve(cwd, testMainFile)

if (isCoffee) {
installPackage('coffeescript')
}

if (processedAnswers.generateTestMain) {
formatter.writeRequirejsConfigFile(testMainFilePath)
console.log(colorScheme.success(`RequireJS bootstrap file generated at "${testMainFilePath}".`))
Expand Down
38 changes: 0 additions & 38 deletions lib/init/formatters.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,45 +72,7 @@ class JavaScriptFormatter {
}
}

class CoffeeFormatter extends JavaScriptFormatter {
constructor () {
super()
this.TEMPLATE_FILE_PATH = getConfigPath('config.tpl.coffee')
this.REQUIREJS_TEMPLATE_FILE = getConfigPath('requirejs.config.tpl.coffee')
}
}

class LiveFormatter extends JavaScriptFormatter {
constructor () {
super()
this.TEMPLATE_FILE_PATH = getConfigPath('config.tpl.ls')
}
}

class TypeFormatter extends JavaScriptFormatter {
constructor () {
super()
this.TEMPLATE_FILE_PATH = getConfigPath('config.tpl.ts')
}
}

exports.JavaScript = JavaScriptFormatter
exports.Coffee = CoffeeFormatter
exports.Live = LiveFormatter
exports.Type = TypeFormatter

exports.createForPath = function (path) {
if (/\.coffee$/.test(path)) {
return new CoffeeFormatter()
}

if (/\.ls$/.test(path)) {
return new LiveFormatter()
}

if (/\.ts$/.test(path)) {
return new TypeFormatter()
}

return new JavaScriptFormatter()
}
22 changes: 0 additions & 22 deletions requirejs.config.tpl.coffee

This file was deleted.

Loading

0 comments on commit c1cb3ae

Please sign in to comment.