Hwaryong
Hwaryong

Reputation: 119

Unable to require 'fs' with Vue CLI 3

I am developing a scheduling software for Windows 10, using Vue CLI 3.

The app needs to use "fs" module, but .. I could not find the way. There is no webpack config file anywhere. How can I solve the problem?

Vue CLI 3 is so different that I cannot use all the ways introduced at stackoverflow.

Please, help me.

Upvotes: 11

Views: 34736

Answers (2)

Sergeon
Sergeon

Reputation: 6788

using FS module while bootstrapping the app

You can use fs when bootstrapping the application. For instance you could read a file in your file system to grab something, then add it to the application to use it somehow. If this is what you want (I doubt), you can just setup something like the following in your vue.config.js:

const fs = require('fs');

const someFileContents = fs.readFileSync('my-path-to-the-file');

module.exports = {
  lintOnSave: true,

  configureWebpack: config => {
    return {
      plugins: [
        new webpack.DefinePlugin({
          'somevar': someFileContents,
        })
      ]
    }
  },
}

And now, whenever you write somevar in your web app code, webpack will had it replaced -at compile time- with the contents of the file. This may have some uses I think, but never did it.

Using FS module in browser

Due to security reasons, you cannot use the fs module in the browser: you won't be able to setup a Vue component that lists filesystem items or write to disk. It is not a webpack, node nor Vue issue, it is due to security limitations of browsers. The native fs module of node.js talks to OS low level API's, and the browser can't access them.

should javascript be able to modify or read filesystems, a lot of devastating pretty bad security screw ups will arise.

The FileSystem API

Now, there is this pretty new browser API, the FileSystem API.

It does not allow to access user filesystem, yet it somehow simulates a sandboxed folder where your web application can store files. It may be useful for you depending on your use case, but does not have the greatest browser support.

 Webpack configuration

There is no webpack config file anywhere.

In fact, all your webpack stuff in a vue-cli 3 app should be done via the vue.config.js file: https://cli.vuejs.org/guide/webpack.html.

There you can execute arbitrary node.js code (in fact you can call fs from there, as said before, since it is code running on your machine, not in the browser).

Upvotes: 26

Gonzalo Lorieto
Gonzalo Lorieto

Reputation: 645

Add this to the webpack conf:

node: {
  fs: "empty"
}

As @Sergeon stated, fs is not for browser usage.

Upvotes: 0

Related Questions