Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

webpack-4

I am trying to import the data from a .json file in a .tsx using following:

import data from "data/mockup.json"

but I got the error

Cannot find module 'data/mockup.json'

My webpack config looks like this:

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

I think the .json is built in webpack4 by default so there may be something wrong with my webpack config?

Version used: webpack: v4.4.1 typescript: 2.7.2

like image 294
ayashi33 Avatar asked May 05 '18 02:05

ayashi33


2 Answers

declare module in d.ts file

declare module "*.json"

Add a field in tsconfig.json in compiler options

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

Now import into file (.tsx)

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

[email protected] and [email protected]

Hope this helps!!!

Ref1: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html

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

like image 127
Ampati Hareesh Avatar answered Oct 16 '22 00:10

Ampati Hareesh


Although answers are helpful to load the JSON file as a module, they are limited in many aspects

  • First: the typescript can load by default JSON files, you only need to add into tsconfig.json below line:

     {
        ...
    
        "resolveJsonModule": true,
    
        ...
     }
    
  • second: the suggested solution will enable implicitly for type check and auto-completion

enter image description here

P.S. the attached image is from a tutorial that talks about the same subject click here to check more

like image 39
AbuDawood Avatar answered Oct 16 '22 00:10

AbuDawood