如图,实际上是存在的,但是ts就会报找不到模块
//index.tsx
import * as React from "react";
import styled from "./styled.scss";
class Header extends React.Component {
constructor(props: any) {
super(props);
}
render() {
return (
<div className={styled.header}>
<i className="fa fa-bars" aria-hidden="true" />
<span />
<i className="fa fa-search" aria-hidden="true" />
</div>
);
}
}
export default Header;
但是把import styled from "./styled.scss"; 改成import "./styled.scss";就没问题
我重新建立了一个react项目 不加载ts同样的方法是不会报错
我在webpack开启了模块化的,这是webpack部分配置 代码太长就不放上来了
//webpack
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
isEnvDevelopment && require.resolve('style-loader'),
isEnvProduction && {
loader: MiniCssExtractPlugin.loader,
options: Object.assign({},
shouldUseRelativeAssetPaths ? {
publicPath: '../../'
} : undefined
),
},
{
loader: require.resolve('css-loader'),
options: cssOptions,
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebook/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
require('postcss-preset-env')({
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
}),
],
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
},
},
].filter(Boolean);
if (preProcessor) {
loaders.push({
loader: require.resolve(preProcessor),
options: {
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
},
});
}
return loaders;
};
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders({
importLoaders: 2,
sourceMap: isEnvProduction ?
shouldUseSourceMap : isEnvDevelopment,
modules: true,
getLocalIdent: getCSSModuleLocalIdent,
},
'sass-loader'
),
sideEffects: true,
},
{
test: sassModuleRegex,
use: getStyleLoaders({
importLoaders: 2,
sourceMap: isEnvProduction ?
shouldUseSourceMap : isEnvDevelopment,
modules: true,
getLocalIdent: getCSSModuleLocalIdent,
},
'sass-loader'
),
},
ts配置
//tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"allowSyntheticDefaultImports": true,
"outDir": "build/dist",
"module": "commonjs",
"target": "es5",
"lib": ["es2015", "dom"],
"sourceMap": true,
// "allowJs": true,
"jsx": "react",
"moduleResolution": "node",
"rootDir": "src",
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"importHelpers": true,
"strictNullChecks": true,
"experimentalDecorators": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true,
"paths": {
"@/*": ["./src/*"]
}
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"build",
"scripts",
"acceptance-tests",
"webpack",
"jest",
"util",
"module",
"src/setupTests.ts"
]
}
能看下你的
tsconfig.json
吗?