search
HomeWeb Front-endFront-end Q&ADoes webpack support es6?

Does webpack support es6?

Jan 18, 2023 pm 07:01 PM
es6webpack

Webpack supports es6. Webpack 2 supports native ES6 module syntax, which means developers can use import and export without introducing additional tools like babel. But if you use other ES6 features, you still need to introduce the babel tool.

Does webpack support es6?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

Module methods


When packaging your application with webpack, you can choose from various module syntax styles, including ES6, CommonJS and AMD.

Although webpack supports multiple module syntaxes, we still recommend using a consistent syntax as much as possible to avoid some strange behaviors and bugs. In fact, webpack enables syntax consistency checking when the nearest package.json file contains a "type" field with a value of "module" or "commonjs". Please pay attention to this before reading:

  • Set "type": "module" for .mjs or .js in package.json

    • CommonJS is not allowed, for example, you cannot use require, module.exports or exports

    • When importing a file, it is mandatory to write an extension, for example, you should use import '. /src/App.mjs' instead of import './src/App' (you can disable this rule by setting Rule.resolve.fullySpecified)

  • Set "type": "commonjs" in package.json for .cjs or .js

    • Both import and export are not available

  • Set "type": "module" for .wasm in package.json

    • When introducing a wasm file, you must write the file extension


webpack 2 supports native ES6 module syntax, which means you don’t need to introduce additional tools like babel , you can use import and export. But note that if you use other ES6 features, you still need to introduce babel. webpack supports the following methods:

import

## Use import to statically import another module exported through export.

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

Warning:

The keyword here is static. In the standard import statement, the module statement cannot introduce other modules in a dynamic way that "has logic or contains variables". More information about import and dynamic usage of import().

You also introduce Data URI through import:

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

export

Export the entire module or named by default Export module.

// 具名导出
export var Count = 5;
export function Multiply(a, b) {
  return a * b;
}

// 默认导出
export default {
  // Some data...
};

import()

function(string path):Promise

Dynamic loading module. The point where import is called is considered a split point, meaning that the requested module and all submodules it references will be split into a single chunk.

Tip:

The ES2015 Loader specification defines the import() method to dynamically load ES2015 modules at runtime.

if (module.hot) {
  import('lodash').then((_) => {
    // Do something with lodash (a.k.a '_')...
  });
}
Warning: The

import() feature relies on built-in Promise. If you want to use import() in older browsers, remember to use a polyfill library like es6-promise or promise-polyfill to pre-populate (shim) the Promise environment.

Expressions in import()

cannot use fully dynamic import statements, such as import(foo). is because foo could be any path to any file in your system or project.

import() must contain at least some path information about the module. Packaging can be limited to a specific directory or set of files, so that when using dynamic expressions - every module that may be requested in an import() call is included. For example, import(`./locale/${language}.json`) will package each .json file in the .locale directory into a new chunk. At runtime, after the variable language has been evaluated, any file like english.json or german.json can be used.

// 想象我们有一个从 cookies 或其他存储中获取语言的方法
const language = detectVisitorLanguage();
import(`./locale/${language}.json`).then((module) => {
  // do something with the translations
});

Tip:

Using the webpackInclude and webpackExclude options allows you to add regular expression patterns to reduce the number of files imported by webpack.

Magic Comments

Inline comments enable this feature. By adding comments in the import, we can do things like name the chunk or select a different mode.

// 单个目标
import(
  /* webpackChunkName: "my-chunk-name" */
  /* webpackMode: "lazy" */
  /* webpackExports: ["default", "named"] */
  'module'
);

// 多个可能的目标
import(
  /* webpackInclude: /\.json$/ */
  /* webpackExclude: /\.noimport\.json$/ */
  /* webpackChunkName: "my-chunk-name" */
  /* webpackMode: "lazy" */
  /* webpackPrefetch: true */
  /* webpackPreload: true */
  `./locale/${language}`
);
import(/* webpackIgnore: true */ 'ignored-module.js');

webpackIgnore: When set to true, disables dynamic import parsing.

Warning:

Note: Setting webpackIgnore to true will not perform code splitting.

webpackChunkName: The name of the new chunk. Starting with webpack 2.6.0, the placeholders [index] and [request] support incremented numbers or actual parsed filenames respectively. After adding this annotation, the individual chunks given to us will be named [my-chunk-name].js instead of [id].js.

webpackMode: Starting with webpack 2.6.0, you can specify a different mode to parse dynamic imports. The following options are supported:

  • 'lazy' (default value): Generate a lazy-loadable module for each import() imported module. chunk.

  • 'lazy-once': Generates a single lazy-loadable chunk that can satisfy all import() calls. This chunk will be obtained on the first import() call, and subsequent import()s will use the same network response. Note that this mode only makes sense in some dynamic statements, such as import(`./locales/${language}.json`), which may contain multiple requested module paths.

  • 'eager': No additional chunks will be generated. All modules are imported by the current chunk and no additional network requests are made. However, a Promise in resolved state will still be returned. In contrast to static imports, the module will not be executed until the call to import() completes.

  • 'weak': Try to load the module, if the module function has been loaded in other ways, (that is, another chunk has imported this module, or contains the module script is loaded). A Promise will still be returned, but will only be resolved successfully if the chunk is already available on the client. If the module is not available, a rejected Promise is returned and the network request is never executed. This is useful for Universal Rendering (SSR) when the required chunks are always provided manually in the initial request (embedded in the page), rather than when the application navigation is triggered on a module import that was not initially provided.

webpackPrefetch: Tells the browser that this resource may be needed for certain navigation jumps in the future.

webpackPreload: Tells the browser that the resource may be needed during the current navigation.

webpackInclude: Regular expression used for matching during import resolution. Only matching modules will be packaged.

webpackExclude: Regular expression used for matching during import resolution. All matching modules will not be packaged.

webpackExports: Tell webpack to only build dynamic import() modules with specified exports. It can reduce chunk size. Available from webpack 5.0.0-beta.18 onwards.

[Related recommendations: javascript learning tutorial]

The above is the detailed content of Does webpack support es6?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Frontend Development with React: Advantages and TechniquesFrontend Development with React: Advantages and TechniquesApr 17, 2025 am 12:25 AM

The advantages of React are its flexibility and efficiency, which are reflected in: 1) Component-based design improves code reusability; 2) Virtual DOM technology optimizes performance, especially when handling large amounts of data updates; 3) The rich ecosystem provides a large number of third-party libraries and tools. By understanding how React works and uses examples, you can master its core concepts and best practices to build an efficient, maintainable user interface.

React vs. Other Frameworks: Comparing and Contrasting OptionsReact vs. Other Frameworks: Comparing and Contrasting OptionsApr 17, 2025 am 12:23 AM

React is a JavaScript library for building user interfaces, suitable for large and complex applications. 1. The core of React is componentization and virtual DOM, which improves UI rendering performance. 2. Compared with Vue, React is more flexible but has a steep learning curve, which is suitable for large projects. 3. Compared with Angular, React is lighter, dependent on the community ecology, and suitable for projects that require flexibility.

Demystifying React in HTML: How It All WorksDemystifying React in HTML: How It All WorksApr 17, 2025 am 12:21 AM

React operates in HTML via virtual DOM. 1) React uses JSX syntax to write HTML-like structures. 2) Virtual DOM management UI update, efficient rendering through Diffing algorithm. 3) Use ReactDOM.render() to render the component to the real DOM. 4) Optimization and best practices include using React.memo and component splitting to improve performance and maintainability.

React in Action: Examples of Real-World ApplicationsReact in Action: Examples of Real-World ApplicationsApr 17, 2025 am 12:20 AM

React is widely used in e-commerce, social media and data visualization. 1) E-commerce platforms use React to build shopping cart components, use useState to manage state, onClick to process events, and map function to render lists. 2) Social media applications interact with the API through useEffect to display dynamic content. 3) Data visualization uses react-chartjs-2 library to render charts, and component design is easy to embed applications.

Frontend Architecture with React: Best PracticesFrontend Architecture with React: Best PracticesApr 17, 2025 am 12:10 AM

Best practices for React front-end architecture include: 1. Component design and reuse: design a single responsibility, easy to understand and test components to achieve high reuse. 2. State management: Use useState, useReducer, ContextAPI or Redux/MobX to manage state to avoid excessive complexity. 3. Performance optimization: Optimize performance through React.memo, useCallback, useMemo and other methods to find the balance point. 4. Code organization and modularity: Organize code according to functional modules to improve manageability and maintainability. 5. Testing and Quality Assurance: Testing with Jest and ReactTestingLibrary to ensure the quality and reliability of the code

React Inside HTML: Integrating JavaScript for Dynamic Web PagesReact Inside HTML: Integrating JavaScript for Dynamic Web PagesApr 16, 2025 am 12:06 AM

To integrate React into HTML, follow these steps: 1. Introduce React and ReactDOM in HTML files. 2. Define a React component. 3. Render the component into HTML elements using ReactDOM. Through these steps, static HTML pages can be transformed into dynamic, interactive experiences.

The Benefits of React: Performance, Reusability, and MoreThe Benefits of React: Performance, Reusability, and MoreApr 15, 2025 am 12:05 AM

React’s popularity includes its performance optimization, component reuse and a rich ecosystem. 1. Performance optimization achieves efficient updates through virtual DOM and diffing mechanisms. 2. Component Reuse Reduces duplicate code by reusable components. 3. Rich ecosystem and one-way data flow enhance the development experience.

React: Creating Dynamic and Interactive User InterfacesReact: Creating Dynamic and Interactive User InterfacesApr 14, 2025 am 12:08 AM

React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment