首页 > 解决方案 > 如何使 tsconfig 与 webpack 提供插件一起使用?

问题描述

我有使用的简单组件styled-componentsutils.tsx包含主题颜色的文件。我通过 WebpackProvidePlugin 加载它,因为我不想在每个组件文件中包含 React 和 styled-components 模块。它可以正常工作、渲染、编译,但我在控制台和编辑器中有一些 TS 错误,因为 typescript 编译器/解析器无法识别 webpack 别名

TS2686:“React”指的是一个 UMD 全局,但当前文件是一个模块。考虑改为添加导入。

TS2304:找不到名称“样式化”。

TS2304:找不到名称“颜色”。

导航.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"]
}

标签: reactjstypescriptwebpacktslinttsconfig

解决方案


一种方法是进入您的 tsconfig.json 并设置:

"allowUmdGlobalAccess": true

推荐阅读