ts-loader/css-loader 无法导入/解析文件 [英] ts-loader / css-loader not being able to import/resolve file

查看:88
本文介绍了ts-loader/css-loader 无法导入/解析文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用 style-loader 和 css-loader 添加 css 模块.很难弄清楚这一点.我也不确定是 ts-loader 的错还是 css-loader 的错.

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]' 
                  }
            ]
        }
    }
}

组件

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


附言我尝试使用 extract-text-webpack-plugin,但这只会使一切变得更加混乱,使错误不堪重负


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

推荐答案

因此,由于这似乎不是一个流行的问题,我设法找到了解决方案.希望这能帮助那些在 ts-loader + css-loader 上苦苦挣扎的人.

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) 添加处理 .css 扩展名的 .d.ts 文件

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

2) 由于我使用的是 Webpack 3.x,因此将 webpack.config.js<中的 style 更改为 style-loader/strong>

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) 在组件文件中导入样式为 *

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

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

4) 在 tsconfig.json 中,将 .d.ts 文件添加到 include 部分.就我而言,它...

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

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

重新启动 webpack-dev-server 或其他任何东西,它应该很好(希望如此).

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

快乐编码!

这篇关于ts-loader/css-loader 无法导入/解析文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆