Skip to content

Commit 942159b

Browse files
authored
Support webpack (#97)
Fix #96
1 parent 9bc31f2 commit 942159b

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

plugin.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,18 @@ function checkVersion (version, pluginName) {
5959
throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof version}'`)
6060
}
6161

62+
// TODO refactor this check and move it inside Fastify itself.
6263
var fastifyVersion
6364
try {
64-
const pkgPath = join(dirname(require.resolve('fastify', { paths: [require.main.filename] })), 'package.json')
65+
var pkgPath
66+
if (require.main.filename) {
67+
// We need to dynamically compute this to support yarn pnp
68+
pkgPath = join(dirname(require.resolve('fastify', { paths: [require.main.filename] })), 'package.json')
69+
} else {
70+
// In bundlers, there is no require.main.filename so we go ahead and require directly
71+
pkgPath = 'fastify/package.json'
72+
}
73+
6574
fastifyVersion = semver.coerce(require(pkgPath).version)
6675
} catch (_) {
6776
console.info('fastify not found, proceeding anyway')

test/bundlers.test.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
'use strict'
2+
3+
const { test } = require('tap')
4+
const fp = require('../plugin')
5+
6+
test('webpack removes require.main.filename', (t) => {
7+
const filename = require.main.filename
8+
const info = console.info
9+
t.tearDown(() => {
10+
require.main.filename = filename
11+
console.info = info
12+
})
13+
14+
require.main.filename = null
15+
16+
console.info = function (msg) {
17+
t.fail('logged: ' + msg)
18+
}
19+
20+
fp((fastify, opts, next) => {
21+
next()
22+
}, {
23+
fastify: '^3.0.0'
24+
})
25+
26+
t.end()
27+
})

0 commit comments

Comments
 (0)