TypeScript declare specific SCSS module

Viewed 711

I'm trying to declare a specific SCSS module to import from TypeScript. I have this declaration file that is working well:

declare module '*.scss' {
  const styles: {
    a: string
    b: string
    c: string
  }

  export default styles
}

But I'd like to narrow down *.scss somehow so that this declaration file only applies to the SCSS file _variables.scss which is located in the same directory.

I have tried to replace *.scss with _variables.scss or ./_variables.scss but then TypeScript wasn't able to find the module declaration at all.

Is this possible with TypeScript?

3 Answers

You can do your module declaration like this. Read more on wildcard module declarations here.

declare module '*_variables.scss' {
  const styles: {
    a: string
    b: string
    c: string
  }

  export default styles
}

I tested different cases to import _variables.scss. I think @JoshA's answer is a great way to be flexible with different (absolute, relative) paths of your file. However, as you mentioned in a comment, you would like to get TS errors when you import _variables.scss from the wrong location.

For this purpose, I created a folder assets in the root directory. I created then _variables.scss and _variables.d.ts in assets folder. Then, I included './_variable.d.ts' in types of tsconfig.json.

root
   /assets
          _variables.dt.ts
          _variables.scss

In my tests, I realised that it is important to have an absolute path, which you will later use for importing _variables.scss in your .ts files. For example, I use Nuxt.js and you can define there root path by ~. If I need to import _variables.scss, I will always use

//someFile.ts
import SomeVariableName from `~/assets/_variables.scss`

Therefore, if I define my _variables.d.ts file as shown below, everything will work, as you need.

//_variables.d.ts
declare module '~/assets/_variables.scss' {
  const styles: {
    a: string
    b: string
    c: string
  }

  export default styles
}

As you see, the path to _variables.scss is exactly the same for import and declare statements: ~/assets/_variables.scss. You will not be able to import the file with relative paths. For example, these would not work:

import SomeVariable from '../assets/_variables.scss'
import SomeVariable from './assets/_variables.scss' 
import SomeVariable from '../_variables.scss'
import SomeVariable from './_variables.scss'

To conclude, if you define in declare module 'Absolute-Path-of-_variables.scss-File-As-You-Import-It-In-Other-.ts-files' {} absolute path to _variables.scss and import it with the same path in .ts files, everything should work for your purpose.

Try to put the entire path of the import in the declare module.

So if your file exists in ../foo/bar/_variables.scss

make the declare

declare module '../foo/bar/_variables.scss' {
  const styles: {
    a: string
    b: string
    c: string
  }

  export default styles
}
Related