Skip to content

Commit

Permalink
Add rule exports-last
Browse files Browse the repository at this point in the history
exports-last will check that all export statements are at the end of the file

Closes #620
  • Loading branch information
k15a committed Oct 19, 2016
1 parent 2cbd801 commit 7e00bb2
Show file tree
Hide file tree
Showing 3 changed files with 124 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ export const rules = {
'unambiguous': require('./rules/unambiguous'),
'no-unassigned-import': require('./rules/no-unassigned-import'),

// export
'exports-last': require('./rules/exports-last'),

// metadata-based
'no-deprecated': require('./rules/no-deprecated'),

Expand Down
39 changes: 39 additions & 0 deletions src/rules/exports-last.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
function isExportStatement({ type }) {
// ES Module export statements
if (type === 'ExportDefaultDeclaration' || type === 'ExportNamedDeclaration') {
return true

// CommonJS export statements
} else if (type === 'ExpressionStatement') {
// TODO
}

return false
}

const rule = {
create(context) {
return {
Program({ body }) {
const lastNonExportStatement = body.reduce((acc, node, index) => {
if (isExportStatement(node)) {
return acc
}
return index
}, 0)

body.forEach((node, index) => {
if (isExportStatement(node) && index < lastNonExportStatement) {

context.report({
node,
message: 'Export statements should appear at the end of the file',
})
}
})
},
}
},
}

export default rule
82 changes: 82 additions & 0 deletions tests/src/rules/exports-last.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { test } from '../utils'

import { RuleTester } from 'eslint'
import rule from 'rules/exports-last'

const ruleTester = new RuleTester()

const errors = ['Export statements should appear at the end of the file']

ruleTester.run('exports-last', rule, {
valid: [
test({
code: `
const foo = 'bar';
const bar = 'baz';
`,
}),
test({
code: `
const foo = 'bar';
export {foo};
`,
}),
test({
code: `
const foo = 'bar';
export default foo;
`,
}),
test({
code: `
const foo = 'bar';
export default foo;
export const bar = true;
`,
}),
// test({
// code: `
// const foo = 'bar';
// module.exports = foo
// `,
// }),
// test({
// code: `
// const foo = 'bar';
// module.exports = foo;
// exports.bar = true
// `,
// }),

],
invalid: [
test({
code: `
export default 'bar';
const bar = true;
`,
errors,
}),
test({
code: `
export const foo = 'bar';
const bar = true;
`,
errors,
}),
// test({
// code: `
// module.exports = 'bar';
// console.log('hi');
// `,
// errors,
// }),
// test({
// code: `
// exports.foo = 'bar';
// const bar = true;
// `,
// errors,
// }),
],
})

0 comments on commit 7e00bb2

Please sign in to comment.