在一个新项目中,我需要将scss / css模块添加到typescript / react应用程序中。 我在项目和webpack.config.dev.js中添加了“typings-for-css-modules-loader” 像这样:(here is the entire webpack.config.dev.js)
{
test: /\.css$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('typings-for-css-modules-loader'),
options: {
importLoaders: 1,
modules: true
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
],
},{
test: /\.scss$/,
use: [
require.resolve('style-loader'),
require.resolve('sass-loader'),
{
loader: require.resolve('typings-for-css-modules-loader'),
options: {
namedexport: true,
camelcase: true,
modules: true
}
}
]
},
当我将test.scss文件添加到我的项目时,编译成功创建了一个test.scss.d.ts,其中包含:
export interface ITestScss {
'toto': string;
}
export const locals: ITestScss;
当我尝试在我的项目中导入此css时:
import styles from './scss/test.scss';
我收到此错误:
Module '"/home/cyprien/projets/test/typescript-sass-modules-boilerplate/src/scss/test.scss"' has no default export.
最后,在浏览器中,我收到此错误:
编译失败
./ SRC / SCSS / test.scss 模块构建失败: .toto { ^ “e”之后的无效CSS:预期的1个选择器或at-rule,是“exports = module.ex” 在/home/cyprien/projets/test/typescript-sass-modules-boilerplate/src/scss/test.scss(第1行,第1列)
答案 0 :(得分:1)
您需要使用插件mini-css-extract-plugin。以下是使用TypeScript和SASS SCSS进行配置的示例(但没有CSS模块也没有PostCSS):
// webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
module.exports = {
mode: "development",
devtool: "source-map",
resolve: {
extensions: [".ts", ".js"]
},
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules/,
use: {
loader: "ts-loader"
}
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader"
]
}
]
},
plugins: [
new MiniCssExtractPlugin()
]
}
我希望你能够适应它。
答案 1 :(得分:0)
找到了这个解决方案:
webpack config(dev),这是为了省事:
{
test: /\.modules\.less$/,
use: [{
loader: 'style-loader' // creates style nodes from JS strings
},{
loader: 'typings-for-css-modules-loader',
options:{
modules:true,
namedExport: true,
camelCase: true,
localIdentName:'[path][name]---[local]---[hash:base64:5]'
}
},{
loader: 'less-loader',
options: { javascriptEnabled: true }// compiles Less to CSS
}]
}
然后将您的less文件命名为something.modules.less
以如下方式将其导入js:
import * as styles from './something.modules.less';
并像这样使用它:
<div className={styles.yourClassName}></div>