Skip to content

Commit 472385e

Browse files
authored
feat(config): warn on named imports from JSON modules (#23378)
1 parent 238ad81 commit 472385e

10 files changed

Lines changed: 124 additions & 8 deletions

File tree

‎.gitignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ node_modules
1515
!**/glob-import/root/dir/node_modules
1616
!**/fixtures/glob-exports/node_modules
1717
!**/fixtures/glob-exports/node_modules/my-pkg/dist
18+
!**/fixtures/config/native-compat/json-named-import-bare/node_modules
19+
!**/fixtures/config/native-compat/json-named-import-ok/node_modules
1820
playground-temp
1921
temp
2022
TODOs.md

‎packages/vite/src/node/__tests__/config.spec.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1728,6 +1728,32 @@ describe('loadConfigFromFile', () => {
17281728
expect(await loadWithWarnings('json-ok')).toHaveLength(0)
17291729
})
17301730

1731+
test('warns on named import from JSON module', async () => {
1732+
const messages = await loadWithWarnings('json-named-import')
1733+
expect(messages).toMatchInlineSnapshot(`
1734+
[
1735+
"(!) Your Vite config uses features that are unsupported by \`configLoader: 'native'\`, which is planned to become the default in a future major version of Vite:
1736+
- named import from JSON module "./data.json" (vite.config.js:1:10). JSON modules only provide a default export per spec. Use the default import and access the property
1737+
Set \`VITE_CONFIG_NATIVE_IGNORE_WARNING=true\` to suppress this warning.",
1738+
]
1739+
`)
1740+
})
1741+
1742+
test('warns on named import from a bare JSON specifier', async () => {
1743+
const messages = await loadWithWarnings('json-named-import-bare')
1744+
expect(messages).toMatchInlineSnapshot(`
1745+
[
1746+
"(!) Your Vite config uses features that are unsupported by \`configLoader: 'native'\`, which is planned to become the default in a future major version of Vite:
1747+
- named import from JSON module "some-pkg/package.json" (vite.config.js:1:10). JSON modules only provide a default export per spec. Use the default import and access the property
1748+
Set \`VITE_CONFIG_NATIVE_IGNORE_WARNING=true\` to suppress this warning.",
1749+
]
1750+
`)
1751+
})
1752+
1753+
test('does not warn on JSON default imports (`default as` included)', async () => {
1754+
expect(await loadWithWarnings('json-named-import-ok')).toHaveLength(0)
1755+
})
1756+
17311757
test('warns on an extension-less import that resolves to JSON', async () => {
17321758
const messages = await loadWithWarnings('json-extensionless')
17331759
expect(messages).toMatchInlineSnapshot(`

‎packages/vite/src/node/__tests__/fixtures/config/native-compat/json-named-import-bare/node_modules/some-pkg/package.json‎

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import { version } from 'some-pkg/package.json' with { type: 'json' }
2+
3+
export default { define: { VERSION: JSON.stringify(version) } }
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{ "version": "1.0.0" }

‎packages/vite/src/node/__tests__/fixtures/config/native-compat/json-named-import-ok/node_modules/some-pkg/package.json‎

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import somePkg from 'some-pkg/package.json' with { type: 'json' }
2+
import data, { default as dataAlias } from './data.json' with { type: 'json' }
3+
4+
export default {
5+
define: {
6+
VERSION: JSON.stringify(data.version + dataAlias.version + somePkg.version),
7+
},
8+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{ "version": "1.0.0" }
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import { version } from './data.json' with { type: 'json' }
2+
3+
export default { define: { VERSION: JSON.stringify(version) } }

‎packages/vite/src/node/nativeConfigCompat.ts‎

Lines changed: 72 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ export type NativeConfigIncompatibilityType =
1212
| 'extensionless-import'
1313
| 'directory-index-import'
1414
| 'json-without-attributes'
15+
| 'json-named-import'
1516
| 'esm-syntax-in-cjs'
1617

1718
export interface NativeConfigIncompatibility {
@@ -31,6 +32,8 @@ export interface ConfigImportRef {
3132
line: number
3233
column: number
3334
hasTypeJsonAttribute: boolean
35+
/** position of the first non-default named binding */
36+
namedImportLoc?: { line: number; column: number }
3437
}
3538

3639
const jsTsExtRE = /\.[cm]?[jt]sx?$/
@@ -56,14 +59,36 @@ export function classifyImportRef(
5659
const base = { file, line, column, specifier }
5760

5861
if (specifier.endsWith('.json')) {
59-
if (ref.hasTypeJsonAttribute) return undefined
60-
return { type: 'json-without-attributes', ...base }
62+
if (!ref.hasTypeJsonAttribute) {
63+
return { type: 'json-without-attributes', ...base }
64+
}
65+
if (ref.namedImportLoc) {
66+
return {
67+
type: 'json-named-import',
68+
file,
69+
line: ref.namedImportLoc.line,
70+
column: ref.namedImportLoc.column,
71+
specifier,
72+
}
73+
}
74+
return undefined
6175
}
6276

6377
if (!resolvedId) return undefined
6478

65-
if (resolvedId.endsWith('.json') && !ref.hasTypeJsonAttribute) {
66-
return { type: 'json-without-attributes', ...base }
79+
if (resolvedId.endsWith('.json')) {
80+
if (!ref.hasTypeJsonAttribute) {
81+
return { type: 'json-without-attributes', ...base }
82+
}
83+
if (ref.namedImportLoc) {
84+
return {
85+
type: 'json-named-import',
86+
file,
87+
line: ref.namedImportLoc.line,
88+
column: ref.namedImportLoc.column,
89+
specifier,
90+
}
91+
}
6792
}
6893

6994
const lastSegment = lastSegmentOf(specifier)
@@ -89,6 +114,24 @@ const hasTypeJson = (
89114
return key === 'type' && attr.value?.value === 'json'
90115
})
91116

117+
const findNonDefaultNamedBinding = (
118+
specifiers: ESTree.Node[],
119+
): ESTree.Node | undefined =>
120+
specifiers.find((s) => {
121+
if (s.type === 'ImportSpecifier') {
122+
return !isDefaultModuleExportName(s.imported)
123+
}
124+
if (s.type === 'ExportSpecifier') {
125+
return !isDefaultModuleExportName(s.local)
126+
}
127+
return false
128+
})
129+
130+
const isDefaultModuleExportName = (node: ESTree.ModuleExportName): boolean =>
131+
node.type === 'Identifier'
132+
? node.name === 'default'
133+
: node.value === 'default'
134+
92135
const DIRNAME_FILENAME = {
93136
__dirname: 'dirname',
94137
__filename: 'filename',
@@ -104,14 +147,23 @@ export function analyzeConfigModuleReferences(
104147
const addImportRef = (
105148
source: ESTree.StringLiteral,
106149
hasTypeJsonAttribute: boolean,
150+
namedBinding: ESTree.Node | undefined,
107151
): void => {
108-
if (!isPathSpecifier(source.value)) return
152+
// bare specifiers are skipped except for the JSON checks, which classify
153+
// from the specifier alone (`vue/package.json` etc.)
154+
if (!isPathSpecifier(source.value) && !source.value.endsWith('.json')) {
155+
return
156+
}
109157
const { line, column } = numberToPos(code, source.start)
158+
const namedImportLoc = namedBinding
159+
? numberToPos(code, namedBinding.start)
160+
: undefined
110161
imports.push({
111162
specifier: source.value,
112163
line,
113164
column,
114165
hasTypeJsonAttribute,
166+
namedImportLoc,
115167
})
116168
}
117169

@@ -120,20 +172,30 @@ export function analyzeConfigModuleReferences(
120172
const node = _node as ESTree.Node
121173
switch (node.type) {
122174
case 'ImportDeclaration':
123-
addImportRef(node.source, hasTypeJson(node.attributes))
175+
addImportRef(
176+
node.source,
177+
hasTypeJson(node.attributes),
178+
findNonDefaultNamedBinding(node.specifiers),
179+
)
124180
break
125181
case 'ExportNamedDeclaration':
126182
case 'ExportAllDeclaration':
127183
if (node.source)
128-
addImportRef(node.source, hasTypeJson(node.attributes))
184+
addImportRef(
185+
node.source,
186+
hasTypeJson(node.attributes),
187+
node.type === 'ExportNamedDeclaration'
188+
? findNonDefaultNamedBinding(node.specifiers)
189+
: undefined,
190+
)
129191
break
130192
case 'ImportExpression':
131193
if (
132194
node.source.type === 'Literal' &&
133195
typeof node.source.value === 'string'
134196
) {
135197
// if a second (options) arg is present, assume the required attributes is set
136-
addImportRef(node.source, node.options != null)
198+
addImportRef(node.source, node.options != null, undefined)
137199
}
138200
break
139201
}
@@ -194,6 +256,8 @@ function describeIncompatibility(
194256
return item.specifier?.endsWith('.json')
195257
? `JSON import "${item.specifier}" without import attributes (${loc}). Add \`with { type: 'json' }\``
196258
: `import "${item.specifier}" resolves to a JSON file (${loc}). Import it with a \`.json\` extension and \`with { type: 'json' }\``
259+
case 'json-named-import':
260+
return `named import from JSON module "${item.specifier}" (${loc}). JSON modules only provide a default export per spec. Use the default import and access the property`
197261
case 'esm-syntax-in-cjs':
198262
return `ESM syntax in a file loaded as CommonJS (${loc}). Use a \`.mjs\` extension or set \`"type": "module"\` in the closest package.json`
199263
}

0 commit comments

Comments
 (0)