2
votes

I built new vue app with typescript using Vue Cli 3.

When I try to import css or sass to my typescript file:

import * as sassStyles from '@/assets/sass/my.module.scss';

I got followning error:

Cannot find module

I found this article How to use CSS Modules with TypeScript and webpack but I have no idea how to integrate it with Vue Cli 3 who is abstracting away webpack config.

Any idea what to put in vue.config.js to able to import css and sass files directly to block?

I need to use typings-for-css-modules-loader instead of css-loader.

3
Why do you need a reference to the imported styles? (i.e. sassStyles)tony19

3 Answers

2
votes

Create a file in your project, say ambient.d.ts (my convention but you can call it anything), with the following:

declare module "@/assets/sass/*.scss" {
  const styles: any;
  export = styles;
}

declare module "@/assets/css/*.css" {
  const styles: any;
  export = styles;
}

adjust the type and form of the export to best match your usage.

2
votes

Try adding a new file called vue.config.js in your project root directory.

In the file, add the following contents:

const path = require('path');

module.exports = {
  css: {
    loaderOptions: {
      sass: {
        includePaths: [
          path.resolve(__dirname, 'PATH_TO_WHERE_YOUR_SCSS_FILES_ARE'),
        ],
      },
    },
  },
};

I came across a similar problem when I was trying to import the scss files from @material, which located in node_modules/@material, after two days of digging, I found this Github issue and gave it a try, and I used 'node_modules' as PATH_TO_WHERE_YOUR_SCSS_FILES_ARE and it solved my problem.

1
votes

Importing the file itself (i.e., import '@/foo.scss') will automatically apply the styles to the current component, so you don't actually need a reference to the imported styles. That is:

// import * as sassStyles from '@/assets/sass/my.module.scss'; // DON'T DO THIS
import '@/assets/sass/my.module.scss';

demo

The only steps needed to add support for importing Sass files in a vue-cli 3.x project is to install node-sass and sass-loader (no additional config needed):

npm i -S node-sass sass-loader

Then, you could use either of the following methods to import a .scss file:

<script> import:

<script>
  import '/path/to/foo.scss';
</script>

<style src>:

<style scoped src="/path/to/foo.scss" lang="scss"></style>

Note the optional scoped attribute makes the styles apply to the current component only (like CSS Modules).