Skip to content

Commit

Permalink
feat: resolve() across module systems.
Browse files Browse the repository at this point in the history
  • Loading branch information
knightedcodemonkey committed May 27, 2024
1 parent 4160583 commit ff94b15
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 4 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@knighted/specifier",
"version": "2.0.0-rc.0",
"version": "2.0.0-rc.1",
"description": "Node.js tool for updating your ES module and CommonJS specifiers.",
"type": "module",
"main": "dist",
Expand Down
22 changes: 21 additions & 1 deletion src/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,29 @@ const format = (
CallExpression({ node }: NodePath<CallExpression>) {
const { callee } = node

/**
* Check for:
*
* import()
* require()
* require.resolve()
* import.meta.resolve()
*
* Omitted:
* const require = createRequire(import.meta.url)
*/
if (
callee.type === 'Import' ||
(callee.type === 'Identifier' && callee.name === 'require')
(callee.type === 'Identifier' && callee.name === 'require') ||
(callee.type === 'MemberExpression' &&
callee.object.type === 'Identifier' &&
callee.object.name === 'require' &&
callee.property.type === 'Identifier' &&
callee.property.name === 'resolve') ||
(callee.type === 'MemberExpression' &&
callee.object.type === 'MetaProperty' &&
callee.property.type === 'Identifier' &&
callee.property.name === 'resolve')
) {
const source = node.arguments[0] as DynamicImportOrRequireArg
const { type, start, end, loc } = source
Expand Down
6 changes: 6 additions & 0 deletions test/__fixtures__/modules.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
require.resolve('./require/file.js')
import.meta.resolve('./meta/file.js')

const obj = {}
obj.resolve = function() {}
obj.resolve('./skip/file.js')
22 changes: 22 additions & 0 deletions test/updateAst.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,26 @@ describe('updateAst', () => {
assert.ok(code.indexOf('./ast-test.js') > -1)
}
})

it('updates resolve from different module types', async () => {
const source = (await readFile(join(fixtures, 'modules.js'))).toString()
const ast = parse(source)
const { code, error } = await updateAst(ast, source, ({ value }) => {
if (value === './require/file.js') {
return './require-test.js'
}

if (value === './meta/file.js') {
return './meta-test.js'
}
})

assert.equal(error, undefined)

if (code) {
assert.ok(code.indexOf('./require-test.js') > -1)
assert.ok(code.indexOf('./meta-test.js') > -1)
assert.ok(code.indexOf('./skip/file.js') > -1)
}
})
})

0 comments on commit ff94b15

Please sign in to comment.