From 4474c113d1fb1c26298dd6794275d5b5c7cc4d93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B1=B1=E5=90=B9=E8=89=B2=E5=BE=A1=E5=AE=88?= <85992002+KazariEX@users.noreply.github.com> Date: Fri, 11 Oct 2024 11:05:54 +0800 Subject: [PATCH] fix(compiler-sfc): use sass modern api if available and avoid deprecation warning (#11992) --- .../compiler-sfc/src/style/preprocessors.ts | 48 +++++++++++++------ 1 file changed, 34 insertions(+), 14 deletions(-) diff --git a/packages/compiler-sfc/src/style/preprocessors.ts b/packages/compiler-sfc/src/style/preprocessors.ts index 6a974368ecc..8c210ad16d1 100644 --- a/packages/compiler-sfc/src/style/preprocessors.ts +++ b/packages/compiler-sfc/src/style/preprocessors.ts @@ -23,28 +23,48 @@ export interface StylePreprocessorResults { // .scss/.sass processor const scss: StylePreprocessor = (source, map, options, load = require) => { - const nodeSass = load('sass') - const finalOptions = { - ...options, - data: getSource(source, options.filename, options.additionalData), - file: options.filename, - outFile: options.filename, - sourceMap: !!map, - } + const nodeSass: typeof import('sass') = load('sass') + const { compileString, renderSync } = nodeSass + + const data = getSource(source, options.filename, options.additionalData) + let css: string + let dependencies: string[] + let sourceMap: any try { - const result = nodeSass.renderSync(finalOptions) - const dependencies = result.stats.includedFiles + if (compileString) { + const { pathToFileURL, fileURLToPath }: typeof import('url') = load('url') + + const result = compileString(data, { + ...options, + url: pathToFileURL(options.filename), + sourceMap: !!map, + }) + css = result.css + dependencies = result.loadedUrls.map(url => fileURLToPath(url)) + sourceMap = map ? result.sourceMap! : undefined + } else { + const result = renderSync({ + ...options, + data, + file: options.filename, + outFile: options.filename, + sourceMap: !!map, + }) + css = result.css.toString() + dependencies = result.stats.includedFiles + sourceMap = map ? JSON.parse(result.map!.toString()) : undefined + } + if (map) { return { - code: result.css.toString(), - map: merge(map, JSON.parse(result.map.toString())), + code: css, errors: [], dependencies, + map: merge(map, sourceMap!), } } - - return { code: result.css.toString(), errors: [], dependencies } + return { code: css, errors: [], dependencies } } catch (e: any) { return { code: '', errors: [e], dependencies: [] } }