我有一个简单的组件,使用了
styled-components
以及包含主题颜色的utils.tsx
文件。我通过WebpackProvidePlugin加载它,因为我不想在每个组件文件中都包含React和styled-components模块。它可以正常工作、渲染和编译,但是在控制台和编辑器中出现了一些TS错误,因为typescript编译器/解析器无法识别webpack别名。
TS2686: 'React'指的是UMD全局变量,但当前文件是一个模块。考虑添加import。
TS2304: 找不到名称'Styled'。
TS2304: 找不到名称'Color'。
Navigation.tsx
const Nav = Styled.nav`
height: 64px;
background-color: ${Color.darkBlue};
`
function Navigation() {
return <Nav>dwa</Nav>
}
export default Navigation
webpack.config.js
...
new webpack.ProvidePlugin({
React: 'react',
Device: [
path.resolve(path.join(__dirname, 'src/utils/utils.tsx')),
'devices',
],
Color: [
path.resolve(path.join(__dirname, 'src/utils/utils.tsx')),
'colors',
],
Styled: ['styled-components', 'default'],
}),
...
tsconfig.json
{
"compilerOptions": {
"module": "none",
"moduleResolution": "node",
"jsx": "react",
"target": "es6",
"lib": ["es2015", "dom", "dom.iterable"],
"sourceMap": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"plugins": [{"name": "typescript-tslint-plugin"}],
"baseUrl": "./",
"paths": {
"components/*": ["src/components/*"],
"utils/*": ["src/utils/*"]
}
},
"include": ["src/**/*.tsx"],
"exclude": ["node_modues"]
}