webpack ReactJs需要'fs'

ruarlubt  于 2022-12-13  发布在  Webpack
关注(0)|答案(3)|浏览(167)

我已经

import fs from 'fs'

在我的package.json中,我有
然后运行命令

>  npm i fs
>  fs@0.0.2 node_modules/fs

接下来在React存储中导入'fs'模块

import fs from 'fs'

但是当我尝试使用fs
除了constructor和一些其他的__方法之外,我没有看到其他的方法。我没有看到createReadStream方法或任何其他的文件操作方法。
有没有人知道出了什么问题?(使用Webpack)并可以根据要求给予更多信息,但我已经走了这么远...
ps:为什么我可以npm i fs --保存当我读到其他帖子时,我不必这样做(使用节点5. 5. 0)

import Reflux from 'reflux'
import AddItemActions from '../actions/AddItemActions'
import request from  'superagent-bluebird-promise'
import fs from 'fs'

var ImageStore = Reflux.createStore({
  init(){
    .
    .
    .
  },

  decryptImage(file) {
    var reader = new FileReader();
    var info = {}
    reader.onload = (output) => {
      debugger
      request.post("https://camfind.p.mashape.com/image_requests")
        .set("X-Mashape-Key", "KEY")
        .set("Content-Type", "application/x-www-form-urlencoded")
        .set("Accept", "application/json")
        .send({'focus': { 'x': 480}})
        .send({'focus': { 'y': 640}})
        .send({'image_request': {'altitude': 27.912109375}})
        .send({'image_request': {'language': "en"}})
        .send({'image_request': {'latitude': 35.8714220766008}})
        .send({'image_request': {'locale' : "en_US"}})
        .send({'image_request': {'longitude': 14.3583203002251}})
        .send({'image_request': {'image': fs.createReadStream("/path" + 'file.jpg')}})
        .then(function (result) {
          console.log(result.status, result.headers, result.body);
          this.info = result
        },
          function(error) {
            console.log(error);
        })
    }

    reader.readAsDataURL(file);
    return info
  },
  .
  .
  .
  .
})
v8wbuo2f

v8wbuo2f1#

create-react-app中,他们已经清除了'fs'。你不能导入它。他们这样做是因为fs是一个节点核心模块。
你必须找到另一个解决这个问题的方法。参见this ticket.

ipakzgxi

ipakzgxi2#

这可能是一个环境问题。浏览器不可能解释和运行一些节点服务器端模块,如fs
解决方案是在节点环境(服务器端)中运行fs方法,或者找到一个提供相同功能但为浏览器编写的包。
在此问题中讨论... Module not found: Error: Cannot resolve module 'fs'
这个问题...

fquxozlt

fquxozlt3#

npm i babel-plugin-preval
尽管浏览器不允许在运行时访问文件系统,您可以在React中使用prevail在构建时将内容从文件系统读入内存,如下所示

// loading content of text file into react project during build time.
// which means everytime text content is changed, you need to rebuild the project to get the updated content.
const greetingContent = preval`
  const fs = require('fs')
  module.exports = fs.readFileSync(require.resolve('./greeting.txt'), 'utf8')
`
console.log(greetingContent);

相关问题