【问题标题】:React Typescript - Webpack externals module can not findReact Typescript - Webpack 外部模块找不到
【发布时间】:2020-04-25 22:39:17
【问题描述】:

我使用带有 typescript 模板的 create-react-app 创建了一个 react 应用程序,并运行了弹出命令。

我只需要从外部 json 文件中获取配置并从应用程序中的任何位置的组件文件中读取它。 所以我做了以下更改以使用 webpack config json

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}

webpack.configjson // 加载外部配置文件

 externals: {
      'Configurator': JSON.stringify(process.env.NODE_ENV === 'production' ? require('./config.prod.json') : require('./config.dev.json'))
    }

Ts 文件

import Configurator from 'Configurator';

但它给出了以下错误

【问题讨论】:

    标签: reactjs typescript webpack


    【解决方案1】:

    您需要更改此行并确保您的 config.*.js 文件正在导出模块:

    externals: {
      'Configurator': JSON.stringify(process.env.NODE_ENV) === 'production' ? path.resolve(__dirname, 'config.prod.js') : path.resolve(__dirname, 'config.dev.js')
    }
    

    尝试将以下内容添加到您的 tsconfig.json

    {
      "compilerOptions": {
        "baseUrl": ".",
        ...
      },
      ...
    }
    

    您也可以尝试使用非相对路径进行导入,因为这会降低 webpack 和 tsconfig 的复杂性,然后您可以删除 webpack 外部配置并执行类似操作。

    在 webpack.config

    中
    ...
    plugins: [new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    })],
    ...
    

    然后像这样导入:

    const config = process.env.NODE_ENV === 'production' ? require('../config.prod.js') : require('../config.dev.js')
    

    【讨论】:

    • 仍然是Cannot find module 'Configurator'. 问题
    • 可能需要把json文件改成导出模块的js文件?
    • @JanithWidarshana 您是否有任何理由不使用相对导入配置?即 import Configurator from '../config.dev.js' 我认为问题出在您的 tsconfig 上,因为 typscript 不知道在哪里可以找到模块,它会在 node_modules 中查找非相对导入
    • 我将我的 tsconfig.json 文件添加到问题中。
    猜你喜欢
    • 2021-09-13
    • 1970-01-01
    • 2018-05-23
    • 2017-04-09
    • 1970-01-01
    • 2020-01-23
    • 2016-01-20
    • 1970-01-01
    • 2017-07-23
    相关资源
    最近更新 更多