【问题标题】:React+Typescript+Webpack4: Cannot find module '***.json'React+Typescript+Webpack4:找不到模块“***.json”
【发布时间】:2024-05-20 20:35:01
【问题描述】:

我正在尝试使用以下方法从 .tsx 中的 .json 文件导入数据:

import data from "data/mockup.json"

但我得到了错误

找不到模块'data/mockup.json'

我的 webpack 配置如下所示:

const babelLoader = {
    loader: 'babel-loader',
    options: {
        cacheDirectory: true,
        presets: [
            ["@babel/preset-env", {
                "targets": {
                    "browsers": ["last 2 versions", "safari >= 7"]
                },
                "modules": true
            }]
        ]
    }
};

module.exports = {
    entry: {...},
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.json'],
        alias: {
            data: path.resolve(__dirname, 'src/app/data')
        }
    },
    output: {...},
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                exclude: /node_modules/,
                use: [
                    babelLoader,
                    {
                        loader: 'ts-loader'
                    }
                ]
            },
            {
                test: /\.js$/,
                exclude: /node_modules\/(?!(dom7|swiper)\/).*/,
                use: [
                    babelLoader
                ]
            }
        ]
    },
    ...
}
enter code here

我认为 .json 默认是内置在 webpack4 中的,所以我的 webpack 配置可能有问题?

使用的版本: 网络包:v4.4.1 打字稿:2.7.2

【问题讨论】:

    标签: webpack-4


    【解决方案1】:

    个人,取消注释:

        "allowSyntheticDefaultImports": true   /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */,
    

    在文件tsconfig.json 中成功了。

    我找到了提示here

    【讨论】:

      【解决方案2】:

      虽然答案有助于将 JSON 文件作为模块加载,但它们在很多方面都受到限制

      • 第一:打字稿默认可以加载JSON文件,你只需要在下面一行添加tsconfig.json

         {
            ...
        
            "resolveJsonModule": true,
        
            ...
         }
        
      • 第二个:建议的解决方案将隐式启用类型检查和自动完成

      附注所附图片来自一个讨论相同主题的教程点击here查看更多

      【讨论】:

        【解决方案3】:

        在 d.ts 文件中声明模块

        declare module "*.json"
        

        在编译器选项的 tsconfig.json 中添加一个字段

        "typeRoots": [ "node_modules/@types", "./typings.d.ts" ],
        

        现在导入文件 (.tsx)

        import * as data from "./dat/data.json";
        

        Webpack@4.4.1 和 Typescript@2.7.2

        希望对你有帮助!!!

        参考1:https://www.typescriptlang.org/docs/handbook/react-&-webpack.html

        Ref2:https://github.com/Microsoft/TypeScript-React-Starter/issues/12

        【讨论】: