React+Typescript+Webpack4: 找不到模块 '***.json'

React+Typescript+Webpack4: Cannot find module '***.json'

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

import data from "data/mockup.json"

但我得到了错误

Cannot find module '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

在 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 and Typescript@2.7.2

希望对您有所帮助!!!

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

参考文献 2:https://github.com/Microsoft/TypeScript-React-Starter/issues/12

虽然答案有助于将 JSON 文件作为模块加载,但它们在许多方面存在局限性

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

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

P.S。所附图片来自谈论同一主题的教程点击here查看更多

个人观点,取消评论:

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

在文件 tsconfig.json 中成功了。

我找到了提示 here