如何使tsconfig与webpack提供的插件配合使用?

4
我有一个简单的组件,使用了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"]
}
1个回答

1

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

"allowUmdGlobalAccess": true

2
这个不起作用。 - VimNing
1
没有一些解释,这个答案并不是很有用。 - Slbox

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接