Skip to content

Commit

Permalink
fix(nuxt): reduce usage of cjs utilities (#27642)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe authored Jun 15, 2024
1 parent 44cada9 commit 2de885b
Show file tree
Hide file tree
Showing 13 changed files with 37 additions and 20 deletions.
5 changes: 4 additions & 1 deletion packages/kit/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,11 @@ export function normalizePlugin (plugin: NuxtPlugin | string): NuxtPlugin {
* Note: By default plugin is prepended to the plugins array. You can use second argument to append (push) instead.
* @example
* ```js
* import { createResolver } from '@nuxt/kit'
* const resolver = createResolver(import.meta.url)
*
* addPlugin({
* src: path.resolve(__dirname, 'templates/foo.js'),
* src: resolver.resolve('templates/foo.js'),
* filename: 'foo.server.js' // [optional] only include in server bundle
* })
* ```
Expand Down
1 change: 1 addition & 0 deletions packages/nuxt/src/core/nitro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,7 @@ export async function initNitro (nuxt: Nuxt & { _nitro?: Nitro }) {
nitroConfig.rollupConfig!.plugins!.push(
ImportProtectionPlugin.rollup({
rootDir: nuxt.options.rootDir,
modulesDir: nuxt.options.modulesDir,
patterns: nuxtImportProtections(nuxt, { isNitro: true }),
exclude: [/core[\\/]runtime[\\/]nitro[\\/]renderer/],
}),
Expand Down
1 change: 1 addition & 0 deletions packages/nuxt/src/core/nuxt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ async function initNuxt (nuxt: Nuxt) {
// Exclude top-level resolutions by plugins
exclude: [join(nuxt.options.srcDir, 'index.html')],
patterns: nuxtImportProtections(nuxt),
modulesDir: nuxt.options.modulesDir,
}
addVitePlugin(() => ImportProtectionPlugin.vite(config))
addWebpackPlugin(() => ImportProtectionPlugin.webpack(config))
Expand Down
8 changes: 4 additions & 4 deletions packages/nuxt/src/core/plugins/import-protection.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { createRequire } from 'node:module'
import { createUnplugin } from 'unplugin'
import { logger } from '@nuxt/kit'
import { resolvePath } from 'mlly'
import { isAbsolute, join, relative, resolve } from 'pathe'
import escapeRE from 'escape-string-regexp'
import type { NuxtOptions } from 'nuxt/schema'

const _require = createRequire(import.meta.url)

interface ImportProtectionOptions {
rootDir: string
modulesDir: string[]
patterns: [importPattern: string | RegExp, warning?: string][]
exclude?: Array<RegExp | string>
}
Expand Down Expand Up @@ -58,6 +57,7 @@ export const nuxtImportProtections = (nuxt: { options: NuxtOptions }, options: {
export const ImportProtectionPlugin = createUnplugin(function (options: ImportProtectionOptions) {
const cache: Record<string, Map<string | RegExp, boolean>> = {}
const importersToExclude = options?.exclude || []
const proxy = resolvePath('unenv/runtime/mock/proxy', { url: options.modulesDir })
return {
name: 'nuxt:import-protection',
enforce: 'pre',
Expand Down Expand Up @@ -85,7 +85,7 @@ export const ImportProtectionPlugin = createUnplugin(function (options: ImportPr
matched = true
}
if (matched) {
return _require.resolve('unenv/runtime/mock/proxy')
return proxy
}
return null
},
Expand Down
8 changes: 4 additions & 4 deletions packages/nuxt/test/auto-imports.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import { join } from 'pathe'
import { createCommonJS, findExports } from 'mlly'
import { findExports } from 'mlly'
import * as VueFunctions from 'vue'
import type { Import } from 'unimport'
import { createUnimport } from 'unimport'
Expand Down Expand Up @@ -59,8 +59,8 @@ const excludedNuxtHelpers = ['useHydration', 'useHead', 'useSeoMeta', 'useServer

describe('imports:nuxt', () => {
try {
const { __dirname } = createCommonJS(import.meta.url)
const entrypointContents = readFileSync(join(__dirname, '../src/app/composables/index.ts'), 'utf8')
const entrypointPath = fileURLToPath(new URL('../src/app/composables/index.ts', import.meta.url))
const entrypointContents = readFileSync(entrypointPath, 'utf8')

const names = findExports(entrypointContents).flatMap(i => i.names || i.name)
for (let name of names) {
Expand Down
2 changes: 2 additions & 0 deletions packages/nuxt/test/import-protection.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { fileURLToPath } from 'node:url'
import { normalize } from 'pathe'
import { describe, expect, it } from 'vitest'
import { ImportProtectionPlugin, nuxtImportProtections } from '../src/core/plugins/import-protection'
Expand Down Expand Up @@ -40,6 +41,7 @@ describe('import protection', () => {
const transformWithImportProtection = (id: string, importer: string) => {
const plugin = ImportProtectionPlugin.rollup({
rootDir: '/root',
modulesDir: [fileURLToPath(new URL('..', import.meta.url))],
patterns: nuxtImportProtections({
options: {
modules: ['some-nuxt-module'],
Expand Down
3 changes: 2 additions & 1 deletion packages/nuxt/test/scan-components.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { fileURLToPath } from 'node:url'
import { resolve } from 'pathe'
import { expect, it, vi } from 'vitest'
import type { ComponentsDir } from 'nuxt/schema'

import { scanComponents } from '../src/components/scan'

const fixtureDir = resolve(__dirname, 'fixture')
const fixtureDir = fileURLToPath(new URL('fixture', import.meta.url))
const rFixture = (...p: string[]) => resolve(fixtureDir, ...p)

vi.mock('@nuxt/kit', () => ({
Expand Down
4 changes: 2 additions & 2 deletions packages/nuxt/test/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { resolve } from 'pathe'
import { fileURLToPath } from 'node:url'

export const fixtureDir = resolve(__dirname, 'fixture')
export const fixtureDir = fileURLToPath(new URL('fixture', import.meta.url))

export function normalizeLineEndings (str: string, normalized = '\n') {
return str.replace(/\r?\n/g, normalized)
Expand Down
5 changes: 4 additions & 1 deletion packages/ui-templates/lib/dev.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { promises as fsp } from 'node:fs'
import type { Plugin } from 'vite'
import { template } from 'lodash-es'
import genericMessages from '../templates/messages.json'

const r = (...path: string[]) => resolve(join(__dirname, '..', ...path))
const templatesRoot = fileURLToPath(new URL('..', import.meta.url))

const r = (...path: string[]) => resolve(join(templatesRoot, ...path))

export const DevRenderingPlugin = () => {
return <Plugin>{
Expand Down
5 changes: 4 additions & 1 deletion packages/ui-templates/lib/prerender.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { promises as fsp } from 'node:fs'
import { globby } from 'globby'

const r = (...path: string[]) => resolve(join(__dirname, '..', ...path))
const templatesRoot = fileURLToPath(new URL('..', import.meta.url))

const r = (...path: string[]) => resolve(join(templatesRoot, ...path))

async function main () {
const templates = await globby(r('dist/templates/*.js'))
Expand Down
7 changes: 4 additions & 3 deletions packages/ui-templates/vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { fileURLToPath } from 'node:url'
import { join } from 'node:path'
import { resolve } from 'node:path'
import { readdirSync } from 'node:fs'

import { defineConfig } from 'vite'
Expand All @@ -8,7 +8,8 @@ import UnoCSS from 'unocss/vite'
import { DevRenderingPlugin } from './lib/dev'
import { RenderPlugin } from './lib/render'

const r = (...path: string[]) => fileURLToPath(new URL(join(...path), import.meta.url))
const rootDir = fileURLToPath(new URL('.', import.meta.url))
const r = (...path: string[]) => resolve(rootDir, ...path)

export default defineConfig({
build: {
Expand All @@ -32,7 +33,7 @@ export default defineConfig({
],
server: {
fs: {
allow: ['./templates', __dirname],
allow: ['./templates', rootDir],
},
},
})
1 change: 1 addition & 0 deletions packages/vite/src/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export function resolveCSSOptions (nuxt: Nuxt): ViteConfig['css'] {

for (const [name, opts] of plugins) {
if (opts) {
// TODO: remove use of requireModule in favour of ESM import
const plugin = requireModule(name, {
paths: [
...nuxt.options.modulesDir,
Expand Down
7 changes: 4 additions & 3 deletions packages/webpack/src/utils/postcss.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { fileURLToPath } from 'node:url'
import createResolver from 'postcss-import-resolver'
import { createCommonJS } from 'mlly'
import { requireModule } from '@nuxt/kit'
import type { Nuxt } from '@nuxt/schema'
import { defu } from 'defu'
Expand Down Expand Up @@ -61,9 +61,10 @@ export const getPostcssConfig = (nuxt: Nuxt) => {
// Keep the order of default plugins
if (!Array.isArray(postcssOptions.plugins) && isPureObject(postcssOptions.plugins)) {
// Map postcss plugins into instances on object mode once
const cjs = createCommonJS(import.meta.url)
const cwd = fileURLToPath(new URL('.', import.meta.url))
postcssOptions.plugins = sortPlugins(postcssOptions).map((pluginName: string) => {
const pluginFn = requireModule(pluginName, { paths: [cjs.__dirname] })
// TODO: remove use of requireModule in favour of ESM import
const pluginFn = requireModule(pluginName, { paths: [cwd] })
const pluginOptions = postcssOptions.plugins[pluginName]
if (!pluginOptions || typeof pluginFn !== 'function') { return null }
return pluginFn(pluginOptions)
Expand Down

0 comments on commit 2de885b

Please sign in to comment.