vuejs / component-compiler-utils

Lower level utilities for compiling Vue single file components
322 stars 75 forks source link

[Question] Less imports @import '~@pkg/path/to/stylesheet.less' #135

Open cmath10 opened 1 year ago

cmath10 commented 1 year ago

Hello! I've noticed that this package uses https://www.npmjs.com/package/less for less file compilation. Also, compileStyle util doesn't support imports like

@import '~@pkg/path/to/stylesheet.less'

out of the box.

I'd like to know if this syntax support is planned or not. I use vue2-jest/vue3-jest & webpack and need to use syntax like that. I also have a workaround, but I'd love to get rid of it:

const path = require('path')
const less = require('less')

const logResultErrors = require('@vue/vue2-jest/lib/utils').logResultErrors

const MODULE_REQUEST_REGEX = /^[^?]*~/

class NodeModuleFileManager extends less.FileManager {
    supports (filename, currentDirectory, options, environment) {
        return MODULE_REQUEST_REGEX.test(filename)
    }

    supportsSync (filename, currentDirectory, options, environment) {
        return true
    }

    loadFile (filename, currentDirectory, options, environment) {
        const rest = [currentDirectory, options, environment]

        if (MODULE_REQUEST_REGEX.test(filename)) {
            return super.loadFile(filename.replace(MODULE_REQUEST_REGEX, ''), ...rest)
        }

        return super.loadFile(filename, ...rest)
    }
}

const compileStyle = require('@vue/component-compiler-utils').compileStyle

module.exports = {
    process: (content, filePath) => {
        const result = compileStyle({
            source: content,
            filePath,
            preprocessLang: 'less',
            preprocessOptions: {
                paths: [path.dirname(filePath), process.cwd()],
                plugins: [{
                    install (lessInstance, pluginManager) {
                        pluginManager.addFileManager(new NodeModuleFileManager());
                    },
                }],
            },
            scoped: false,
        })

        logResultErrors(result)

        return result.code
    },
}