From bde30f62b08697dee68a2750cf5b2650699eaf67 Mon Sep 17 00:00:00 2001 From: Christopher Willis-Ford <7019101+cwillisf@users.noreply.github.com> Date: Mon, 18 Mar 2024 11:25:04 -0700 Subject: [PATCH] feat: add rules for asset modules --- README.md | 15 +++++++++++++++ src/index.cjs | 49 ++++++++++++++++++++++++++++++++++++++----------- 2 files changed, 53 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 458f005..5348d58 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,21 @@ module.exports = [ - `node` builds to `dist/node/` - Supports merging in arbitrary configuration with `merge({...})` +### Asset Modules + +This configuration makes webpack 5's [Asset Modules](https://webpack.js.org/guides/asset-modules/) available through +resource queries parameters: + +```js +import myImage from './my-image.png?asset'; // Use `asset` (let webpack decide) +import myImage from './my-image.png?resource'; // Use `asset/resource`, similar to `file-loader` +import myImage from './my-image.png?inline'; // Use `asset/inline`, similar to `url-loader` +import myImage from './my-image.png?source'; // Use `asset/source`, similar to `raw-loader` +``` + +You can also use `file` for `asset/resource`, `url` for `asset/inline`, and `raw` for `asset/source`, to make it clear +which loader you're replacing. + ## API ### `new ScratchWebpackConfigBuilder(options)` diff --git a/src/index.cjs b/src/index.cjs index f06660f..cf5add4 100644 --- a/src/index.cjs +++ b/src/index.cjs @@ -87,18 +87,45 @@ class ScratchWebpackConfigBuilder { ] }, module: { - rules: [{ - test: enableReact ? /\.[cm]?jsx?$/ : /\.[cm]?js$/, - loader: 'babel-loader', - options: { - presets: [ - '@babel/preset-env', - ...( - enableReact ? ['@babel/preset-react'] : [] - ) - ] + rules: [ + { + test: enableReact ? /\.[cm]?jsx?$/ : /\.[cm]?js$/, + loader: 'babel-loader', + options: { + presets: [ + '@babel/preset-env', + ...( + enableReact ? ['@babel/preset-react'] : [] + ) + ] + } + }, + { + // `asset` automatically chooses between exporting a data URI and emitting a separate file. + // Previously achievable by using `url-loader` with asset size limit. + resourceQuery: /^\?asset$/, + type: 'asset' + }, + { + // `asset/resource` emits a separate file and exports the URL. + // Previously achievable by using `file-loader`. + resourceQuery: /^\?(resource|file)$/, + type: 'asset/resource' + }, + { + // `asset/inline` exports a data URI of the asset. + // Previously achievable by using `url-loader`. + resourceQuery: /^\?(inline|url)$/, + type: 'asset/inline' + }, + { + // `asset/source` exports the source code of the asset. + // Previously achievable by using `raw-loader`. + resourceQuery: /^\?(source|raw)$/, + type: 'asset/source' } - }] + ], + }, plugins: [] };