Issue with importing CSS/SASS into Vue Cli 3 Typescript within the <script> block

Recently, I created a new Vue app using TypeScript with Vue Cli 3.

However, when attempting to import CSS or Sass into my TypeScript file, I encountered the following issue:

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

This resulted in the error message:

Cannot find module

While searching for a solution, I came across an article on How to use CSS Modules with TypeScript and webpack, but I'm unsure how to implement it in Vue Cli 3, which abstracts away the webpack configuration.

Does anyone have any suggestions on what to add to the vue.config.js file in order to directly import CSS and Sass files into the block?

I've read that using typings-for-css-modules-loader instead of css-loader may be necessary.

Answer №1

By importing the file directly (e.g., import '@/foo.scss'), the styles will automatically be applied to the current component without the need for a reference to the imported styles. In other words:

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

Check out the demo

To add support for importing Sass files in a vue-cli project, simply install sass and sass-loader (no extra configuration required):

npm i -S sass sass-loader

After that, you can import a .scss file using one of the following methods:

  • <script> import:
<script>
  import '/path/to/foo.scss';
</script>
  • <style src>:
<style scoped src="/path/to/foo.scss" lang="scss"></style>

Keep in mind that by adding the optional scoped attribute, the styles will only apply to the current component (similar to CSS Modules).

Answer №2

To start, craft a new file within your current project's directory. You can name it something like ambient.d.ts (I typically go with this, but feel free to choose your own title). Inside this file, include the following code:

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

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

Make sure to adjust the export type and structure to align best with your specific requirements and usage.

Answer №3

To resolve the issue of importing scss files from @material located in node_modules/@material, follow these steps:

Create a new file called vue.config.js in the root directory of your project.

const path = require('path');

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

I encountered a similar problem while trying to import these scss files, and after researching for two days, I found a solution on this Github issue. By setting 'node_modules' as the value for

PATH_TO_WHERE_YOUR_SCSS_FILES_ARE
, the problem was resolved.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with comparing strings in Typescript

This particular issue is causing my Angular application to malfunction. To illustrate, the const I've defined serves as a means of testing certain values within a function. Although there are workarounds for this problem, I find it perplexing and woul ...

The combination of UseState and useContext in React Typescript may lead to compatibility issues

I attempted to integrate the context API with the useState hook but encountered difficulties when using TypeScript. First, let's create App.tsx: const App = () => { const [exampleId, updateExampleId] = useState(0); return ( <div> ...

What are the tips for using ts-node in the presence of errors?

While developing, I have encountered some issues with ts-node. When I need to test something, commenting out code is my usual approach. However, when using ts-node, I keep getting this error message: 'foo' is declared but its value is never rea ...

The VueJS component reference component is completely inaccessible

I am having trouble understanding how to properly use refs in Vue components. I have two files that are not working together correctly. show.vue <template> <div> <b-container fluid class="bg-white" v-if="$refs.chart"> <b- ...

Is it possible to utilize axios in Vue while utilizing CORS in the API?

I am encountering an issue with making a GET request to a CORS enabled corona virus API using axios and Vue. I have no control over their server, and my Vue app was created with vue-cli. Interestingly, I am able to make two requests from different APIs - ...

Does moment/moment-timezone have a feature that allows for the conversion of a timezone name into a more easily comprehendible format?

Consider this example project where a timezone name needs to be converted to a more readable format. For instance: input: America/Los_Angeles output: America Los Angeles While "America/Los_Angeles" may seem human-readable, the requirement is to convert ...

Using Vuetify to filter items in a v-data-table upon clicking a button

My table structure is similar to this, https://i.sstatic.net/56TUi.png I am looking to implement a functionality where clicking on the Filter Button will filter out all items that are both male and valid with a value of true. users = [ { name: &apos ...

Navigate to a different route in AntD Table by clicking on it

I am currently implementing React Router in my navigation component. My goal is to enable users to navigate from screen Y to screen X when they click on a table element. In the past, I achieved this by using "this" command but it seems that it does not ...

Tips for making use of incomplete types

Is there a way to reference a type in TypeScript without including all of its required fields, without creating a new interface or making all fields optional? Consider the following scenario: interface Test { one: string; two: string; } _.findWhe ...

Unable to access component data while inside a v-for loop scope

I recently started using Vue and I'm having trouble accessing my component data within a v-for loop. After implementing the code below, I encountered this error message. TypeError: Cannot read property 'whatever' of undefined at eva ...

Running TypeScript Jest tests in Eclipse 2020-12: A step-by-step guide

Having a TypeScript project with a test suite that runs smoothly using npm test in the project directory from the console. Is there a feature within Eclipse that can facilitate running these tests directly within the IDE, similar to how Java tests are ex ...

Compile a selection of messages from the conversations into an array

Need assistance in displaying messages from a chat Id using Vue js. I have managed to retrieve the data but facing issues in displaying them using the component. Any guidance would be much appreciated. This is where the messages will be displayed: <tem ...

Error encountered during build and deploy process on Windows while running npm

Struggling with compiling files using webpack and npm for my reactJS application. Everything runs smoothly when I use npm start. However, running npm run deploy or npm run build on a windows environment doesn't work while it works fine on a linux env ...

Ways to divide the vuetify-text-field-label into two lines

My vuetify text field has a label that is too long for mobile devices. I am wondering if there is a way to automatically wrap the text. I attempted using div and p, as shown in this codepen link <div id="app"> <v-app id="inspire ...

Troubleshooting font color issues with PrimeNG charts in Angular

I have a chart and I am looking to modify the color of the labels https://i.sstatic.net/vsw6x.png The gray labels on the chart need to be changed to white for better readability Here is my code snippet: HTML5: <div class="box-result"> ...

Can a VS Code theme extension be designed using JavaScript or TypeScript rather than JSON?

Currently working on a VS Code theme extension, I am interested in exploring the possibility of using JavaScript or TypeScript files instead of a JSON file. The idea of having all the theme information crammed into one massive JSON file feels disorganize ...

Guide on assigning a value to an object array within an Angular application

I need help figuring out how to update a value in an object array. The current object array is structured like this: objArr = [ { "id": "123", "name": "abc" }, { "id": "null", "name ...

Replace the JS function in the bundle with a new custom function

I have compiled my AngularJS website using webpack. While in the Chrome console, I am trying to override a function within the controller of a particular directive. Is this achievable? ...

An issue occurred in resolving dependencies for the UsersService in Nest

I've been experimenting with Nest a bit, attempting to create a module that I can publish on my private repository for reuse in future projects. However, I've run into an error: ERROR [ExceptionHandler] Nest can't resolve dependencies of the ...

Tips for using jest.mock with simple-git/promise

I have been attempting to simulate the checkout function of simple-git/promise in my testing but without success. Here is my current approach: jest.mock('simple-git/promise', () => { return { checkout: async () => { ...