diff --git a/packages/runtime-core/src/index.ts b/packages/runtime-core/src/index.ts index 243bde548c5..ed2de8bd7a1 100644 --- a/packages/runtime-core/src/index.ts +++ b/packages/runtime-core/src/index.ts @@ -105,6 +105,11 @@ export { // plugins export { getCurrentInstance } from './component' +/** + * @internal + */ +export { getCurrentGenericInstance } from './component' + // For raw render function users export { h } from './h' // Advanced render function utilities diff --git a/packages/runtime-dom/src/helpers/useCssModule.ts b/packages/runtime-dom/src/helpers/useCssModule.ts index 0fb738975d1..12ef833ecca 100644 --- a/packages/runtime-dom/src/helpers/useCssModule.ts +++ b/packages/runtime-dom/src/helpers/useCssModule.ts @@ -1,9 +1,9 @@ -import { getCurrentInstance, warn } from '@vue/runtime-core' +import { getCurrentGenericInstance, warn } from '@vue/runtime-core' import { EMPTY_OBJ } from '@vue/shared' export function useCssModule(name = '$style'): Record { if (!__GLOBAL__) { - const instance = getCurrentInstance()! + const instance = getCurrentGenericInstance() if (!instance) { __DEV__ && warn(`useCssModule must be called inside setup()`) return EMPTY_OBJ diff --git a/packages/runtime-vapor/__tests__/helpers/useCssModule.spec.ts b/packages/runtime-vapor/__tests__/helpers/useCssModule.spec.ts new file mode 100644 index 00000000000..5186edcc6f2 --- /dev/null +++ b/packages/runtime-vapor/__tests__/helpers/useCssModule.spec.ts @@ -0,0 +1,55 @@ +import { useCssModule } from '@vue/runtime-dom' +import { makeRender } from '../_utils' +import { defineVaporComponent, template } from '@vue/runtime-vapor' + +const define = makeRender() + +describe('useCssModule', () => { + function mountWithModule(modules: any, name?: string) { + let res + define( + defineVaporComponent({ + __cssModules: modules, + setup() { + res = useCssModule(name) + const n0 = template('
')() + return n0 + }, + }), + ).render() + return res + } + + test('basic usage', () => { + const modules = { + $style: { + red: 'red', + }, + } + expect(mountWithModule(modules)).toMatchObject(modules.$style) + }) + + test('basic usage', () => { + const modules = { + foo: { + red: 'red', + }, + } + expect(mountWithModule(modules, 'foo')).toMatchObject(modules.foo) + }) + + test('warn out of setup usage', () => { + useCssModule() + expect('must be called inside setup').toHaveBeenWarned() + }) + + test('warn missing injection', () => { + mountWithModule(undefined) + expect('instance does not have CSS modules').toHaveBeenWarned() + }) + + test('warn missing injection', () => { + mountWithModule({ $style: { red: 'red' } }, 'foo') + expect('instance does not have CSS module named "foo"').toHaveBeenWarned() + }) +})