首页 文章

React和TypeScript - 如何导入Less

提问于
浏览
0

我正在尝试在我的ReactJS组件中导入LESS类 .

我正在使用 react-autosuggest 并根据文档(对于JS)我应该这样做:

//file: myTheme.css

.container { ... }
.input { ... }
.suggestionsContainer { ... }
.suggestion { ... }
.suggestionFocused { ... }

然后,在我的组件中导入它并使用如下:

import theme from 'theme.css';
// ...
<Autosuggest theme={theme} ... />

问题是,TypeScript不允许我像这样导入css文件 . 它说:

error TS2307: Cannot find module '../../../Stylesheets/AutosuggestStyles.css'

另一个问题是我想使用 Less 为我的组件设置样式 . 我不知道该怎么做 .

我怎么能这样做(如果不能用Less,CSS对我来说已经足够了)

2 回答

  • 0

    我怎么能这样做

    只需在文件 globals.d.ts 中声明它

    declare module "theme.css";
    

    更多

    https://basarat.gitbooks.io/typescript/content/docs/types/ambient/intro.html

  • 1

    我们对webpack使用typed-css-modules-loader . 它由观察者产生d.ts类型 .

    • npm install less-loader style-loader css-loader typed-css-modules-loader --save-dev

    • 添加到webpack.config,到规则部分(如果您使用的是Webpack 2)

    {
    test: /\.less$/,
    include: jsDir,
    exclude: commonExcludePaths,
    use: [
        'style-loader',
        'css-loader?modules&importLoaders=1&localIdentName=\'[path][name]-[local]--[hash:base64:5]\'',
        'typed-css-modules-loader',
    ]}
    

    有时TS编译器看不到新的输入,你需要等待或重新运行你的观察者 . 希望这可以帮助

相关问题