首页 > 解决方案 > 如何将第三方模块声明为全局模块,这样我就不需要导入了?(带有 typescript 的 Webpack5)

问题描述

在我的 React with Webpack 项目中,我将一些模块声明为全局变量,这样我就不必每次想使用它们时都导入它们。

在我的 Webpack 文件中:

plugins: [
        new webpack.ProvidePlugin({
            '_': 'lodash',
            'React': 'react',
            'moment': 'moment'
        })
   ]

现在我可以在任何地方使用 _,React,moment 而不显式导入它。

将 Typescript 添加到项目后,我收到如下错误:

'moment' refers to a UMD global, but the current file is a module. Consider adding an import instead.

'_' refers to a UMD global, but the current file is a module. Consider adding an import instead.

我的 tsconfig 文件:

{
"compilerOptions": {
    "jsx": "react-jsx",
    "allowSyntheticDefaultImports": true,
    "module": "commonjs",
    "noImplicitAny": true,
    "outDir": "./build/",
    "preserveConstEnums": true,
    "removeComments": true,
    "sourceMap": true,
    "target": "es5"
},
"include": [
    "src/index.tsx"
  ]
}

我如何告诉 typescript 这些库已经是全球性的并且它们存在?

标签: reactjstypescriptwebpack

解决方案


设法通过将以下内容添加到我的 tsconfig 文件来解决此问题

"allowUmdGlobalAccess": true,

推荐阅读