A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://webpack.js.org/api/module-methods/ below:

Module Methods | webpack

This section covers all methods available in code compiled with webpack. When using webpack to bundle your application, you can pick from a variety of module syntax styles including ES6, CommonJS, and AMD.

While webpack supports multiple module syntaxes, we recommend following a single syntax for consistency and to avoid odd behaviors/bugs. Actually webpack would enforce the recommendation for .mjs files, .cjs files or .js files when their nearest parent package.json file contains a "type" field with a value of either "module" or "commonjs". Please pay attention to these enforcements before you read on:

ES6 (Recommended)

Version 2 of webpack supports ES6 module syntax natively, meaning you can use import and export without a tool like babel to handle this for you. Keep in mind that you will still probably need babel for other ES6+ features. The following methods are supported by webpack:

import

Statically import the exports of another module.

import MyModule from './my-module.js';
import { NamedExport } from './other-module.js';
warning

The keyword here is statically. A normal import statement cannot be used dynamically within other logic or contain variables. See the spec for more information and import() below for dynamic usage.

You can also import Data URI:

import 'data:text/javascript;charset=utf-8;base64,Y29uc29sZS5sb2coJ2lubGluZSAxJyk7';
import {
  number,
  fn,
} from 'data:text/javascript;charset=utf-8;base64,ZXhwb3J0IGNvbnN0IG51bWJlciA9IDQyOwpleHBvcnQgY29uc3QgZm4gPSAoKSA9PiAiSGVsbG8gd29ybGQiOw==';
export

Export anything as a default or named export.


export var Count = 5;
export function Multiply(a, b) {
  return a * b;
}


export default {
  
};
import()

function(string path):Promise

Dynamically load modules. Calls to import() are treated as split points, meaning the requested module and its children are split out into a separate chunk.

tip

The ES2015 Loader spec defines import() as method to load ES2015 modules dynamically on runtime.

if (module.hot) {
  import('lodash').then((_) => {
    
  });
}
warning

This feature relies on Promise internally. If you use import() with older browsers, remember to shim Promise using a polyfill such as es6-promise or promise-polyfill.

Dynamic expressions in import()

It is not possible to use a fully dynamic import statement, such as import(foo). Because foo could potentially be any path to any file in your system or project.

The import() must contain at least some information about where the module is located. Bundling can be limited to a specific directory or set of files so that when you are using a dynamic expression - every module that could potentially be requested on an import() call is included. For example, import(`./locale/${language}.json`) will cause every .json file in the ./locale directory to be bundled into the new chunk. At run time, when the variable language has been computed, any file like english.json or german.json will be available for consumption.


const language = detectVisitorLanguage();
import(`./locale/${language}.json`).then((module) => {
  
});
tip

Using the webpackInclude and webpackExclude options allows you to add regex patterns that reduce the number of files that webpack will bundle for this import.

Magic Comments

Inline comments to make features work. By adding comments to the import, we can do things such as name our chunk or select different modes. For a full list of these magic comments see the code below followed by an explanation of what these comments do.


import(
  
  
  
  
  'module'
);


import(
  
  
  
  
  
  
  `./locale/${language}`
);

import( 'ignored-module.js');
webpackIgnore

JavaScript Usage

Disables dynamic import parsing when set to true.

When using import.meta.url, it does not remain as-is; instead, it gets replaced based on the baseURI. For modules, it is replaced with new URL("./", import.meta.url), and for other cases, it defaults to document.baseURI. This ensures that relative URLs work correctly, aligning with the base URL context.

import( 'ignored-module.js');

new URL( 'file1.css', import.meta.url);
warning

Note that setting webpackIgnore to true opts out of code splitting.

CSS Usage

The webpackIgnore comment can control whether webpack processes a specific import or URL reference. It works in certain cases out of the box but doesn’t support all cases by default due to performance reasons.

We support webpackIgnore in the following cases:

@import  url(./basic.css);

.class {
  color: red;
  background:  url('./url/img.png');
}

.class {
  background-image: image-set(
     url(./url/img1x.png) 1x,
    url(./url/img2x.png) 2x,
    url(./url/img3x.png) 3x
  );
}
tip

For other CSS scenarios, css-loader fully supports webpackIgnore, allowing more flexibility if needed.

webpackChunkName

A name for the new chunk. Since webpack 2.6.0, the placeholders [index] and [request] are supported within the given string to an incremented number or the actual resolved filename respectively. Adding this comment will cause our separate chunk to be named [my-chunk-name].js instead of [id].js.

webpackFetchPriority5.87.0+

Set fetchPriority for specific dynamic imports. It's also possible to set a global default value for all dynamic imports by using the module.parser.javascript.dynamicImportFetchPriority option.

import(
  
  'path/to/module'
);
webpackMode

Since webpack 2.6.0, different modes for resolving dynamic imports can be specified. The following options are supported:

webpackPrefetch

Tells the browser that the resource is probably needed for some navigation in the future. Check out the guide for more information on how webpackPrefetch works.

webpackPreload

Tells the browser that the resource might be needed during the current navigation. Check out the guide for more information on how webpackPreload works.

tip

Note that all options can be combined like so /* webpackMode: "lazy-once", webpackChunkName: "all-i18n-data" */. This is wrapped in a JavaScript object and executed using node VM. You do not need to add curly brackets.

webpackInclude

A regular expression that will be matched against during import resolution. Only modules that match will be bundled.

webpackExclude

A regular expression that will be matched against during import resolution. Any module that matches will not be bundled.

tip

Note that webpackInclude and webpackExclude options do not interfere with the prefix. eg: ./locale.

webpackExports

Tells webpack to only bundle the specified exports of a dynamically import()ed module. It can decrease the output size of a chunk. Available since webpack 5.0.0-beta.18.

warning

webpackExports cannot be used with destructuring assignments.

CommonJS

The goal of CommonJS is to specify an ecosystem for JavaScript outside the browser. The following CommonJS methods are supported by webpack:

require
require(dependency: String);

Synchronously retrieve the exports from another module. The compiler will ensure that the dependency is available in the output bundle.

var $ = require('jquery');
var myModule = require('my-module');

It's possible to enable magic comments for require as well, see module.parser.javascript.commonjsMagicComments for more.

warning

Using it asynchronously may not have the expected effect.

require.resolve
require.resolve(dependency: String);

Synchronously retrieve a module's ID. The compiler will ensure that the dependency is available in the output bundle. It is recommended to treat it as an opaque value which can only be used with require.cache[id] or __webpack_require__(id) (best to avoid such usage).

warning

Module ID's type can be a number or a string depending on the optimization.moduleIds configuration.

See module.id for more information.

require.cache

Multiple requires of the same module result in only one module execution and only one export. Therefore a cache in the runtime exists. Removing values from this cache causes new module execution and a new export.

warning

This is only needed in rare cases for compatibility!

var d1 = require('dependency');
require('dependency') === d1;
delete require.cache[require.resolve('dependency')];
require('dependency') !== d1;

require.cache[module.id] === module;
require('./file.js') === module.exports;
delete require.cache[module.id];
require.cache[module.id] === undefined;
require('./file.js') !== module.exports; 
require.cache[module.id] !== module;
require.ensure warning

require.ensure() is specific to webpack and superseded by import().

require.ensure(
  dependencies: String[],
  callback: function(require),
  errorCallback: function(error),
  chunkName: String
)

Split out the given dependencies to a separate bundle that will be loaded asynchronously. When using CommonJS module syntax, this is the only way to dynamically load dependencies. Meaning, this code can be run within execution, only loading the dependencies if certain conditions are met.

warning

This feature relies on Promise internally. If you use require.ensure with older browsers, remember to shim Promise using a polyfill such as es6-promise or promise-polyfill.

var a = require('normal-dep');

if (module.hot) {
  require.ensure(['b'], function (require) {
    var c = require('c');

    
  });
}

The following parameters are supported in the order specified above:

warning

Although the implementation of require is passed as an argument to the callback function, using an arbitrary name e.g. require.ensure([], function(request) { request('someModule'); }) isn't handled by webpack's static parser. Use require instead, e.g. require.ensure([], function(require) { require('someModule'); }).

AMD

Asynchronous Module Definition (AMD) is a JavaScript specification that defines an interface for writing and loading modules. The following AMD methods are supported by webpack:

define (with factory)
define([name: String], [dependencies: String[]], factoryMethod: function(...))

If dependencies are provided, factoryMethod will be called with the exports of each dependency (in the same order). If dependencies are not provided, factoryMethod is called with require, exports and module (for compatibility!). If this function returns a value, this value is exported by the module. The compiler ensures that each dependency is available.

warning

Note that webpack ignores the name argument.

define(['jquery', 'my-module'], function ($, myModule) {
  

  
  return function doSomething() {
    
  };
});
warning

This CANNOT be used in an asynchronous function.

define (with value)
define(value: !Function)

This will export the provided value. The value here can be anything except a function.

define({
  answer: 42,
});
warning

This CANNOT be used in an async function.

require (amd-version)
require(dependencies: String[], [callback: function(...)])

Similar to require.ensure, this will split the given dependencies into a separate bundle that will be loaded asynchronously. The callback will be called with the exports of each dependency in the dependencies array.

warning

This feature relies on Promise internally. If you use AMD with older browsers (e.g. Internet Explorer 11), remember to shim Promise using a polyfill such as es6-promise or promise-polyfill.

require(['b'], function (b) {
  var c = require('c');
});
warning

There is no option to provide a chunk name.

Labeled Modules

The internal LabeledModulesPlugin enables you to use the following methods for exporting and requiring within your modules:

export label

Export the given value. The label can occur before a function declaration or a variable declaration. The function name or variable name is the identifier under which the value is exported.

export: var answer = 42;
export: function method(value) {
  
};
warning

Using it in an async function may not have the expected effect.

require label

Make all exports from the dependency available in the current scope. The require label can occur before a string. The dependency must export values with the export label. CommonJS or AMD modules cannot be consumed.

some-dependency.js

export: var answer = 42;
export: function method(value) {
  
};
require: 'some-dependency';
console.log(answer);
method(...);
Webpack

Aside from the module syntaxes described above, webpack also allows a few custom, webpack-specific methods:

require.context
require.context(
  (directory: String),
  (includeSubdirs: Boolean) ,
  (filter: RegExp) ,
  (mode: String) 
);

Specify a whole group of dependencies using a path to the directory, an option to includeSubdirs, a filter for more fine grained control of the modules included, and a mode to define the way how loading will work. Underlying modules can then be resolved later on:

var context = require.context('components', true, /\.html$/);
var componentA = context.resolve('componentA');

If mode is set to 'lazy', the underlying modules will be loaded asynchronously:

var context = require.context('locales', true, /\.json$/, 'lazy');
context('localeA').then((locale) => {
  
});

The full list of available modes and their behavior is described in import() documentation.

require.include
require.include((dependency: String));

Include a dependency without executing it. This can be used for optimizing the position of a module in the output chunks.

require.include('a');
require.ensure(['a', 'b'], function (require) {
  
});
require.ensure(['a', 'c'], function (require) {
  
});

This will result in the following output:

Without require.include('a') it would be duplicated in both anonymous chunks.

require.resolveWeak

Similar to require.resolve, but this won't pull the module into the bundle. It's what is considered a "weak" dependency.

if (__webpack_modules__[require.resolveWeak('module')]) {
  
}
if (require.cache[require.resolveWeak('module')]) {
  
}



const page = 'Foo';
__webpack_modules__[require.resolveWeak(`./page/${page}`)];
tip

require.resolveWeak is the foundation of universal rendering (SSR + Code Splitting), as used in packages such as react-universal-component. It allows code to render synchronously on both the server and initial page-loads on the client. It requires that chunks are manually served or somehow available. It's able to require modules without indicating they should be bundled into a chunk. It's used in conjunction with import() which takes over when user navigation triggers additional imports.

warning

If the module source contains a require that cannot be statically analyzed, critical dependencies warning is emitted.

Example code:

someFn(require);
require.bind(null);
require(variable);

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4