Skip to content

Commit 6bf210c

Browse files
committed
feat: support import.meta.* for webpack
1 parent 1166be4 commit 6bf210c

File tree

3 files changed

+51
-3
lines changed

3 files changed

+51
-3
lines changed

packages/bridge/src/module.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { defineNuxtModule, installModule, checkNuxtCompatibility, logger, writeTypes, addTemplate } from '@nuxt/kit'
1+
import { defineNuxtModule, installModule, checkNuxtCompatibility, logger, writeTypes, addTemplate, addWebpackPlugin } from '@nuxt/kit'
22
import type { NuxtModule, NuxtCompatibility } from '@nuxt/schema'
33
import type { NodeMiddleware } from 'h3'
44
import { fromNodeMiddleware } from 'h3'
@@ -13,6 +13,7 @@ import { setupMeta } from './meta'
1313
import { setupTranspile } from './transpile'
1414
import { generateWebpackBuildManifest } from './webpack/manifest'
1515
import pageMetaModule from './page-meta/module'
16+
import { ImportMetaPlugin } from './webpack/import-meta'
1617

1718
export default defineNuxtModule({
1819
meta: {
@@ -173,5 +174,7 @@ export default defineNuxtModule({
173174
getContents: () => 'export default false'
174175
})
175176
}
177+
178+
addWebpackPlugin(ImportMetaPlugin.webpack)
176179
}
177180
})
+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { pathToFileURL } from 'node:url'
2+
import { createUnplugin } from 'unplugin'
3+
import { parseURL } from 'ufo'
4+
import { normalize } from 'pathe'
5+
import MagicString from 'magic-string'
6+
7+
const NODE_MODULES_RE = /[\\/]node_modules[\\/]/
8+
9+
// polyfill for using `import.meta` in webpack 4
10+
export const ImportMetaPlugin = createUnplugin(() => {
11+
return {
12+
name: 'nuxt:import-meta-transform',
13+
enforce: 'post',
14+
transformInclude (id) {
15+
const { pathname } = parseURL(
16+
decodeURIComponent(pathToFileURL(id).href)
17+
)
18+
if (pathname.endsWith('.js') || pathname.endsWith('.vue')) {
19+
return true
20+
}
21+
},
22+
transform (code, id) {
23+
id = normalize(id)
24+
const isNodeModule = NODE_MODULES_RE.test(id)
25+
26+
if (isNodeModule) {
27+
return
28+
}
29+
30+
const s = new MagicString(code)
31+
s.replace(/import\.meta\.client/g, 'process.client')
32+
.replace(/import\.meta\.server/g, 'process.server')
33+
.replace(/import\.meta\.browser/g, 'process.browser')
34+
.replace(/import\.meta\.nitro/g, 'process.nitro')
35+
.replace(/import\.meta\.prerender/g, 'process.prerender')
36+
37+
if (s.hasChanged()) {
38+
return {
39+
code: s.toString(),
40+
map: s.generateMap({ hires: true })
41+
}
42+
}
43+
}
44+
}
45+
})

playground/pages/with-layout.vue

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
<script setup>
22
let message
3-
if (process.client) {
3+
if (import.meta.client) {
44
message = 'Client'
5-
} else if (process.server) {
5+
} else if (import.meta.server) {
66
message = 'Server'
77
}
88

0 commit comments

Comments
 (0)