网页 综合 更新时间 2026-11-14 09:19:18

ECMAScript Modules | webpack

自动蜘蛛 webpack.js.org 正文约 6000 字
ECMAScript Modules | webpack
ECMAScript Modules (ESM) is a specification for using Modules in the Web. It's supported by all modern browsers and the recommended way of writing modular code for the Web.
Webpack supports processing ECMAScript Modules to optimize them.
The export keyword allows to expose things from an ESM to other modules:
The import keyword allows to get references to things from other modules into an ESM:
When importing a namespace object from an ECMAScript Module, webpack follows the ESM convention of setting Symbol.toStringTag to "Module" on the namespace object.
By default webpack will automatically detect whether a file is an ESM or a different module system.
Node.js established a way of explicitly setting the module type of files by using a property in the package.json. Setting "type": "module" in a package.json does force all files below this package.json to be ECMAScript Modules. Setting "type": "commonjs" will instead force them to be CommonJS Modules.
In addition to that, files can set the module type by using .mjs or .cjs extension. .mjs will force them to be ESM, .cjs force them to be CommonJs.
In DataURIs using the text/javascript or application/javascript mime type will also force module type to ESM.
In addition to the module format, flagging modules as ESM also affect the resolving logic, interop logic and the available symbols in modules.
Webpack exposes several import.meta properties for use in ESM:
Example - using import.meta.url for assets:
Example - HMR in ESM:
In ESM, you can use await at the top level of a module. Webpack treats the module as an async module automatically. Enabled by default since 5.83.0; the experiments.topLevelAwait option itself was removed in 5.102.0 (it just works).
Avoid top-level await in your entry point when targeting the browser. It delays the entire module graph evaluation. Prefer import() for deferred loading. For Node.js, Electron, or Web Worker targets this restriction does not apply.
Imports in ESM are resolved more strictly. Relative requests must include a file extension (e.g. *.js or *.mjs) following the Node.js convention when the file is flagged as ESM:
Requests to packages e.g. import "lodash" are still supported.
To disable this check (useful when migrating a large CJS codebase), you can use fullySpecified=false:
CommonJS syntax is not available in ESM: require, module, exports, __filename, __dirname.
When webpack bundles a CommonJS module imported from ESM, both the default import (the entire module.exports object) and named imports (its properties) work:
This interop applies when webpack treats the imported module as CommonJS. If that module itself uses ESM export syntax, webpack will auto-detect it as ESM and use its exports directly. This commonly affects projects that mix .js files in a project that has "type": "module" set - webpack may treat some files as ESM while third-party packages in node_modules remain CommonJS.
This is webpack's bundling behavior. When Node.js itself loads a CommonJS module from ESM, T> named imports only work if Node.js can detect them statically; otherwise only the default T> import is available - consider migrating to ESM T> or using @babel/plugin-transform-modules-commonjs.
webpack bundles the code of a dependency as it finds it. target and your browserslist configuration constrain the runtime code webpack generates — they never downlevel the syntax you or a package wrote. So a package published with arrow functions, optional chaining or class fields reaches the browser exactly as published, and an older browser fails on it at parse time, with an error pointing into the bundle rather than at the package.
This became more common with webpack 5, which resolves the exports field, so a package that offers both a legacy and a modern build now hands webpack the modern one by default.
There are two ways out, and they are not exclusive.
Transpile the dependency. Guides — this site's build performance page included — recommend keeping loaders off node_modules, which is the right default: it is the bulk of the code and the slowest part to transform. Rather than dropping that rule, carve out the packages that need it:
The condition grammar also expresses this the other way round — exclude: { and: [/node_modules/], not: [/node_modules[\\/]pkg-a[\\/]/] } skips node_modules except for one package.
A package whose files mix CommonJS and ESM needs sourceType: "unambiguous" in the Babel options, otherwise Babel treats every file as one or the other and the wrong half breaks.
Or resolve a different build of it. When the package still publishes an ES5 bundle under another condition or field, point webpack at it instead of transpiling — see resolve.conditionNames and resolve.mainFields. Both apply to every package webpack resolves, so narrow them with resolve.byDependency or a per-package Rule.resolve rather than changing them globally.
Whichever you pick, the syntax webpack emits for its own runtime is a separate setting: keep a browserslist config, or set target to something like ['web', 'es5'], so the runtime does not fail on the same browsers.
ReferenceError: require is not defined
When a file is treated as ESM, CommonJS globals (require, module, exports, __filename, __dirname) are unavailable.
Fix: Replace require() with import statements. For conditional or dynamic loading, use import().
Must use import to load ES Module (Node.js) / SyntaxError: Cannot use import statement in a module (browser)
This happens when a file using ESM import/export syntax is not flagged as ESM - either "type": "module" is missing from package.json, or the file uses a .js extension instead of .mjs.
Fix: Add "type": "module" to your package.json, or rename the file to .mjs.
Module not found: Error: Can't resolve './utils' (missing extension)
In ESM, relative imports must include the file extension. Webpack follows the Node.js ESM convention here.
Fix: Change import { helper } from './utils' to import { helper } from './utils.js', or set fullySp
访问原文 返回搜索 https://webpack.js.org/guides/ecma-script-modules/
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。