我正在尝试从 CSS 模块导入主题,但 TypeScript 给我一个“找不到模块”错误,并且主题未在运行时应用。我认为我的 Webpack 配置有问题,但我不确定问题出在哪里。
我正在使用以下工具:
"typescript": "^2.0.3"
"webpack": "2.1.0-beta.25"
"webpack-dev-server": "^2.1.0-beta.9"
"react": "^15.4.0-rc.4"
"react-toolbox": "^1.2.3"
"node-sass": "^3.10.1"
"style-loader": "^0.13.1"
"css-loader": "^0.25.0"
"sass-loader": "^4.0.2"
"sass-lint": "^1.9.1"
"sasslint-webpack-plugin": "^1.0.4"
这是我的webpack.config.js
var path = require('path');
var webpack = require('webpack');
var sassLintPlugin = require('sasslint-webpack-plugin');
module.exports = {
entry: [
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/dev-server',
'./src/index.tsx',
],
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: 'http://localhost:8080/',
filename: 'dist/bundle.js',
},
devtool: 'source-map',
resolve: {
extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js'],
},
module: {
rules: [{
test: /\.js$/,
loader: 'source-map-loader',
exclude: /node_modules/,
enforce: 'pre',
}, {
test: /\.tsx?$/,
loader: 'tslint-loader',
exclude: /node_modules/,
enforce: 'pre',
}, {
test: /\.tsx?$/,
loaders: [
'react-hot-loader/webpack',
'awesome-typescript-loader',
],
exclude: /node_modules/,
}, {
test: /\.scss$/,
loaders: ['style', 'css', 'sass']
}, {
test: /\.css$/,
loaders: ['style', 'css']
}],
},
externals: {
'react': 'React',
'react-dom': 'ReactDOM'
},
plugins: [
new sassLintPlugin({
glob: 'src/**/*.s?(a|c)ss',
ignoreFiles: ['src/normalize.scss'],
failOnWarning: false, // Do it.
}),
new webpack.HotModuleReplacementPlugin(),
],
devServer: {
contentBase: './'
},
};
和我尝试导入的 App.tsx
:
import * as React from 'react';
import { AppBar } from 'react-toolbox';
import appBarTheme from 'react-toolbox/components/app_bar/theme.scss'
// local ./theme.scss stylesheets aren't found either
interface IAppStateProps {
// No props yet
}
interface IAppDispatchProps {
// No state yet
}
class App extends React.Component<IAppStateProps & IAppDispatchProps, any> {
constructor(props: IAppStateProps & IAppDispatchProps) {
super(props);
}
public render() {
return (
<div className='wrapper'>
<AppBar title='My App Bar' theme={appBarTheme}>
</AppBar>
</div>
);
}
}
export default App;
启用类型安全样式表模块导入还需要什么?
最佳答案
TypeScript 不知道除 .ts
或 .tsx
之外还有其他文件,因此如果导入的文件后缀未知,它将抛出错误。
如果你有一个 webpack 配置允许你导入其他类型的文件,你必须告诉 TypeScript 编译器这些文件存在。为此,请添加一个声明文件,您可以在其中声明具有合适名称的模块。
要声明的模块内容取决于用于文件类型的 webpack 加载器。在通过 sass-loader → css-loader → style-loader 传输 *.scss
文件的 webpack 配置中,导入的模块中不会有任何内容,正确的模块声明应该是这样的:
// declaration.d.ts
declare module '*.scss';
如果加载器是为 css-modules 配置的,只需像这样扩展声明:
// declaration.d.ts
declare module '*.scss' {
const content: Record<string, string>;
export default content;
}
关于typescript - 无法导入 CSS/SCSS 模块。 typescript 说 "Cannot Find Module",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40382842/