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

匿名 (未验证) 提交于 2019-12-03 09:14:57

问题:

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

回答1:

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!



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!