Skip to content

Commit

Permalink
add requireResolve option
Browse files Browse the repository at this point in the history
  • Loading branch information
vikr01 committed Oct 21, 2018
1 parent b4a2f11 commit 4773c69
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
27 changes: 27 additions & 0 deletions tests/src/rules/no-unresolved.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,15 @@ function runResolverTests(resolver) {
, options: [{ amd: true }]}),
rest({ code: 'define(["./does-not-exist"], function (bar) {})' }),

// requireResolve setting
rest({ code: 'var foo = require.resolve("./bar")'
, options: [{ requireResolve: true }]}),
rest({ code: 'require.resolve("./bar")'
, options: [{ requireResolve: true }]}),
rest({ code: 'require.resolve("./does-not-exist")'
, options: [{ requireResolve: false }]}),
rest({ code: 'require.resolve("./does-not-exist")' }),

// stress tests
rest({ code: 'require("./does-not-exist", "another arg")'
, options: [{ commonjs: true, amd: true }]}),
Expand Down Expand Up @@ -178,6 +187,24 @@ function runResolverTests(resolver) {
type: 'Literal',
}],
}),

// requireResolve setting
rest({
code: 'var bar = require.resolve("./baz")',
options: [{ requireResolve: true }],
errors: [{
message: "Unable to resolve path to module './baz'.",
type: 'Literal',
}],
}),
rest({
code: 'require.resolve("./baz")',
options: [{ requireResolve: true }],
errors: [{
message: "Unable to resolve path to module './baz'.",
type: 'Literal',
}],
}),
],
})

Expand Down
22 changes: 22 additions & 0 deletions utils/moduleVisitor.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,19 @@ exports.default = function visitModules(visitor, options) {
}
}

function checkRequireResolve(call) {
if (call.callee.type !== 'MemberExpression') return
if (call.callee.object.name !== 'require') return
if (call.callee.property.name !== 'resolve') return
if (call.arguments.length !== 1) return

const modulePath = call.arguments[0]
if (modulePath.type !== 'Literal') return
if (typeof modulePath.value !== 'string') return

checkSourceValue(modulePath, call)
}

const visitors = {}
if (options.esmodule) {
Object.assign(visitors, {
Expand All @@ -97,6 +110,14 @@ exports.default = function visitModules(visitor, options) {
}
}

if (options.requireResolve) {
const currentCallExpression = visitors['CallExpression']
visitors['CallExpression'] = function (call) {
if (currentCallExpression) currentCallExpression(call)
checkRequireResolve(call)
}
}

return visitors
}

Expand All @@ -111,6 +132,7 @@ function makeOptionsSchema(additionalProperties) {
'commonjs': { 'type': 'boolean' },
'amd': { 'type': 'boolean' },
'esmodule': { 'type': 'boolean' },
'requireResolve': { 'type': 'boolean' },
'ignore': {
'type': 'array',
'minItems': 1,
Expand Down

0 comments on commit 4773c69

Please sign in to comment.