Webpack interview questions
13 questions with answers. 105 open jobs in India ask for Webpack.
NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack
Webpack and Browserify
Webpack and Browserify do pretty much the same job, which is processing your code to be used in a target environment (mainly browser, though you can target other environments like Node). Result of such processing is one or more bundles - assembled scripts suitable for targeted environment.
For example, let's say you wrote ES6 code divided into modules and want to be able to run it in a browser. If those modules are Node modules, the browser won't understand them since they exist only in the Node environment. ES6 modules also won't work in older browsers like IE11. Moreover, you might have used experimental language features (ES next proposals) that browsers don't implement yet so running such script would just throw errors. Tools like Webpack and Browserify solve these problems by translating such code to a form a browser is able to execute. On top of that, they make it possible to apply a huge variety of optimisations on those bundles.
However, Webpack and Browserify differ in many ways, Webpack offers many tools by default (e.g. code splitting), while Browserify can do this only after downloading plugins but using both leads to very similar results. It comes down to personal preference (Webpack is trendier). Btw, Webpack is not a task runner, it is just processor of your files (it processes them by so called loaders and plugins) and it can be run (among other ways) by a task runner.
Webpack Dev Server
Webpack Dev Server provides a similar solution to Browsersync - a development server where you can deploy your app rapidly as you are working on it, and verify your development progress immediately, with the dev server automatically refreshing the browser on code changes or even propagating changed code to browser without reloading with so called hot module replacement.
Task runners vs NPM scripts
I've been using Gulp for its conciseness and easy task writing, but have later found out I need neither Gulp nor Grunt at all. Everything I have ever needed could have been done using NPM scripts to run 3rd-party tools through their API. Choosing between Gulp, Grunt or NPM scripts depends on taste and experience of your team.
While tasks in Gulp or Grunt are easy to read even for people not so familiar with JS, it is yet another tool to require and learn and I personally prefer to narrow my dependencies and make things simple. On the other hand, replacing these tasks with the combination of NPM scripts and (propably JS) scripts which run those 3rd party tools (eg. Node script configuring and running rimraf for cleaning purposes) might be more challenging. But in the majority of cases, those three are equal in terms of their results.
Examples
As for the examples, I suggest you have a look at this React starter project, which shows you a nice combination of NPM and JS scripts covering the whole build and deploy process. You can find those NPM scripts in
package.jsonin the root folder, in a property namedscripts. There you will mostly encounter commands likebabel-node tools/run start. Babel-node is a CLI tool (not meant for production use), which at first compiles ES6 filetools/run(run.js file located in tools) - basically a runner utility. This runner takes a function as an argument and executes it, which in this case isstart- another utility (start.js) responsible for bundling source files (both client and server) and starting the application and development server (the dev server will be probably either Webpack Dev Server or Browsersync).Read the rest at the sourceFrom Stack Overflow: asked by VB_, answered by Daniel Macak (CC BY-SA 4.0)
where is create-react-app webpack config and files?
If you want to find webpack files and configurations go to your package.json file and look for scripts
You will find that scripts object is using a library react-scripts
Now go to node_modules and look for react-scripts folder react-script-in-node-modules
This react-scripts/scripts and react-scripts/config folder contains all the webpack configurations.
From Stack Overflow: asked by Mohammad, answered by Vikram Thakur (CC BY-SA 4.0)
What exactly is Hot Module Replacement in Webpack?
First I want to note that Hot Module Replacement (HMR) is still an experimental feature.
HMR is a way of exchanging modules in a running application (and adding/removing modules). You basically can update changed modules without a full page reload.
Documentation
Prerequirements:
- Using Plugins: https://webpack.js.org/concepts/plugins/
- Code Splitting: https://webpack.js.org/guides/code-splitting/
- webpack-dev-server: https://webpack.js.org/configuration/dev-server/
It's not so much for HMR, but here are the links:
- Example: https://webpack.js.org/guides/hot-module-replacement/
- API: https://webpack.js.org/concepts/hot-module-replacement/
I'll add these answers to the documentation.
How does it work?
From the app view
The app code asks the HMR runtime to check for updates. The HMR runtime downloads the updates (async) and tells the app code that an update is available. The app code asks the HMR runtime to apply updates. The HMR runtime applies the updates (sync). The app code may or may not require user interaction in this process (you decide).
From the compiler (webpack) view
In addition to the normal assets, the compiler needs to emit the "Update" to allow updating from a previous version to this version. The "Update" contains two parts:
- the update manifest (json)
- one or multiple update chunks (js)
The manifest contains the new compilation hash and a list of all update chunks (2).
The update chunks contain code for all updated modules in this chunk (or a flag if a module was removed).
The compiler additionally makes sure that module and chunk ids are consistent between these builds. It uses a "records" json file to store them between builds (or it stores them in memory).
From the module view
HMR is an opt-in feature, so it only affects modules that contains HMR code. The documentation describes the API that is available in modules. In general, the module developer writes handlers that are called when a dependency of this module is updated. They can also write a handler that is called when this module is updated.
In most cases, it's not mandatory to write HMR code in every module. If a module has no HMR handlers, the update bubbles up. This means a single handler can handle updates for a complete module tree. If a single module in this tree is updated, the complete module tree is reloaded (only reloaded, not transferred).
From the HMR runtime view (technical)
Additional code is emitted for the module system runtime to track module
parentsandchildren.On the management side, the runtime supports two methods:
checkandapply.A
checkdoes a HTTP request to the update manifest. When this request fails, there is no update available. Elsewise the list of updated chunks is compared to the list of currently-loaded chunks. For each loaded chunk, the corresponding update chunk is downloaded. All module updates are stored in the runtime as updates. The runtime switches into thereadystate, meaning an update has been downloaded and is ready to be applied.For each new chunk request in the ready state, the update chunk is also downloaded.
The
applymethod flags all updated modules as invalid. For each invalid module, there needs to be an update handler in the module or update handlers in every parent. Else the invalid bubbles up and marks all parents as invalid too. This process continues until no more "bubble up" occurs. If it bubbles up to an entry point, the process fails.Read the rest at the sourceFrom Stack Overflow: asked by Dan Abramov, answered by Tobias K. (CC BY-SA 4.0)
What does "publicPath" in Webpack do?
output.pathLocal disk directory to store all your output files (Absolute path).
Example:
path.join(__dirname, "build/")Webpack will output everything into
localdisk/path-to-your-project/build/output.publicPathWhere your browser can access uploaded bundled files. (absolute path, or relative to main HTML file)
Example:
/assets/Assumed you deployed the app at server root
http://server/.By using
/assets/, the app will find webpack assets at:http://server/assets/. Under the hood, every urls that webpack encounters will be re-written to begin with "/assets/".src="picture.jpg"Re-writes ➡src="/assets/picture.jpg"Accessed by: (
http://server/assets/picture.jpg)src="/img/picture.jpg"Re-writes ➡src="/assets/img/picture.jpg"Accessed by: (
http://server/assets/img/picture.jpg)From Stack Overflow: asked by Misha Moroshko, answered by Kevin Law (CC BY-SA 4.0)
Webpack style-loader vs css-loader
The CSS loader takes a CSS file and returns the CSS with
importsandurl(...)resolved via webpack'srequirefunctionality:var css = require("css!./file.css"); // => returns css code from file.css, resolves imports and url(...)It doesn't actually do anything with the returned CSS.
The style loader takes CSS and actually inserts it into the page so that the styles are active on the page.
They perform different operations, but it's often useful to chain them together, like Unix pipes. For example, if you were using the Less CSS preprocessor, you could use
require("style!css!less!./file.less")to
- Turn
file.lessinto plain CSS with the Less loader - Resolve all the
importsandurl(...)s in the CSS with the CSS loader - Insert those styles into the page with the style loader
From Stack Overflow: asked by Anvesh Checka, answered by Michelle Tilley (CC BY-SA 3.0)
- Turn
What does this "react-scripts eject" command do?
npm run ejectNote: this is a one-way operation. Once you
eject, you can’t go back!If you aren’t satisfied with the build tool and configuration choices, you can
ejectat any time. This command will remove the single build dependency from your project.Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except
ejectwill still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.You don’t have to ever use
eject. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.Alternatives to Ejecting
Ejecting lets you customize anything, but from that point on you have to maintain the configuration and scripts yourself. This can be daunting if you have many similar projects. In such cases instead of ejecting we recommend to fork
react-scriptsand any other packages you need. This article dives into how to do it in depth. You can find more discussion in this issue.From Stack Overflow: asked by Ishan Patel, answered by Sergii (CC BY-SA 4.0)
What are differences between SystemJS and Webpack?
If you go to the SystemJS Github page, you will see the description of the tool:
Universal dynamic module loader - loads ES6 modules, AMD, CommonJS and global scripts in the browser and NodeJS.
Because you use modules in TypeScript or ES6, you need a module loader. In the case of SystemJS, the
systemjs.config.jsallows us to configure the way in which module names are matched with their corresponding files.This configuration file (and SystemJS) is necessary if you explicitly use it to import the main module of your application:
<script> System.import('app').catch(function(err){ console.error(err); }); </script>When using TypeScript, and configuring the compiler to the
commonjsmodule, the compiler creates code that is no longer based on SystemJS. In this example, the typescript compiler config file would appear like this:{ "compilerOptions": { "target": "es5", "module": "commonjs", // <------ "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "removeComments": false, "noImplicitAny": false } }Webpack is a flexible module bundler. This means that it goes further and doesn't only handle modules but also provides a way to package your application (concat files, uglify files, ...). It also provides a dev server with load reload for development.
SystemJS and Webpack are different but with SystemJS, you still have work to do (with Gulp or SystemJS builder for example) to package your Angular2 application for production.
From Stack Overflow: asked by smartmouse, answered by Thierry Templier (CC BY-SA 4.0)
What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?
This is related to
compactoption of Babel compiler, which commands to "not include superfluous whitespace characters and line terminators. When set to 'auto' compact is set to true on input sizes of >100KB." By default its value is "auto", so that is probably the reason you are getting the warning message. See Babel documentation.You can change this option from Webpack using a query parameter. For example:
loaders: [ { test: /\.js$/, loader: 'babel', query: {compact: false} } ]From Stack Overflow: asked by Johan Alkstål, answered by rst (CC BY-SA 3.0)
Vue CLI CSS pre-processor option: dart-sass VS node-sass?
Update 09/17/2020:
As this answer gets up-votes every day, I thought maybe it is worth diving deeper into this topic.
Considering sass-lang website:
Dart Sass is the primary implementation of Sass, which means it gets new features before any other implementation. It's fast, easy to install, and it compiles to pure JavaScript which makes it easy to integrate into modern web development workflows.
Dart-Sass is fast, but not the JS compiled version. Practically when we say Dart-Sass there are two options:
- Dart-Sass on Dart-VM
- Dart-Sass on NPM which is pure JS compiled version
I compiled Bootstrap 4 Sass file to CSS with Node-Sass, Dart-Sass and Dart-Sass(JS) and you can see the following result:
- In this particular case, two seconds is not a big deal; but consider Dart-Sass(JS) is nine times slower than Dart-Sass(Dart VM) and three times slower than node-sass.
- I had a project with +20 themes, it took 30 seconds with node-sass, but I tried to use Dart-Sass(JS), and it took a century!
- Although Dart-Sass(Dart VM) is the fastest but installing or integrating it is a bit tricky.
- And Node-Sass is considered deprecated.
I blogged about it here, you can read more about it here.
From Stack Overflow: asked by ux.engineer, answered by Ali Bahrami (CC BY-SA 4.0)
How to Polyfill node core modules in webpack 5?
I was also getting these errors when upgrading from webpack v4 to v5. Resolved by making the following changes to
webpack.config.jsAdded resolve.fallback property
Removed node property
{ resolve: { modules: [...], fallback: { "fs": false, "tls": false, "net": false, "path": false, "zlib": false, "http": false, "https": false, "stream": false, "crypto": false, "crypto-browserify": require.resolve('crypto-browserify'), //if you want to use this module also don't forget npm i crypto-browserify } }, entry: [...], output: {...}, module: { rules: [...] }, plugins: [...], optimization: { minimizer: [...], }, // node: { // fs: 'empty', // net: 'empty', // tls: 'empty' // }, }upgrade from v4 to v5 => https://webpack.js.org/migrate/5/#clean-up-configuration
From Stack Overflow: asked by Saber, answered by Maqsood Ahmed (CC BY-SA 4.0)
How to copy static files to build directory with Webpack?
Requiring assets using the file-loader module is the way webpack is intended to be used (source). However, if you need greater flexibility or want a cleaner interface, you can also copy static files directly using my
copy-webpack-plugin(npm, Github). For yourstatictobuildexample:const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { context: path.join(__dirname, 'your-app'), plugins: [ new CopyWebpackPlugin({ patterns: [ { from: 'static' } ] }) ] };Compatibility note: If you're using an old version of webpack like
webpack@4.x.x, usecopy-webpack-plugin@6.x.x. Otherwise use latest.From Stack Overflow: asked by Vitalii Korsakov, answered by kevlened (CC BY-SA 4.0)
How to add fonts to create-react-app based projects?
There are two options:
Using Imports
This is the suggested option. It ensures your fonts go through the build pipeline, get hashes during compilation so that browser caching works correctly, and that you get compilation errors if the files are missing.
As described in “Adding Images, Fonts, and Files”, you need to have a CSS file imported from JS. For example, by default
src/index.jsimportssrc/index.css:import './index.css';A CSS file like this goes through the build pipeline, and can reference fonts and images. For example, if you put a font in
src/fonts/MyFont.woff, yourindex.cssmight include this:@font-face { font-family: 'MyFont'; src: local('MyFont'), url(./fonts/MyFont.woff) format('woff'); /* other formats include: 'woff2', 'truetype, 'opentype', 'embedded-opentype', and 'svg' */ }Notice how we’re using a relative path starting with
./. This is a special notation that helps the build pipeline (powered by Webpack) discover this file.Normally this should be enough.
Using
publicFolderIf for some reason you prefer not to use the build pipeline, and instead do it the “classic way”, you can use the
publicfolder and put your fonts there.The downside of this approach is that the files don’t get hashes when you compile for production so you’ll have to update their names every time you change them, or browsers will cache the old versions.
If you want to do it this way, put the fonts somewhere into the
publicfolder, for example, intopublic/fonts/MyFont.woff. If you follow this approach, you should put CSS files intopublicfolder as well and not import them from JS because mixing these approaches is going to be very confusing. So, if you still want to do it, you’d have a file likepublic/index.css. You would have to manually add<link>to this stylesheet frompublic/index.html:<link rel="stylesheet" href="%PUBLIC_URL%/index.css">And inside of it, you would use the regular CSS notation:
@font-face { font-family: 'MyFont'; src: local('MyFont'), url(fonts/MyFont.woff) format('woff'); }Notice how I’m using
fonts/MyFont.woffas the path. This is becauseindex.cssis in thepublicfolder so it will be served from the public path (usually it’s the server root, but if you deploy to GitHub Pages and set yourhomepagefield tohttp://myuser.github.io/myproject, it will be served from/myproject). Howeverfontsare also in thepublicfolder, so they will be served fromfontsrelatively (eitherhttp://mywebsite.example/fontsorhttp://myuser.github.io/myproject/fonts). Therefore we use the relative path.Note that since we’re avoiding the build pipeline in this example, it doesn’t verify that the file actually exists. This is why I don’t recommend this approach. Another problem is that our
index.cssfile doesn’t get minified and doesn’t get a hash. So it’s going to be slower for the end users, and you risk the browsers caching old versions of the file.Which Way to Use?
Go with the first method (“Using Imports”). I only described the second one since that’s what you attempted to do (judging by your comment), but it has many problems and should only be the last resort when you’re working around some issue.
From Stack Overflow: asked by Maxim Veksler, answered by Dan Abramov (CC BY-SA 4.0)
How do I generate sourcemaps when using babel and webpack?
In order to use source map, you should change
devtooloption value fromtrueto the value which available inthis list, for instancesource-mapdevtool: 'source-map'devtool:'source-map'- A SourceMap is emitted.From Stack Overflow: asked by user916367, answered by Oleksandr T. (CC BY-SA 3.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Stack Overflowby its contributors, named on each answerCC BY-SA13 questions