Skip to content

Commit

Permalink
feat(css)!: remove css default export
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red committed Aug 17, 2023
1 parent bd9b749 commit d87a047
Show file tree
Hide file tree
Showing 13 changed files with 46 additions and 255 deletions.
48 changes: 8 additions & 40 deletions packages/vite/client.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,60 +38,28 @@ declare module '*.module.sss' {

// CSS
declare module '*.css' {
/**
* @deprecated Use `import style from './style.css?inline'` instead.
*/
const css: string
export default css
export {}
}
declare module '*.scss' {
/**
* @deprecated Use `import style from './style.scss?inline'` instead.
*/
const css: string
export default css
export {}
}
declare module '*.sass' {
/**
* @deprecated Use `import style from './style.sass?inline'` instead.
*/
const css: string
export default css
export {}
}
declare module '*.less' {
/**
* @deprecated Use `import style from './style.less?inline'` instead.
*/
const css: string
export default css
export {}
}
declare module '*.styl' {
/**
* @deprecated Use `import style from './style.styl?inline'` instead.
*/
const css: string
export default css
export {}
}
declare module '*.stylus' {
/**
* @deprecated Use `import style from './style.stylus?inline'` instead.
*/
const css: string
export default css
export {}
}
declare module '*.pcss' {
/**
* @deprecated Use `import style from './style.pcss?inline'` instead.
*/
const css: string
export default css
export {}
}
declare module '*.sss' {
/**
* @deprecated Use `import style from './style.sss?inline'` instead.
*/
const css: string
export default css
export {}
}

// Built-in asset types
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,13 @@ describe('fixture', async () => {
).code

expect(
(
await transformGlobImport(code, id, root, resolveId, true)
)?.s.toString(),
(await transformGlobImport(code, id, root, resolveId))?.s.toString(),
).toMatchSnapshot()
})

it('preserve line count', async () => {
const getTransformedLineCount = async (code: string) =>
(
await transformGlobImport(code, 'virtual:module', root, resolveId, true)
)?.s
(await transformGlobImport(code, 'virtual:module', root, resolveId))?.s
.toString()
.split('\n').length

Expand All @@ -52,7 +48,7 @@ describe('fixture', async () => {
].join('\n')
expect(
(
await transformGlobImport(code, 'virtual:module', root, resolveId, true)
await transformGlobImport(code, 'virtual:module', root, resolveId)
)?.s.toString(),
).toMatchSnapshot()

Expand All @@ -62,7 +58,6 @@ describe('fixture', async () => {
'virtual:module',
root,
resolveId,
true,
)
expect('no error').toBe('should throw an error')
} catch (err) {
Expand All @@ -80,7 +75,7 @@ describe('fixture', async () => {

expect(
(
await transformGlobImport(code, id, root, resolveId, true, true)
await transformGlobImport(code, id, root, resolveId, true)
)?.s.toString(),
).toMatchSnapshot()
})
Expand Down
1 change: 0 additions & 1 deletion packages/vite/src/node/optimizer/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,6 @@ function esbuildScanPlugin(
id,
config.root,
resolve,
config.isProduction,
)

return result?.s.toString() || transpiledContents
Expand Down
29 changes: 10 additions & 19 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,6 @@ const commonjsProxyRE = /\?commonjs-proxy/
const inlineRE = /[?&]inline\b/
const inlineCSSRE = /[?&]inline-css\b/
const styleAttrRE = /[?&]style-attr\b/
const usedRE = /[?&]used\b/
const varRE = /^var\(/i

const cssBundleName = 'style.css'
Expand Down Expand Up @@ -473,10 +472,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
`const __vite__css = ${JSON.stringify(cssContent)}`,
`__vite__updateStyle(__vite__id, __vite__css)`,
// css modules exports change on edit so it can't self accept
`${
modulesCode ||
`import.meta.hot.accept()\nexport default __vite__css`
}`,
`${modulesCode || 'import.meta.hot.accept()'}`,
`import.meta.hot.prune(() => __vite__removeStyle(__vite__id))`,
].join('\n')
return { code, map: { mappings: '' } }
Expand Down Expand Up @@ -505,22 +501,17 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
}

let code: string
if (usedRE.test(id)) {
if (modulesCode) {
code = modulesCode
} else {
let content = css
if (config.build.cssMinify) {
content = await minifyCSS(content, config, true)
}
code = `export default ${JSON.stringify(content)}`
if (modulesCode) {
code = modulesCode
} else if (inlined) {
let content = css
if (config.build.cssMinify) {
content = await minifyCSS(content, config, true)
}
code = `export default ${JSON.stringify(content)}`
} else {
// if moduleCode exists return it **even if** it does not have `?used`
// this will disable tree-shake to work with `import './foo.module.css'` but this usually does not happen
// this is a limitation of the current approach by `?used` to make tree-shake work
// See #8936 for more details
code = modulesCode || `export default ''`
// empty module when it's not a CSS module nor `?inline`
code = 'export {}'
}

return {
Expand Down
31 changes: 1 addition & 30 deletions packages/vite/src/node/plugins/importAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ import {
ERR_OUTDATED_OPTIMIZED_DEP,
throwOutdatedRequest,
} from './optimizedDeps'
import { isCSSRequest, isDirectCSSRequest, isModuleCSSRequest } from './css'
import { isCSSRequest, isDirectCSSRequest } from './css'
import { browserExternalId } from './resolve'

const debug = createDebugger('vite:import-analysis')
Expand Down Expand Up @@ -527,35 +527,6 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
// normalize
const [url, resolvedId] = await normalizeUrl(specifier, start)

if (
!isDynamicImport &&
specifier &&
!specifier.includes('?') && // ignore custom queries
isCSSRequest(resolvedId) &&
!isModuleCSSRequest(resolvedId)
) {
const sourceExp = source.slice(expStart, start)
if (
sourceExp.includes('from') && // check default and named imports
!sourceExp.includes('__vite_glob_') // glob handles deprecation message itself
) {
const newImport =
sourceExp + specifier + `?inline` + source.slice(end, expEnd)
this.warn(
`\n` +
colors.cyan(importerModule.file) +
`\n` +
colors.reset(generateCodeFrame(source, start)) +
`\n` +
colors.yellow(
`Default and named imports from CSS files are deprecated. ` +
`Use the ?inline query instead. ` +
`For example: ${newImport}`,
),
)
}
}

// record as safe modules
// safeModulesPath should not include the base prefix.
// See https://github.com/vitejs/vite/issues/9438#issuecomment-1465270409
Expand Down
83 changes: 8 additions & 75 deletions packages/vite/src/node/plugins/importMetaGlob.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import {
slash,
transformStableResult,
} from '../utils'
import { isCSSRequest, isModuleCSSRequest } from './css'

const { isMatch, scan } = micromatch

Expand Down Expand Up @@ -86,7 +85,6 @@ export function importGlobPlugin(config: ResolvedConfig): Plugin {
config.root,
(im, _, options) =>
this.resolve(im, id, options).then((i) => i?.id || im),
config.isProduction,
config.experimental.importGlobRestoreExtension,
)
if (result) {
Expand Down Expand Up @@ -338,24 +336,6 @@ const importPrefix = '__vite_glob_'

const { basename, dirname, relative, join } = posix

const warnedCSSDefaultImportVarName = '__vite_warned_css_default_import'
const jsonStringifyInOneline = (input: any) =>
JSON.stringify(input).replace(/[{,:]/g, '$& ').replace(/\}/g, ' }')
const createCssDefaultImportWarning = (
globs: string[],
options: GeneralImportGlobOptions,
) =>
`if (!${warnedCSSDefaultImportVarName}) {` +
`${warnedCSSDefaultImportVarName} = true;` +
`console.warn(${JSON.stringify(
'Default import of CSS without `?inline` is deprecated. ' +
"Add the `{ query: '?inline' }` glob option to fix this.\n" +
`For example: \`import.meta.glob(${jsonStringifyInOneline(
globs.length === 1 ? globs[0] : globs,
)}, ${jsonStringifyInOneline({ ...options, query: '?inline' })})\``,
)});` +
`}`

export interface TransformGlobImportResult {
s: MagicString
matches: ParsedImportGlob[]
Expand All @@ -370,7 +350,6 @@ export async function transformGlobImport(
id: string,
root: string,
resolveId: IdResolver,
isProduction: boolean,
restoreQueryExtension = false,
): Promise<TransformGlobImportResult | null> {
id = slash(id)
Expand Down Expand Up @@ -401,15 +380,7 @@ export async function transformGlobImport(
const staticImports = (
await Promise.all(
matches.map(
async ({
globs,
globsResolved,
isRelative,
options,
index,
start,
end,
}) => {
async ({ globsResolved, isRelative, options, index, start, end }) => {
const cwd = getCommonBase(globsResolved) ?? root
const files = (
await fg(globsResolved, {
Expand Down Expand Up @@ -459,7 +430,6 @@ export async function transformGlobImport(
return { filePath, importPath }
}

let includesCSS = false
files.forEach((file, i) => {
const paths = resolvePaths(file)
const filePath = paths.filePath
Expand All @@ -474,10 +444,6 @@ export async function transformGlobImport(

importPath = `${importPath}${importQuery}`

const isCSS =
!query && isCSSRequest(file) && !isModuleCSSRequest(file)
includesCSS ||= isCSS

const importKey =
options.import && options.import !== '*'
? options.import
Expand All @@ -491,36 +457,14 @@ export async function transformGlobImport(
staticImports.push(
`import ${expression} from ${JSON.stringify(importPath)}`,
)
if (!isProduction && isCSS) {
objectProps.push(
`get ${JSON.stringify(
filePath,
)}() { ${createCssDefaultImportWarning(
globs,
options,
)} return ${variableName} }`,
)
} else {
objectProps.push(`${JSON.stringify(filePath)}: ${variableName}`)
}
objectProps.push(`${JSON.stringify(filePath)}: ${variableName}`)
} else {
let importStatement = `import(${JSON.stringify(importPath)})`
if (importKey)
importStatement += `.then(m => m[${JSON.stringify(importKey)}])`
if (!isProduction && isCSS) {
objectProps.push(
`${JSON.stringify(
filePath,
)}: () => { ${createCssDefaultImportWarning(
globs,
options,
)} return ${importStatement}}`,
)
} else {
objectProps.push(
`${JSON.stringify(filePath)}: () => ${importStatement}`,
)
}
objectProps.push(
`${JSON.stringify(filePath)}: () => ${importStatement}`,
)
}
})

Expand All @@ -533,20 +477,9 @@ export async function transformGlobImport(
? '\n'.repeat(originalLineBreakCount)
: ''

let replacement: string
if (!isProduction && includesCSS) {
replacement =
'/* #__PURE__ */ Object.assign(' +
'(() => {' +
`let ${warnedCSSDefaultImportVarName} = false;` +
`return {${objectProps.join(',')}${lineBreaks}};` +
'})()' +
')'
} else {
replacement = `/* #__PURE__ */ Object.assign({${objectProps.join(
',',
)}${lineBreaks}})`
}
const replacement = `/* #__PURE__ */ Object.assign({${objectProps.join(
',',
)}${lineBreaks}})`
s.overwrite(start, end, replacement)

return staticImports
Expand Down

0 comments on commit d87a047

Please sign in to comment.