Roland Jegorov
Roland Jegorov

Reputation: 819

ts-loader / css-loader not being able to import/resolve file

Trying to add css modules using style-loader and css-loader. Having a hard time figuring this out. I'm also not sure whether it's ts-loader to blame or css-loader.

webpack.config.js

const path = require('path');

module.exports = env => {
    return {
        devtool: "inline-source-map",
        entry: "./src/index.tsx",
        output: {
            path: path.resolve(__dirname, "/public"),
            filename: "build/app.js"
        },
        resolve: {
            extensions: [".ts", ".tsx", ".js", ".json"],
        },
        module: {
            rules: [
                {
                    test: /\.tsx?$/,
                    loader: "ts-loader",
                },
                {
                    test: /\.css$/,
                    loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' 
                  }
            ]
        }
    }
}

component

import styles from "./Main.css"; // TS2307: Cannot find module './Main.css'.


P.S. I tried using the extract-text-webpack-plugin, but that only messed up everything even more making the errors overwhelming

Upvotes: 2

Views: 3000

Answers (1)

Roland Jegorov
Roland Jegorov

Reputation: 819

So since this doesn't seem like a popular problem I managed to find the solution. Hope this will help anyone who struggles with ts-loader + css-loader.

1) Add .d.ts file that handles .css extensions

// I put it in root, but could be anywhere
// <root>/defs.d.ts
declare module "*.css" {
    var styles: { [key: string]: string };
    export = styles
}

2) Since I use Webpack 3.x, change style to style-loader in webpack.config.js

    module: {
        rules: [
            //...
            {
                test: /\.css$/,
                loader: 'style-loader!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' 
            }
        ]
    }

3) Import styles as * in component file

// In Main.tsx
import * as styles from "./Main.css";

// Usage
<div className={styles.nameOfClass} />

4) In tsconfig.json add .d.ts file to the include part. In my case its...

"include": [
    "src",
    "./defs.d.ts"
],

Restart webpack-dev-server or whatever and it should be good to go (hopefully).

Happy coding!

Upvotes: 3

Related Questions