Just namespace it:
const detachedG = d3.create('svg:g');
Here is the code with that change:
<!doctype html>
<html lang="en">
<head><script src="https://d3js.org/d3.v5.min.js"></script></head>
<body>
<svg></svg>
<script>
const svg = d3.select('svg');
const g = svg.append('g');
const detachedG = d3.create('svg:g');
detachedG.selectAll('g')
.data([5,10,20,40])
.enter()
.append('rect')
.attr('fill', 'green')
.attr('x', d => d)
.attr('y', d => d)
.attr('height', d => d)
.attr('width', d => d);
g.append(() => detachedG.node());
</script>
</body>
</html>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…