![New axobject-query Maintainer Faces Backlash Over Controversial Decision to Support Legacy Node.js Versions](https://cdn.sanity.io/images/cgdhsj6q/production/86e6ebdea652d20da070ebbda20134b839972db7-1024x1024.webp?w=800&fit=max&auto=format)
Security News
New axobject-query Maintainer Faces Backlash Over Controversial Decision to Support Legacy Node.js Versions
A JavaScript library maintainer is under fire after merging a controversial PR to support legacy versions of Node.js.
webpack
Advanced tools
Package description
Webpack is a powerful module bundler for JavaScript applications. It processes applications by internally building a dependency graph which maps every module your project needs and generates one or more bundles. It is highly extensible via loaders and plugins, and it's designed to manage, transform, and bundle frontend assets like JavaScript, CSS, and images.
Module Bundling
Webpack bundles all the JavaScript files and other assets like CSS and images into a single output file. The code sample shows a basic webpack configuration defining an entry point and the output bundle.
module.exports = {
entry: './path/to/my/entry/file.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'my-first-webpack.bundle.js'
}
};
Loaders
Loaders allow webpack to process different types of files and convert them into modules that can be included in your bundle. The code sample demonstrates how to use loaders to handle .txt and .css files.
module.exports = {
module: {
rules: [
{ test: /\.txt$/, use: 'raw-loader' },
{ test: /\.css$/, use: ['style-loader', 'css-loader'] }
]
}
};
Plugins
Plugins can be leveraged to perform a wider range of tasks like bundle optimization, asset management, and environment variable injection. The code sample shows how to use the HtmlWebpackPlugin to generate an index.html file with the bundled assets injected.
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
plugins: [new HtmlWebpackPlugin({ template: './src/index.html' })]
};
Development Server
Webpack provides a development server that can be used to serve your application during development. It supports live reloading. The code sample configures the webpack development server to serve files from the 'dist' directory.
module.exports = {
devServer: {
contentBase: './dist',
open: true
}
};
Code Splitting
Code splitting allows you to split your code into various bundles which can then be loaded on demand or in parallel. The code sample shows how to split the application and vendor code into separate bundles.
module.exports = {
entry: {
app: './src/app.js',
vendor: './src/vendor.js'
},
output: {
filename: '[name].bundle.js',
path: __dirname + '/dist'
}
};
Rollup is a module bundler for JavaScript which uses a flat bundle approach that's more efficient for libraries and applications with a complex module structure. It's known for its tree-shaking capabilities, which eliminate unused code.
Parcel is a web application bundler that offers a zero-configuration setup. It's known for its fast bundle times and out-of-the-box support for many file types without the need for additional plugins or loaders.
Browserify lets you require('modules') in the browser by bundling up all of your dependencies. It's been around longer than webpack and has a simpler approach, but it lacks some of the more advanced features and optimizations that webpack offers.
FuseBox is a bundler/module loader that combines the power of webpack, JSPM, and SystemJS. It introduces a streamlined workflow and has a powerful API. It's known for its speed and simplicity.
Readme
As developer you want to reuse existing code.
As with node.js and web all file are already in the same language, but it is extra work to use your code with the node.js module system and the browser.
The goal of webpack
is to bundle CommonJs modules into javascript files which can be loaded by <script>
-tags.
Simply concating all required files has a disadvantage: many code to download (and execute) on page load.
Therefore webpack
uses the require.ensure
function (CommonJs/Modules/Async/A) to split your code automatically into multiple bundles which are loaded on demand.
This happens mostly transparent to the developer with a single function call. Dependencies are resolved for you.
The result is a smaller inital code download which results in faster page load.
TL;DR
// a.js
var b = require("./b");
b.stuff("It works");
// b.js
exports.stuff = function(text) {
console.log(text);
}
are compiled to
(/* small webpack header */)
({
0: function(module, exports, require) {
var b = require(1);
b.stuff("It works");
},
1: function(module, exports, require) {
exports.stuff = function(text) {
console.log(text);
}
}
})
var a = require("a");
var b = require("b");
require.ensure(["c"], function(require) {
require("b").xyz();
var d = require("d");
});
File 1: web.js
- code of module a and dependencies
- code of module b and dependencies
File 2: 1.web.js
- code of module c and dependencies (but code is not used)
- code of module d and dependencies
See details for exact output.
Somethings it happens that browsers require other code than node.js do.
webpack
allow module developers to specify replacements which are used in the compile process of webpack
.
Modules in web_modules
replace modules in node_modules
.
filename.web.js
replaces filename.js
when required without file extention.
TODO specify replacements in options
If the require
d module is not known while compile time we get into a problem.
A solution is the method require.context
which takes a directory as parameter
and returns a function which behaves like the require
function issued from a file
in this directory (but only if used for files in that directory).
We have a directory full of templates, which are compiled javascript files. A template should be loaded by template name.
var requireTemplate = require.context("./templates");
function getTemplate(templateName) {
return requireTemplate("./" + templateName);
}
In addition to that webpack
uses the require.context
function automatically
if you use variables or other non-literal things in the require
function.
That means the following code behaves like the above:
function getTemplate(templateName) {
return require("./templates/" + templateName);
}
// is compiled like: return require.context("./templates")("./"+templateName)
See details for complete example.
When try to store the require
function in another variable or try to pass it as parameter,
webpack
convert it to a require.context(".")
to be combatible.
There is a warning emitted in this case.
Warning: The complete code in the directory are included. So use it carefully.
require
-functionAs dependencies are resolved before running:
require
should not be overwritten by variable declaration (var require = ...
), by function parameter is allowed function(require) {...}
.require.ensure
should not be overwritten or called indirectrequire.context
should not be overwritten or called indirectrequire.context
should be a literal or addition of multiple literalsrequire
should access a file in current directory: This throws an exception: var r = require; r("../file");
The following cases could result in too much code in result file if used wrong:
require
: var r = require; r("./file");
require.context
. It includes the whole directory.require(variable)
, require(condition ? "a" : "b")
(TODO)require.ensure
is not inlined in the call.As node.js specific modules like fs
will not work in browser they are not included and cause an error.
You should replace them by own modules if you want to use them.
web_modules
fs
path
...
TODO provide some replacements
webpack
offers a command line interface:
after npm install webpack -g
you can use the webpack
command
if invoked without arguments it prints a usage:
Usage: webpack <options> <input> <output>
Options:
--single Disable Code Splitting [boolean] [default: false]
--min Minimize it with uglifyjs [boolean] [default: false]
--filenames Output Filenames Into File [boolean] [default: false]
--options Options JSON File [string]
--script-src-prefix Path Prefix For JavaScript Loading [string]
--libary Stores the exports into this variable [string]
--colors Output Stats with colors [boolean] [default: false]
webpack(context, moduleName, [options], callback)
webpack(absoluteModulePath, [options], callback)
options
you can save this options object in a JSON file and use it with the shell command.
outputJsonpFunction
JSONP function used to load chunks
scriptSrcPrefix
Path from where chunks are loaded
outputDirectory
write files to this directory (absolute path)
output
write first chunk to this file
outputPostfix
write chunks to files named chunkId plus outputPostfix
libary
exports of input file are stored in this variable
minimize
minimize outputs with uglify-js
includeFilenames
add absolute filenames of input files as comments
callback
function(err, source / stats)
source
if options.output
is not set
else stats
as json see example
webpack
as originally intended as fork for webmake
for @medikoo so it shared several ideas with it.
So big credit goes to medikoo.
However webpack
has big differences:
webpack
replaces module names and paths with numbers. webmake
don't do that and do resolves requires on client-side.
This design of webmake
was intended to support variables as arguments to require calls.
webpack
resolves requires in compile time and have no resolve code on client side. This results in smaller bundles.
Variables as arguments will be handled different and with more limitations in webpack
.
Another limitation in webmake
which are based on the previous one is that modules must be in the current package scope.
In webpack
this is not a restriction.
There is no require.context
in webmake
. Therefore there is a forced include list in options which allows modules to be required even if the names were not available at compile time.
The design of webmake
causes all modules with the same name to overlap.
This can be problematic if different submodules rely on specific versions of the same module.
The behaivior also differs from the behaivior of node.js, because node.js installs a module for each instance in submodules and webmake
cause them the merge into a single module which is only installed once.
In webpack
this is not the case.
Different versions do not overlap and modules are installed multiple times.
But in webpack
this can (currently) cause duplicate code if a module is used in multiple modules.
I want to face this issue (TODO).
webmake
do (currently) not support Code Splitting.
But medikoo said he works at some related feature.
You can run the unit tests with npm test
.
You can run the browser tests:
cd test/browsertests
node build
and open test.html
in browser. There must be several OKs in the file and no FAIL.
TODO more tests
You are welcome to contribute by writing issues or pull requests.
You are also welcome to correct any spelling mistakes or any language issues, because my english is not so good...
FAQs
Packs ECMAScript/CommonJs/AMD modules for the browser. Allows you to split your codebase into multiple bundles, which can be loaded on demand. Supports loaders to preprocess files, i.e. json, jsx, es7, css, less, ... and your custom stuff.
The npm package webpack receives a total of 20,838,186 weekly downloads. As such, webpack popularity was classified as popular.
We found that webpack demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
A JavaScript library maintainer is under fire after merging a controversial PR to support legacy versions of Node.js.
Security News
Results from the 2023 State of JavaScript Survey highlight key trends, including Vite's dominance, rising TypeScript adoption, and the enduring popularity of React. Discover more insights on developer preferences and technology usage.
Security News
The US Justice Department has penalized two consulting firms $11.3 million for failing to meet cybersecurity requirements on federally funded projects, emphasizing strict enforcement to protect sensitive government data.