网页
综合
更新时间 2026-11-14 05:12:11
Asset Management | webpack
自动蜘蛛
webpack.js.org
正文约 6000 字
If you've been following the guides from the start, you will now have a small project that shows "Hello webpack". Now let's try to incorporate some other assets, like images, to see how they can be handled.
Prior to webpack, front-end developers would use tools like grunt and gulp to process these assets and move them from their /src folder into their /dist or /build directory. The same idea was used for JavaScript modules, but tools like webpack will dynamically bundle all dependencies (creating what's known as a dependency graph). This is great because every module now explicitly states its dependencies and we'll avoid bundling modules that aren't in use.
One of the coolest webpack features is that you can also include any other type of file, besides JavaScript, for which there is a loader or built-in Asset Modules support. This means that the same benefits listed above for JavaScript (e.g. explicit dependencies) can be applied to everything used in building a website or web app. Let's start with CSS, as you may already be familiar with that setup.
Let's make a minor change to our project before we get started:
Webpack understands CSS on its own, so you can import a CSS file from a JavaScript module with nothing to install and nothing to configure:
Webpack parses the file — resolving its @import and url() references — and extracts it into a .css output file next to your bundle. CSS Modules, minification and content hashes all come from the same built-in support; What's built-in states what it covers and what still needs a loader.
Built-in CSS is controlled by experiments.css, which defaults to 'auto': it turns itself on unless a module.rules entry with a loader already matches your .css files. That means an existing loader-based setup keeps working untouched — see the migration guide.
Preprocessors still use loaders, and module loaders can be chained. Each loader in the chain applies transformations to the processed resource. A chain is executed in reverse order (right to left).
For example, given the following rule:
Even though postcss-loader appears before sass-loader in the use array, webpack runs sass-loader first (compiling Sass into CSS), then runs postcss-loader on the result. The type: 'css/auto' tells webpack to take the CSS that comes out of the chain through its own CSS pipeline.
If this order is not maintained, webpack may throw errors.
Now run your build command:
Webpack extracted the CSS into its own file, bundle.css — the name follows output.cssFilename, which defaults from output.filename. Link it from the page:
Open up dist/index.html in your browser again and you should see that Hello webpack is now styled in red.
A separate stylesheet is the default because the browser can fetch it in parallel with the bundle and cache it on its own. If you would rather have the styles injected from JavaScript at runtime, set exportType: 'style' and no <link> is needed.
Minification is built in too: in mode: 'production' webpack minifies the emitted CSS with no extra plugin, and can maintain vendor prefixes for your browserslist target — see Minification. On top of that, loaders exist for pretty much any flavor of CSS you can think of – postcss, sass, and less to name a few.
So now we're pulling in our CSS, but what about our images like backgrounds and icons? As of webpack 5, using the built-in Asset Modules we can easily incorporate those in our system as well:
Now, when you import MyImage from './my-image.png', that image will be processed and added to your output directory and the MyImage variable will contain the final url of that image after processing. The same happens for a url('./my-image.png') inside your CSS: webpack recognizes it as a local file and rewrites the path to the final one in your output directory. With experiments.html enabled, <img src="./my-image.png" /> in an HTML file is handled the same way — see Native HTML.
Let's add an image to our project and see how this works, you can use any image you like:
Let's create a new build and open up the index.html file again:
If all went well, you should now see your icon as a repeating background, as well as an img element beside our Hello webpack text. If you inspect this element, you'll see that the actual filename has changed to something like 86c447381066a936d5c5.png. This means webpack found our file in the src folder and processed it!
So what about other assets like fonts? The Asset Modules will take any file you load through them and output it to your build directory. This means we can use them for any kind of file, including fonts. Let's update our webpack.config.js to handle font files:
Add some font files to your project:
With the rule configured and fonts in place, you can incorporate them via an @font-face declaration. The local url(...) directive will be picked up by webpack, as it was with the image:
Now run a new build and let's see if webpack handled our fonts:
Open up dist/index.html again and see if our Hello webpack text has changed to the new font. If all is well, you should see the changes.
Another useful asset that can be loaded is data, like JSON files, CSVs, TSVs, and XML. Support for JSON is actually built-in, similar to NodeJS, meaning import Data from './data.json' will work by default. To import CSVs, TSVs, and XML you could use the csv-loader and xml-loader. Let's handle loading all three:
Add some data files to your project:
Now you can import any one of those four types of data (JSON, CSV, TSV, XML) and the Data variable you import, will contain parsed JSON for consumption:
Re-run the npm run build command and open dist/index.html. If you look at the console in your developer tools, you should be able to see your imported data being logged to the console!
This can be especially helpful when implementing some sort of data visualization using a tool like d3. Instead of making an ajax request and parsing the data at runtime you can load it into your module during the build process so that the
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。