Home > Net >  How does webpack access file system and write files?
How does webpack access file system and write files?

Time:06-02

I can't figure out from webpack's website or from their package dependencies how webpack actually reads and writes files on the local file system.

I would also like to write some automation script to process some of the source code files, and could borrow from how webpack works.

Do they have some binary already packaged in library? Then how does that run cross platform? Is it running on Node? Please enlighten me!

CodePudding user response:

Is it running on Node?

Yes it is a Node.js library/package.

How Webpack actually reads and writes files on the local file system?

It makes use of native fs module to read and write files. To watch files continuously for changes during the dev mode, it makes use of watchpack. Further, if you are using Webpack Dev Server, then it doesn't write output files to file system. It keeps them in-memory and using connect like middleware serve the files from memory.

...to process some of the source code files

Webpack makes use of acorn library to parse the JavaScript AST for understanding the JS syntax.

I would also like to write some automation script...

If you intend to process some source code files, you have two options - loaders and plugins. Loaders work at individual file level and go through a loader pipeline. Think of it like a code-transpiler where a file in one language is converted into another or similar language (typescript to JS for example). Loaders are stateless and relatively simple to implement. E.g., sass-loader will convert SCSS into CSS which will be then passed through css-loader to resolve all the @import statements.

Plugins, on the other hand, are more advanced but complex to implement. Plugins work on whole compilation process level and achieve this by tapping into the compiler hooks/events. So when you need to deal with more than one file at any time, then plugin is probably the way to go. For example, CSS extraction plugin needs to extract CSS from multiple files into a single file. You will need plugin for that.

  • Related