简体   繁体   中英

Cannot find module 'redux' (or any other module)

I have a react app that works with webpack using TypeScript (2.7.2). I keep receiving this error for some reason:

Uncaught Error: Cannot find module 'redux'
at webpackEmptyContext (store_sync:2)
at eval (index.js:19)
at eval (index.js:7)
at Object.eval (index.js:15)
at eval (index.js:41)
at Object../app/store/index.js (993f4d11644a7f5254ac.js:3512)
at __webpack_require__ (bundle.js:780)
at fn (bundle.js:148)
at eval (main.tsx:8)
at Object../main.tsx (993f4d11644a7f5254ac.js:3547)

Even if I try to require any of the modules, non work and all of them throw this error message.

This is my tsconfig.json file:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "preserveConstEnums": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "removeComments": true,
    "noUnusedLocals": true,
    "noImplicitReturns": true,
    "jsx": "react",
    "sourceMap": true,
    "declaration": false,
    "noLib":false,
    "outDir": "build",
    "allowSyntheticDefaultImports": true,
    "lib": ["es5","es6", "dom", "es2015.promise"]

  },
  "fileGlob" : [
    "src/main.tsx",
    "src/app/**/*.ts",
    "src/app/**/*.tsx"
  ],
  "exclude": [
    "node_modules/@types/react-redux/index.d.ts",
    "views",
    "build",
    "src/statics/**/*.tsx",
    "src/statics/**/*.ts",
    "server/**"
  ]
}

and my packages.json file:

    {
  "name": "anayst-station-3.1.1",
  "version": "1.0.0",
  "private": true,
  "description": "Analyst Station 3.1.1",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack -p --progress --colors",
    "format": "prettier --write \"src/**/*.{ts,tsx,css}\"",
    "frontend": "webpack-dev-server --mode development --hot --progress --color --port 8080 --open",
    "backend": "babel-node ./server/analystStation.js --presets es2015,stage-2",
    "start": "concurrently --kill-others \"npm run frontend\" \"npm run backend\""
  },
  "license": "MIT",
  "devDependencies": {
    "@types/classnames": "2.2.4",
    "@types/history": "4.6.2",
    "@types/node": "10.3.2",
    "@types/react": "16.3.17",
    "@types/react-dom": "16.0.6",
    "@types/react-redux": "6.0.2",
    "@types/react-router": "4.0.26",
    "@types/react-router-redux": "^5.0.15",
    "@types/redux-actions": "2.3.0",
    "@types/webpack": "4.4.0",
    "@types/webpack-env": "1.13.6",
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.4",
    "css-loader": "^0.28.11",
    "file-loader": "^1.1.11",
    "html-loader": "^1.0.0-alpha.0",
    "html-webpack-plugin": "^4.0.0-alpha",
    "mini-css-extract-plugin": "^0.4.0",
    "postcss": "^6.0.22",
    "postcss-browser-reporter": "^0.5.0",
    "postcss-cssnext": "^3.1.0",
    "postcss-import": "^11.1.0",
    "postcss-loader": "^2.1.5",
    "postcss-reporter": "^5.0.0",
    "postcss-url": "^7.3.2",
    "prettier": "^1.13.5",
    "react-hot-loader": "^4.3.1",
    "redux-devtools-extension": "^2.13.2",
    "style-loader": "^0.21.0",
    "ts-loader": "^4.4.1",
    "typescript": "^2.9.1",
    "url-loader": "^1.0.1",
    "webpack": "^4.12.0",
    "webpack-cleanup-plugin": "^0.5.1",
    "webpack-cli": "^3.0.3",
    "webpack-dev-server": "^3.1.4"
  },
  "dependencies": {
    "@babel/plugin-syntax-decorators": "^7.0.0-beta.51",
    "@babel/plugin-syntax-jsx": "^7.0.0-beta.51",
    "@babel/plugin-syntax-typescript": "^7.0.0-beta.51",
    "@types/mongoose": "^5.0.18",
    "@types/redux": "^3.6.31",
    "@types/tedious": "^1.8.33",
    "azure-storage": "^2.10.0",
    "babel-cli": "^6.26.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",
    "classnames": "^2.2.6",
    "compression": "^1.7.2",
    "concurrently": "^3.6.0",
    "connect-mongo": "^2.0.1",
    "connect-roles": "^3.1.2",
    "dogapi": "^2.8.0",
    "express": "^4.16.3",
    "express-session": "^1.15.6",
    "helmet": "^3.12.1",
    "hsts": "^2.1.0",
    "json2csv": "^4.1.5",
    "jsonwebtoken": "^8.3.0",
    "moment": "^2.22.2",
    "mongodb-migrations": "^0.8.5",
    "mongoose": "^5.1.7",
    "mssql": "^4.1.0",
    "node-cache": "^4.2.0",
    "node-schedule": "^1.3.0",
    "nodemailer": "^4.6.7",
    "nodemailer-smtp-transport": "^2.7.4",
    "nodemon": "^1.17.5",
    "npm-run-all": "^4.1.3",
    "passport": "^0.4.0",
    "passport-local": "^1.0.0",
    "path": "^0.12.7",
    "react": "^16.4.0",
    "react-dom": "^16.4.0",
    "react-redux": "^5.0.7",
    "react-router": "^4.3.1",
    "react-router-redux": "^5.0.0-alpha.9",
    "redux": "^4.0.0",
    "redux-actions": "^2.4.0",
    "request-ip": "^2.0.2",
    "tedious": "^2.6.1",
    "validator": "^10.4.0",
    "winston": "^2.2.0"
  }
}

I run my "Frontend" script and everything compiles, but in my browsers console I see that error. I also see this in my Terminal as a warning:

WARNING in ./app/models/index.js 7:24-31
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

My webpack.config.js file

var webpack = require('webpack');
var path = require('path');

// variables
var isProduction = process.argv.indexOf('-p') >= 0 || process.env.NODE_ENV === 'production';
var sourcePath = path.join(__dirname, './src');
var outPath = path.join(__dirname, './dist');

// plugins
var HtmlWebpackPlugin = require('html-webpack-plugin');
var MiniCssExtractPlugin = require('mini-css-extract-plugin');
var WebpackCleanupPlugin = require('webpack-cleanup-plugin');

module.exports = {
  context: sourcePath,
  entry: {
    app: './main.tsx'
  },
  output: {
    path: outPath,
    filename: 'bundle.js',
    chunkFilename: '[chunkhash].js',
    publicPath: '/'
  },
  target: 'web',
  resolve: {
    extensions: ['.js', '.ts', '.tsx', '.jsx'],
    // Fix webpack's default behavior to not load packages with jsnext:main module
    // (jsnext:main directs not usually distributable es6 format, but es6 sources)
    mainFields: ['module', 'browser', 'main'],
    alias: {
      app: path.resolve(__dirname, 'src/app/')
    }
  },
  module: {
    rules: [
      {
        test: /\.(ts|tsx)$/,
        use:{
          loader: 'ts-loader',
          options: {
            transpileOnly: true
          }
        }
      },
      /* {
         test: /\.tsx?$/,
         exclude: ['/src/statics/'],
         use: [
           isProduction && {
             loader: 'babel-loader',
             options: { plugins: ['react-hot-loader/babel'] }
           },
           'ts-loader'
         ].filter(Boolean)
       },
*/

      {
        test: /\.(js|jsx)$/,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015'],
          compact:false
        }
      }
     ,
      // css
      {
        test: /\.css$/,
        use: [
          isProduction ? MiniCssExtractPlugin.loader : 'style-loader',
          {
            loader: 'css-loader',
            query: {
              modules: true,
              sourceMap: !isProduction,
              importLoaders: 1,
              localIdentName: isProduction ? '[hash:base64:5]' : '[local]__[hash:base64:5]'
            }
          },
          {
            loader: 'postcss-loader',
            options: {
              ident: 'postcss',
              plugins: [
                require('postcss-import')({ addDependencyTo: webpack }),
                require('postcss-url')(),
                require('postcss-cssnext')(),
                require('postcss-reporter')(),
                require('postcss-browser-reporter')({
                  disabled: isProduction
                })
              ]
            }
          }
        ]
      },
      // static assets
      { test: /\.html$/, use: 'html-loader' },
      { test: /\.(png|svg)$/, use: 'url-loader?limit=10000' },
      { test: /\.(jpg|gif)$/, use: 'file-loader' }
    ]
  },
  optimization: {
    splitChunks: {
      name: true,
      cacheGroups: {
        commons: {
          chunks: 'initial',
          minChunks: 2
        },
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          chunks: 'all',
          priority: -10
        }
      },

    },
    runtimeChunk: true
  },
  plugins: [
    new webpack.EnvironmentPlugin({
      NODE_ENV: 'development', // use 'development' unless process.env.NODE_ENV is defined
      DEBUG: false
    }),
    new WebpackCleanupPlugin(),
    new MiniCssExtractPlugin({
      filename: '[contenthash].css',
      disable: !isProduction
    }),
    new HtmlWebpackPlugin({
      template: 'assets/index.html'
    })
  ],
  devServer: {
    contentBase: sourcePath,
    hot: true,
    inline: true,
    historyApiFallback: {
      disableDotRule: true
    },
    stats: 'minimal'
  },
  node: {
    // workaround for webpack-dev-server issue
    // https://github.com/webpack/webpack-dev-server/issues/60#issuecomment-103411179
    fs: 'empty',
    net: 'empty'
  }
};

This is my file importing the libraries

import { Store, createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import { routerMiddleware } from 'react-router-redux';
import { History } from 'history';
import { logger } from '../../app/middleware';
import { RootState, rootReducer } from '../../app/reducers';

export function configureStore(history: History, initialState?: RootState): Store<RootState> {
  let middleware = applyMiddleware(logger, routerMiddleware(history));

  if (process.env.NODE_ENV !== 'production') {
    middleware = composeWithDevTools(middleware);
  }

  const store = createStore(rootReducer as any, initialState as any, middleware) as Store<RootState>;

  if (module.hot) {
    module.hot.accept('app/reducers', () => {
      const nextReducer = require('app/reducers');
      store.replaceReducer(nextReducer);
    });
  }

  return store;
}

What am I missing?

The problem, as the error describe, is that you are trying to use a module which does not exist from redux . Store is not a module which redux's export.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM