Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support css alias #692

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions playground/alias/TestAlias.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<template>
<h2>Alias</h2>
<p class="alias">{{ msg }}</p>
<p class="dir-alias">{{ dirMsg }}</p>
<p class="alias alias-css">{{ msg }}</p>
<p class="dir-alias alias-scss">{{ dirMsg }}</p>
<p class="dir-alias-index">{{ dirIndexMsg }}</p>
<p class="dir-alias-import-outside">{{ importOutsideMsg }}</p>
</template>
Expand All @@ -21,3 +21,8 @@ export default {
})
}
</script>

<style lang="scss">
@import "/@alias/aliased.css";
@import "/@alias/aliasedScss.scss";
</style>
3 changes: 3 additions & 0 deletions playground/alias/aliased-dir/aliased.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.alias-css {
color: red;
}
25 changes: 15 additions & 10 deletions src/node/build/buildPluginCss.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
} from '@vue/compiler-sfc'
import chalk from 'chalk'
import { CssPreprocessOptions } from '../config'
import { InternalResolver } from '../resolver'

const debug = require('debug')('vite:build:css')

Expand All @@ -34,16 +35,19 @@ interface BuildCssOption {
modulesOptions?: SFCAsyncStyleCompileOptions['modulesOptions']
}

export const createBuildCssPlugin = ({
root,
publicBase,
assetsDir,
minify = false,
inlineLimit = 0,
cssCodeSplit = true,
preprocessOptions,
modulesOptions = {}
}: BuildCssOption): Plugin => {
export const createBuildCssPlugin = (
resolver: InternalResolver,
{
root,
publicBase,
assetsDir,
minify = false,
inlineLimit = 0,
cssCodeSplit = true,
preprocessOptions,
modulesOptions = {}
}: BuildCssOption
): Plugin => {
const styles: Map<string, string> = new Map()
const assets = new Map<string, Buffer>()
let staticCss = ''
Expand All @@ -63,6 +67,7 @@ export const createBuildCssPlugin = ({
const result = isVueStyle
? css
: await compileCss(
resolver,
root,
id,
{
Expand Down
9 changes: 6 additions & 3 deletions src/node/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,9 @@ export async function createBaseRollupPlugins(
// vite:esbuild
enableEsbuild ? await createEsbuildPlugin(options.jsx) : null,
// vue
enableRollupPluginVue ? await createVuePlugin(root, options) : null,
enableRollupPluginVue
? await createVuePlugin(resolver, root, options)
: null,
require('@rollup/plugin-json')({
preferConst: true,
indent: ' ',
Expand Down Expand Up @@ -181,6 +183,7 @@ export async function createBaseRollupPlugins(
}

async function createVuePlugin(
resolver: InternalResolver,
root: string,
{
vueCustomBlockTransforms = {},
Expand All @@ -195,7 +198,7 @@ async function createVuePlugin(
const {
options: postcssOptions,
plugins: postcssPlugins
} = await resolvePostcssOptions(root, true)
} = await resolvePostcssOptions(resolver, root, true)

if (typeof vueTransformAssetUrls === 'object') {
vueTransformAssetUrls = {
Expand Down Expand Up @@ -378,7 +381,7 @@ export async function build(options: BuildConfig): Promise<BuildResult> {
sourcemap
),
// vite:css
createBuildCssPlugin({
createBuildCssPlugin(resolver, {
root,
publicBase: publicBasePath,
assetsDir,
Expand Down
2 changes: 1 addition & 1 deletion src/node/server/serverPluginCss.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ export const cssPlugin: ServerPlugin = ({ root, app, watcher, resolver }) => {
const filePath = resolver.requestToFile(ctx.path)
const preprocessLang = ctx.path.replace(cssPreprocessLangRE, '$2')

const result = await compileCss(root, ctx.path, {
const result = await compileCss(resolver, root, ctx.path, {
id: '',
source: css,
filename: filePath,
Expand Down
4 changes: 3 additions & 1 deletion src/node/server/serverPluginVue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ export const vuePlugin: ServerPlugin = ({
}
const id = hash_sum(publicPath)
const result = await compileSFCStyle(
resolver,
root,
styleBlock,
index,
Expand Down Expand Up @@ -601,6 +602,7 @@ function compileSFCTemplate(
}

async function compileSFCStyle(
resolver: InternalResolver,
root: string,
style: SFCStyleBlock,
index: number,
Expand All @@ -619,7 +621,7 @@ async function compileSFCStyle(

const { generateCodeFrame } = resolveCompiler(root)
const resource = filePath + `?type=style&index=${index}`
const result = (await compileCss(root, publicPath, {
const result = (await compileCss(resolver, root, publicPath, {
source: style.content,
filename: resource,
id: ``, // will be computed in compileCss
Expand Down
39 changes: 35 additions & 4 deletions src/node/utils/cssUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ import path from 'path'
import postcssrc from 'postcss-load-config'
import chalk from 'chalk'
import { asyncReplace } from './transformUtils'
import { isExternalUrl, resolveFrom } from './pathUtils'
import { isExternalUrl, resolveFrom, bareImportRE } from './pathUtils'
import { resolveCompiler } from './resolveVue'
import hash_sum from 'hash-sum'
import {
SFCAsyncStyleCompileOptions,
SFCStyleCompileResults
} from '@vue/compiler-sfc'
import { InternalResolver } from '../resolver'

export const urlRE = /url\(\s*('[^']+'|"[^"]+"|[^'")]+)\s*\)/
export const cssPreprocessLangRE = /(.+)\.(less|sass|scss|styl|stylus|postcss)$/
Expand Down Expand Up @@ -52,6 +53,7 @@ export function rewriteCssUrls(
}

export async function compileCss(
resolver: InternalResolver,
root: string,
publicPath: string,
{
Expand Down Expand Up @@ -84,7 +86,7 @@ export async function compileCss(
const {
options: postcssOptions,
plugins: postcssPlugins
} = await resolvePostcssOptions(root, isBuild)
} = await resolvePostcssOptions(resolver, root, isBuild)

if (preprocessLang) {
preprocessOptions = preprocessOptions[preprocessLang] || preprocessOptions
Expand All @@ -94,6 +96,21 @@ export async function compileCss(
case 'sass':
preprocessOptions = {
includePaths: ['node_modules'],
importer: [
(id: string) => {
if (id.startsWith('file://')) {
id = id.replace('file://', '')
}
if (isExternalUrl(id)) {
return { file: id }
}
id = resolver.alias(id) || id
if (id.startsWith('.') || bareImportRE.test(id)) {
return { file: id }
}
return { file: resolver.requestToFile(id) }
}
],
...preprocessOptions
}
break
Expand Down Expand Up @@ -153,11 +170,25 @@ async function loadPostcssConfig(
}
}

export async function resolvePostcssOptions(root: string, isBuild: boolean) {
export async function resolvePostcssOptions(
resolver: InternalResolver,
root: string,
isBuild: boolean
) {
const config = await loadPostcssConfig(root)
const options = config && config.options
const plugins = config ? config.plugins : []
plugins.unshift(require('postcss-import')())
plugins.unshift(
require('postcss-import')({
resolve: (id: string) => {
id = resolver.alias(id) || id
if (id.startsWith('.') || bareImportRE.test(id)) {
return id
}
return resolver.requestToFile(id)
}
})
)
if (isBuild) {
plugins.push(require('postcss-discard-comments')({ removeAll: true }))
}
Expand Down
3 changes: 3 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -613,6 +613,9 @@ describe('vite', () => {
'directory aliased internal import outside hmr works'
)
}
// css alias
expect(await getComputedColor('.alias-css')).toBe('rgb(255, 0, 0)')
expect(await getComputedColor('.alias-scss')).toBe('rgb(255, 0, 0)')
})

test('transforms', async () => {
Expand Down