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.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
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
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 '_')... }); }Copy after login
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!