Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

reactjs - Module not found: Error: Cannot resolve module 'fs'

I'm making a react app using Babel and Webpack and I want to use the file-exists package from npm. I already installed and saved the package as a dependency for my project. After running npm start I get this error:

ERROR in ./~/file-exists/index.js
Module not found: Error: Cannot resolve module 'fs' in C:GitHubCryptoPrices ode_modulesfile-exists
@ ./~/file-exists/index.js 3:9-22

file-exists uses fs as a dependency but for some reason it is not working. Npm starts and runs without any issues if I don't require file-exists anywhere.

here is my webpack config file:

module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      // exclude: /node_modules/,
      loader: 'babel',
      query: {
        presets: ['react', 'es2015', 'stage-1']
      }
    }]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
};

I'm new to Webpack and Babel so I'm a little bit lost.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It looks like you're calling the fs file-exists method in your index.js file. I'm not sure in what context you're calling the method, but this looks like a client-side call to a server-side method. I ran into a similar issue just recently.

From what I understand, the main issue seems to be that you can't call server-side (Node) methods in browser-interpreted client-side (front end) code. You have to call them from a server.

Webpack can load the fs module code into your front end, but the browser can't actually interpret those Node methods and run them; only a Node environment can do that. (more here)

You could fix the core issue by modifying the call to fs methods to happen somewhere server-side, or by finding an equivalent browser-supported package that offers the same functionality as the fs methods you need but that can be run in a browser.

A quick search for "fs module for browser" brings up a variety of options that might work for what you need, like fs-web, browserify-fs or filer.

Here is a similar question with some insight. Use fs module in React.js,node.js, webpack, babel,express


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...