Skip to content

Commit

Permalink
fix(css/assets): respect alias in css url() paths
Browse files Browse the repository at this point in the history
close #2043
  • Loading branch information
yyx990803 committed Feb 16, 2021
1 parent 34064c8 commit ad50060
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 28 deletions.
5 changes: 5 additions & 0 deletions packages/playground/assets/__tests__/assets.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,11 @@ describe('css url() references', () => {
expect(bg).toMatch(iconMatch)
})

test('aliased', async () => {
const bg = await getBg('.css-url-aliased')
expect(bg).toMatch(assetMatch)
})

if (isBuild) {
test('preserve postfix query/hash', () => {
expect(findAssetFile(/\.css$/, 'foo')).toMatch(`woff2?#iefix`)
Expand Down
8 changes: 7 additions & 1 deletion packages/playground/assets/css/css-url.css
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,13 @@
}

.css-url-same-line {
background: url('/nested/asset.png') top right / 10px no-repeat, url('/icon.png') bottom right / 10px no-repeat;
background: url('/nested/asset.png') top right / 10px no-repeat,
url('/icon.png') bottom right / 10px no-repeat;
}

.css-url-aliased {
background: url('@/asset.png');
background-size: 10px;
}

/*
Expand Down
3 changes: 3 additions & 0 deletions packages/playground/assets/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ <h2>CSS url references</h2>
>CSS background (multiple urls on same line)</span
>
</div>
<div class="css-url-aliased">
<span style="background: #fff">CSS background (aliased)</span>
</div>

<h2>SVG Fragments</h2>
<div>
Expand Down
7 changes: 7 additions & 0 deletions packages/playground/assets/vite.config.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
const path = require('path')

/**
* @type {import('vite').UserConfig}
*/
module.exports = {
base: '/foo/',
publicDir: 'static',
resolve: {
alias: {
'@': path.resolve(__dirname, 'nested')
}
},
build: {
outDir: 'dist/foo',
manifest: true
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ export function fileToUrl(
}
}

export function fileToDevUrl(id: string, config: ResolvedConfig) {
function fileToDevUrl(id: string, config: ResolvedConfig) {
let rtn: string
if (checkPublicFile(id, config)) {
// in public dir, keep the url as-is
Expand Down
71 changes: 45 additions & 26 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ import { ResolveFn, ViteDevServer } from '../'
import {
getAssetFilename,
assetUrlRE,
fileToDevUrl,
registerAssetToChunk,
urlToBuiltUrl
fileToUrl,
checkPublicFile
} from './asset'
import MagicString from 'magic-string'
import * as Postcss from 'postcss'
Expand Down Expand Up @@ -103,7 +103,12 @@ export function cssPlugin(config: ResolvedConfig): Plugin {
const moduleCache = new Map<string, Record<string, string>>()
cssModulesCache.set(config, moduleCache)

const resolvers = createCSSResolvers(config)
const resolveUrl = config.createResolver({
preferRelative: true,
tryIndex: false,
extensions: []
})
const atImportResolvers = createCSSResolvers(config)

return {
name: 'vite:css',
Expand All @@ -117,27 +122,38 @@ export function cssPlugin(config: ResolvedConfig): Plugin {
return
}

const urlReplacer: CssUrlReplacer = server
? (url, importer) => {
if (url.startsWith('/')) {
return config.base + url.slice(1)
} else {
const filePath = normalizePath(
path.resolve(path.dirname(importer || id), url)
)
return fileToDevUrl(filePath, config)
}
}
: (url, importer) => {
return urlToBuiltUrl(url, importer || id, config, this)
}
const urlReplacer: CssUrlReplacer = async (url, importer) => {
if (checkPublicFile(url, config)) {
return config.base + url.slice(1)
}
const resolved = await resolveUrl(url, importer)
if (resolved) {
return fileToUrl(resolved, config, this)
}
return url
}

// const urlReplacer: CssUrlReplacer = server
// ? (url, importer) => {
// if (url.startsWith('/')) {
// return config.base + url.slice(1)
// } else {
// const filePath = normalizePath(
// path.resolve(path.dirname(importer || id), url)
// )
// return fileToDevUrl(filePath, config)
// }
// }
// : (url, importer) => {
// return urlToBuiltUrl(url, importer || id, config, this)
// }

const { code: css, modules, deps } = await compileCSS(
id,
raw,
config,
urlReplacer,
resolvers
atImportResolvers
)
if (modules) {
moduleCache.set(id, modules)
Expand Down Expand Up @@ -416,13 +432,13 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
}
}

interface CSSResolvers {
interface CSSAtImportResolvers {
css: ResolveFn
sass: ResolveFn
less: ResolveFn
}

function createCSSResolvers(config: ResolvedConfig): CSSResolvers {
function createCSSResolvers(config: ResolvedConfig): CSSAtImportResolvers {
let cssResolve: ResolveFn | undefined
let sassResolve: ResolveFn | undefined
let lessResolve: ResolveFn | undefined
Expand Down Expand Up @@ -471,7 +487,7 @@ async function compileCSS(
code: string,
config: ResolvedConfig,
urlReplacer: CssUrlReplacer,
resolvers: CSSResolvers
atImportResolvers: CSSAtImportResolvers
): Promise<{
code: string
map?: SourceMap
Expand Down Expand Up @@ -530,7 +546,7 @@ async function compileCSS(
code,
config.root,
opts,
resolvers
atImportResolvers
)
if (preprocessResult.errors.length) {
throw preprocessResult.errors[0]
Expand All @@ -557,7 +573,10 @@ async function compileCSS(
postcssPlugins.unshift(
(await import('postcss-import')).default({
async resolve(id, basedir) {
const resolved = await resolvers.css(id, path.join(basedir, '*'))
const resolved = await atImportResolvers.css(
id,
path.join(basedir, '*')
)
if (resolved) {
return path.resolve(resolved)
}
Expand Down Expand Up @@ -799,7 +818,7 @@ type StylePreprocessor = (
additionalData?: PreprocessorAdditionalData
filename: string
},
resolvers: CSSResolvers
resolvers: CSSAtImportResolvers
) => StylePreprocessorResults | Promise<StylePreprocessorResults>

export interface StylePreprocessorResults {
Expand Down Expand Up @@ -954,13 +973,13 @@ let ViteLessManager: any
function createViteLessPlugin(
less: typeof Less,
rootFile: string,
resolvers: CSSResolvers
resolvers: CSSAtImportResolvers
): Less.Plugin {
if (!ViteLessManager) {
ViteLessManager = class ViteManager extends less.FileManager {
resolvers
rootFile
constructor(rootFile: string, resolvers: CSSResolvers) {
constructor(rootFile: string, resolvers: CSSAtImportResolvers) {
super()
this.rootFile = rootFile
this.resolvers = resolvers
Expand Down

0 comments on commit ad50060

Please sign in to comment.