Working with options

The term options in Webpack refers to settings made from the command line rather than the configuration, which is done through the altering of configuration script.

In the following example, we will begin by altering the configuration file, simply to lay the groundwork for our options tutorial.

Throughout the following configuration, Node's path module is used and prefixed with the _dirname global variable. Node's path module is simply the utility that Node uses for working with file or directory paths. There may be file path problems when working between operating systems, and this prevents those problems from occurring and also ensures that relative paths work correctly.

The file concerned in the example is called webpack.config.js. We will use it to set the mode of the project, and we need to do this before we get to the options:

const path = require('path');

module.exports = {
  mode: "production", // "production" | "development" | "none"
entry: "./app/entry", // string | object | array

In the preceding code block, the chosen mode instructs Webpack to make use of its built-in optimizations accordingly. The entry path will default to ./src. This is where the execution of the application begins and bundling will start.

The following code block will show the rest of the same file:

output: {
path: path.resolve(__dirname, "dist"), // string

filename: "bundle.js", // string
publicPath: "/assets/", // string
library: "MyLibrary", // string,

libraryTarget: "umd", // universal module definition },

This section of the code snippets shows options related to how Webpack emits results.


The target directory for all output files must be an absolute path (use the Node.js path module).

filename indicates the filename template for entry chunks, and publicPath refers to the Uniform Resource Locator (URL) to the output directory, resolved relative to the relevant HTML page. Put simply, this means the file path from the HTML page you may be using to the bundled project files. The remainder of the code refers to the name of the exported library and the nature of the exported library.

The following topic concerns configuration regarding modules. After working on output options, this will be the next logical step in project development:

module: { 
rules: [
{ test: /.jsx?$/, include: [ path.resolve(__dirname, "app") ], exclude: [ path.resolve(__dirname, "app/demo-files") ],

The preceding code block includes rules for modules, such as parser options and the configuration of loaders. These are matching conditions, and each accepts a string or a regular expression. The term test has the same behavior as include. They both must be matched, but this is not the case for exclude. exclude takes preference over the test and include options.

For best practice, RegExp should only be used in test when filenames match. When using arrays of paths, absolute paths should be used in preference to the include and exclude options. The include option should be preferred over the exclude method:

issuer: { test, include, exclude },
enforce: "pre", enforce: "post",
loader: "babel-loader",
options: { presets: ["es2015"] },
}, { test: /.html$/, use: [ "htmllint-loader",
{ loader: "html-loader", options: { / ... / } } ] },

The preceding code block includes conditions for the issuer, and the origin of the imported elements. The code also includes options to flag the application of these rules, even if they are overridden. This is an advanced option, however.

The reference to loader indicates which loader should be applied. This resolves relative to the contextual location. A loader suffix is no longer optional since Webpack 2, for the sake of clarity. There is also space for applying multiple further options and loaders.

In the same configuration, we will explore rules and conditions that can be applied within the same procedure, illustrated in the following code block:

{ oneOf: [ / rules / ] },
{ rules: [ / rules / ] },
{ resource: { and: [ / conditions / ] } },
{ resource: { or: [ / conditions / ] } },
{ resource: [ / conditions / ] },
{ resource: { not: / condition / } }], /* Advanced module configuration */ }, resolve: {

The preceding code block includes nested rules, all of which combine with conditions to be useful. By way of explanation, note each of the following commands and what they denote:

  • and option matches are only made if all conditions are also matched.
  • or matches apply when a condition is matched—this is the default for arrays.
  • not indicates if the condition is not matched.

There is also an option for resolving module requests; this does not apply to the resolving of loaders. The following example shows the use of this resolve module request:

modules: [
      "node_modules",
      path.resolve(__dirname, "app")
    ], extensions: [".js", ".json", ".jsx", ".css"], 
alias: {
"module": "new-module",
"only-module$": "new-module",
"module": path.resolve(__dirname, "app/third/module.js"), },
}, performance: { hints: "warning", // enum maxAssetSize: 200000, // int (in bytes), maxEntrypointSize: 400000, // int (in bytes) assetFilter: function(assetFilename) {
return assetFilename.endsWith('.css') || assetFilename.endsWith('.js'); } },

The preceding code block shows the same configuration file we have been following up to now in this section. However, let's take a look at some key elements. Where it states path.resolve, this refers to directories in which to look for modules. Directly below this, where it states ], extensions:, this refers to file extensions that are used.

After this part is code that, in descending order, refers to a list of module name aliases. Modules' aliases are imported relative to the current location context, as illustrated in the following code block:

devtool: "source-map", // enum
context: __dirname, // string (absolute path!)
target: "web", // enum
externals: ["react", /^@angular/],
serve: { //object port: 1337, content: './dist', // ... },
stats: "errors-only",

The devtool configuration enhances debugging by adding metadata for the browser. Note that the source-map option can be more detailed, but this is at the expense of build speed, and the web option indicates the home directory for Webpack. The entry and module.rules.loader option is resolved relative to this directory and refers to the environment in which the bundle should run. The serve configuration lets you provide options for webpack-serve and lets you precisely control which bundle information gets displayed, such as the following:

devServer: { proxy: { // proxy URLs to backend development server '/api': 'http://localhost:3000' },
    contentBase: path.join(__dirname, 'public'), 
    compress: true, 
    historyApiFallback: true, 
    hot: true, 
    https: false, 
    noInfo: true, 

  },
  plugins: [

  ],
  // list of additional plugins

Let's explain the preceding code block. Where it states compress: true, this enables gzip compression of contents. The historyApiFallback: true part is true for when encountering any 404 page-loading errors. The hot: true text refers to having hot module replacement permissible or not; this is subject to HotModuleReplacementPlugin being installed first. https should be set to true for self-signed objects or certificate-authorized objects. If the noInfo key is set to true, you will only get errors and warnings on hot reloads.

The configuration is done, and we can now run a build. To do this, use the following command:

npx webpack-cli init

Once the preceding code is run in the command-line environment, the user might be prompted to install @webpack-cli/init, if it is not yet installed in the project.

After running npx webpack-cli init, more packages may be installed in the project, depending on the choices made during the configuration generation. The following code block shows the printout from running NPX Webpack's CLI initialization:

npx webpack-cli init

 INFO For more information and a detailed description of each question, have a look at https://github.com/webpack/webpack-cli/blob/master/INIT.md
 INFO Alternatively, run `webpack(-cli) --help` for usage info.

 Will your application have multiple bundles? No
 Which module will be the first to enter the application? [default: ./src/index]
 Which folder will your generated bundles be in? [default: dist]:
 Will you be using ES2015? Yes
 Will you use one of the below CSS solutions? No

  [email protected]
  [email protected]
  [email protected]
  @babel/[email protected]
  [email protected]
  @babel/[email protected]
  [email protected]
  added 124 packages from 39 contributors, updated 4 packages and audited 
25221 packages in 7.463s found 0 vulnerabilities Congratulations! Your new webpack configuration file has been created
!

If your output in the CLI looks like the preceding code block, then your configuration has been successful. It's essentially an automated readout from the command line and should signify that all the options set in the previous code block have been recorded.

We have gone through configurations and options, and you should now know the difference and the extent to which each can be used. It's now a natural process to move on to asset management.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.19.31.73