feat: added support for import file from "./file.ext" with { type: "bytes" } to get the content as `Uint8Array` (#19928)

This commit is contained in:
Alexander Akait 2025-09-24 21:01:10 +03:00 committed by GitHub
parent c647cf193c
commit f6c3c24da3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
45 changed files with 1095 additions and 260 deletions

View File

@ -21,5 +21,11 @@ trim_trailing_whitespace = false
[test/cases/parsing/bom/bomfile.{css,js}]
charset = utf-8-bom
[test/configCases/asset-modules/bytes/file.text]
insert_final_newline = false
[test/configCases/asset-modules/bytes/file.svg]
insert_final_newline = false
[test/configCases/css/no-extra-runtime-in-js/source.text]
insert_final_newline = false

View File

@ -3977,6 +3977,10 @@ export interface GeneratorOptionsByModuleTypeKnown {
* Generator options for asset modules.
*/
asset?: AssetGeneratorOptions;
/**
* No generator options are supported for this module type.
*/
"asset/bytes"?: EmptyGeneratorOptions;
/**
* Generator options for asset/inline modules.
*/
@ -3985,6 +3989,10 @@ export interface GeneratorOptionsByModuleTypeKnown {
* Generator options for asset/resource modules.
*/
"asset/resource"?: AssetResourceGeneratorOptions;
/**
* No generator options are supported for this module type.
*/
"asset/source"?: EmptyGeneratorOptions;
/**
* Generator options for css modules.
*/
@ -4041,6 +4049,10 @@ export interface ParserOptionsByModuleTypeKnown {
* Parser options for asset modules.
*/
asset?: AssetParserOptions;
/**
* No parser options are supported for this module type.
*/
"asset/bytes"?: EmptyParserOptions;
/**
* No parser options are supported for this module type.
*/

View File

@ -1,223 +0,0 @@
This is a very simple example that shows the usage of the asset module type.
Files can be imported like other modules without file-loader.
# example.js
```javascript
import png from "./images/file.png";
import jpg from "./images/file.jpg";
import svg from "./images/file.svg";
const container = document.createElement("div");
Object.assign(container.style, {
display: "flex",
justifyContent: "center"
});
document.body.appendChild(container);
function createImageElement(title, src) {
const div = document.createElement("div");
div.style.textAlign = "center";
const h2 = document.createElement("h2");
h2.textContent = title;
div.appendChild(h2);
const img = document.createElement("img");
img.setAttribute("src", src);
img.setAttribute("width", "150");
div.appendChild(img);
container.appendChild(div);
}
[png, jpg, svg].forEach(src => {
createImageElement(src.split(".").pop(), src);
});
```
# webpack.config.js
```javascript
"use strict";
module.exports = {
output: {
assetModuleFilename: "images/[hash][ext]"
},
module: {
rules: [
{
test: /\.(png|jpg|svg)$/,
type: "asset"
}
]
}
};
```
# js/output.js
```javascript
/******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ([
/* 0 */,
/* 1 */
/*!*************************!*\
!*** ./images/file.png ***!
\*************************/
/*! default exports */
/*! exports [not provided] [no usage info] */
/*! runtime requirements: __webpack_require__.p, module, __webpack_require__.* */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
module.exports = __webpack_require__.p + "images/89a353e9c515885abd8e.png";
/***/ }),
/* 2 */
/*!*************************!*\
!*** ./images/file.jpg ***!
\*************************/
/*! default exports */
/*! exports [not provided] [no usage info] */
/*! runtime requirements: module */
/***/ ((module) => {
module.exports = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAA...4CD/9M//Z";
/***/ }),
/* 3 */
/*!*************************!*\
!*** ./images/file.svg ***!
\*************************/
/*! default exports */
/*! exports [not provided] [no usage info] */
/*! runtime requirements: module */
/***/ ((module) => {
module.exports = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDo...vc3ZnPgo=";
/***/ })
/******/ ]);
```
<details><summary><code>/* webpack runtime code */</code></summary>
``` js
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/publicPath */
/******/ (() => {
/******/ __webpack_require__.p = "dist/";
/******/ })();
/******/
/************************************************************************/
```
</details>
``` js
var __webpack_exports__ = {};
// This entry needs to be wrapped in an IIFE because it needs to be isolated against other modules in the chunk.
(() => {
/*!********************!*\
!*** ./example.js ***!
\********************/
/*! namespace exports */
/*! exports [not provided] [no usage info] */
/*! runtime requirements: __webpack_require__, __webpack_require__.r, __webpack_exports__, __webpack_require__.* */
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _images_file_png__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./images/file.png */ 1);
/* harmony import */ var _images_file_jpg__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./images/file.jpg */ 2);
/* harmony import */ var _images_file_svg__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./images/file.svg */ 3);
const container = document.createElement("div");
Object.assign(container.style, {
display: "flex",
justifyContent: "center"
});
document.body.appendChild(container);
function createImageElement(title, src) {
const div = document.createElement("div");
div.style.textAlign = "center";
const h2 = document.createElement("h2");
h2.textContent = title;
div.appendChild(h2);
const img = document.createElement("img");
img.setAttribute("src", src);
img.setAttribute("width", "150");
div.appendChild(img);
container.appendChild(div);
}
[_images_file_png__WEBPACK_IMPORTED_MODULE_0__, _images_file_jpg__WEBPACK_IMPORTED_MODULE_1__, _images_file_svg__WEBPACK_IMPORTED_MODULE_2__].forEach(src => {
createImageElement(src.split(".").pop(), src);
});
})();
/******/ })()
;
```
# Info
## webpack output
```
asset images/89a353e9c515885abd8e.png 14.6 KiB [emitted] [immutable] [from: images/file.png] (auxiliary name: main)
asset output.js 13 KiB [emitted] (name: main)
chunk (runtime: main) output.js (main) 9.58 KiB (javascript) 14.6 KiB (asset) 306 bytes (runtime) [entry] [rendered]
> ./example.js main
dependent modules 8.86 KiB (javascript) 14.6 KiB (asset) [dependent] 3 modules
runtime modules 306 bytes 2 modules
./example.js 742 bytes [built] [code generated]
[no exports]
[used exports unknown]
entry ./example.js main
webpack X.X.X compiled successfully
```

View File

@ -1,30 +0,0 @@
import png from "./images/file.png";
import jpg from "./images/file.jpg";
import svg from "./images/file.svg";
const container = document.createElement("div");
Object.assign(container.style, {
display: "flex",
justifyContent: "center"
});
document.body.appendChild(container);
function createImageElement(title, src) {
const div = document.createElement("div");
div.style.textAlign = "center";
const h2 = document.createElement("h2");
h2.textContent = title;
div.appendChild(h2);
const img = document.createElement("img");
img.setAttribute("src", src);
img.setAttribute("width", "150");
div.appendChild(img);
container.appendChild(div);
}
[png, jpg, svg].forEach(src => {
createImageElement(src.split(".").pop(), src);
});

View File

Before

Width:  |  Height:  |  Size: 656 B

After

Width:  |  Height:  |  Size: 656 B

488
examples/asset/README.md Normal file
View File

@ -0,0 +1,488 @@
This is a very simple example that shows the usage of the asset module type.
Files can be imported like other modules without file-loader.
# example.js
```javascript
// There are different ways to use files:
// 1. Using `import something from "./file.ext";`
// return URLs or Data URL, depends on your configuration
import png from "./images/file.png";
import jpg from "./images/file.jpg";
import svg from "./images/file.svg";
// 2. Using `import something from "./file.ext"; with { type: "text" }` or `import something from "./file.ext"; with { type: "bytes" }`
// You don't need extra options in your configuration for these imports, they work out of the box
// returns the content as text
import text from "./content/file.text" with { type: "text" };
// returns the content as `Uint8Array`
import bytes from "./content/bytes.svg" with { type: "bytes" };
// 3. Using `new URL("./file.ext", import.meta.url);`
// You don't need extra options in your configuration for `new URL(...)` construction, they work out of the box
const url = new URL("./images/url.svg", import.meta.url);
const container = document.createElement("div");
Object.assign(container.style, {
display: "flex",
flexWrap: "wrap",
justifyContent: "center"
});
document.body.appendChild(container);
function createImageElement(div, data) {
const img = document.createElement("img");
img.setAttribute("src", data);
img.setAttribute("width", "150");
div.appendChild(img);
container.appendChild(div);
}
function createTextElement(div, data) {
const context = document.createElement("div");
context.textContent = data;
div.appendChild(context);
container.appendChild(div);
}
function createBlobElement(div, data) {
const blob = new Blob([data], { type: 'image/svg+xml' });
const blobUrl = URL.createObjectURL(blob);
const img = document.createElement("img");
img.setAttribute("src", blobUrl);
img.setAttribute("width", "150");
div.appendChild(img);
container.appendChild(div);
img.addEventListener(
'load',
() => { URL.revokeObjectURL(blobUrl) },
{ once: true }
);
}
const files = [
{
title: "import png from \"./images/file.png\";",
data: png,
render: createImageElement,
},
{
title: "import jpg from \"./images/file.jpg\";",
data: jpg,
render: createImageElement,
},
{
title: "import svg from \"./images/file.svg\";",
data: svg,
render: createImageElement,
},
{
title: "import text from \"./content/file.text\" with { type: \"text\" };",
data: text,
render: createTextElement,
},
{
title: "import bytes from \"./content/file.text\" with { type: \"bytes\" };",
data: bytes,
render: createBlobElement,
},
{
title: "new URL(\"./url.svg\", import.meta.url);",
data: url,
render: createImageElement,
},
];
function render(title, data, fn) {
const div = document.createElement("div");
div.style.textAlign = "center";
div.style.width = "50%";
const h2 = document.createElement("h2");
h2.textContent = title;
div.appendChild(h2);
fn(div, data)
}
files.forEach(item => {
render(item.title, item.data, item.render);
});
```
# webpack.config.js
```javascript
"use strict";
module.exports = {
output: {
assetModuleFilename: "images/[hash][ext]"
},
module: {
rules: [
{
test: /file\.(png|jpg|svg)$/,
type: "asset"
},
]
}
};
```
# js/output.js
```javascript
/******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ([
/* 0 */,
/* 1 */
/*!*************************!*\
!*** ./images/file.png ***!
\*************************/
/*! default exports */
/*! exports [not provided] [no usage info] */
/*! runtime requirements: __webpack_require__.p, module, __webpack_require__.* */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
module.exports = __webpack_require__.p + "images/89a353e9c515885abd8e.png";
/***/ }),
/* 2 */
/*!*************************!*\
!*** ./images/file.jpg ***!
\*************************/
/*! default exports */
/*! exports [not provided] [no usage info] */
/*! runtime requirements: module */
/***/ ((module) => {
module.exports = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAA...4CD/9M//Z";
/***/ }),
/* 3 */
/*!*************************!*\
!*** ./images/file.svg ***!
\*************************/
/*! default exports */
/*! exports [not provided] [no usage info] */
/*! runtime requirements: module */
/***/ ((module) => {
module.exports = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDo...vc3ZnPgo=";
/***/ }),
/* 4 */
/*!************************!*\
!*** ./images/url.svg ***!
\************************/
/*! default exports */
/*! exports [not provided] [no usage info] */
/*! runtime requirements: __webpack_require__.p, module, __webpack_require__.* */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
module.exports = __webpack_require__.p + "images/afc10c70ed4ce2b33593.svg";
/***/ }),
/* 5 */
/*!***************************!*\
!*** ./content/file.text ***!
\***************************/
/*! default exports */
/*! exports [not provided] [no usage info] */
/*! runtime requirements: module */
/***/ ((module) => {
module.exports = "a Ā 𐀀 文 🦄 Text\n";
/***/ }),
/* 6 */
/*!***************************!*\
!*** ./content/bytes.svg ***!
\***************************/
/*! default exports */
/*! exports [not provided] [no usage info] */
/*! runtime requirements: __webpack_require__.tb, module */
/***/ ((module) => {
module.exports = __webpack_require__.tb("PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2MDAgNjAwIj48dGl0bGU+aWNvbi1zcXVhcmUtc21hbGw8L3RpdGxlPjxwYXRoIGZpbGw9IiNGRkYiIGQ9Ik0zMDAgLjFMNTY1IDE1MHYyOTkuOUwzMDAgNTk5LjggMzUgNDQ5LjlWMTUweiIvPjxwYXRoIGZpbGw9IiM4RUQ2RkIiIGQ9Ik01MTcuNyA0MzkuNUwzMDguOCA1NTcuOHYtOTJMNDM5IDM5NC4xbDc4LjcgNDUuNHptMTQuMy0xMi45VjE3OS40bC03Ni40IDQ0LjF2MTU5bDc2LjQgNDQuMXpNODEuNSA0MzkuNWwyMDguOSAxMTguMnYtOTJsLTEzMC4yLTcxLjYtNzguNyA0NS40em0tMTQuMy0xMi45VjE3OS40bDc2LjQgNDQuMXYxNTlsLTc2LjQgNDQuMXptOC45LTI2My4yTDI5MC40IDQyLjJ2ODlsLTEzNy4zIDc1LjUtMS4xLjYtNzUuOS00My45em00NDYuOSAwTDMwOC44IDQyLjJ2ODlMNDQ2IDIwNi44bDEuMS42IDc1LjktNDR6Ii8+PHBhdGggZmlsbD0iIzFDNzhDMCIgZD0iTTI5MC40IDQ0NC44TDE2MiAzNzQuMVYyMzQuMmwxMjguNCA3NC4xdjEzNi41em0xOC40IDBsMTI4LjQtNzAuNnYtMTQwbC0xMjguNCA3NC4xdjEzNi41ek0yOTkuNiAzMDN6bS0xMjktODVsMTI5LTcwLjlMNDI4LjUgMjE4bC0xMjguOSA3NC40LTEyOS03NC40eiIvPjwvc3ZnPgo=");
/***/ })
/******/ ]);
```
<details><summary><code>/* webpack runtime code */</code></summary>
``` js
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = __webpack_modules__;
/******/
/************************************************************************/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/to binary */
/******/ (() => {
/******/ // define to binary helper
/******/ __webpack_require__.tb = (() => {
/******/ var table = new Uint8Array(128);
/******/ for (var i = 0; i < 64; i++) table[i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i * 4 - 205] = i;
/******/ return (base64) => {
/******/ var n = base64.length, bytes = new Uint8Array((n - (base64[n - 1] == '=') - (base64[n - 2] == '=')) * 3 / 4 | 0);
/******/ for (var i = 0, j = 0; i < n;) {
/******/ var c0 = table[base64.charCodeAt(i++)], c1 = table[base64.charCodeAt(i++)];
/******/ var c2 = table[base64.charCodeAt(i++)], c3 = table[base64.charCodeAt(i++)];
/******/ bytes[j++] = (c0 << 2) | (c1 >> 4);
/******/ bytes[j++] = (c1 << 4) | (c2 >> 2);
/******/ bytes[j++] = (c2 << 6) | c3;
/******/ }
/******/ return bytes
/******/ }
/******/ })();
/******/ })();
/******/
/******/ /* webpack/runtime/publicPath */
/******/ (() => {
/******/ __webpack_require__.p = "dist/";
/******/ })();
/******/
/******/ /* webpack/runtime/jsonp chunk loading */
/******/ (() => {
/******/ __webpack_require__.b = (document && document.baseURI) || self.location.href;
/******/
/******/ // object to store loaded and loading chunks
/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched
/******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
/******/ var installedChunks = {
/******/ 0: 0
/******/ };
/******/
/******/ // no chunk on demand loading
/******/
/******/ // no prefetching
/******/
/******/ // no preloaded
/******/
/******/ // no HMR
/******/
/******/ // no HMR manifest
/******/
/******/ // no on chunks loaded
/******/
/******/ // no jsonp function
/******/ })();
/******/
/************************************************************************/
```
</details>
``` js
var __webpack_exports__ = {};
// This entry needs to be wrapped in an IIFE because it needs to be isolated against other modules in the chunk.
(() => {
/*!********************!*\
!*** ./example.js ***!
\********************/
/*! namespace exports */
/*! exports [not provided] [no usage info] */
/*! runtime requirements: __webpack_require__, __webpack_require__.b, __webpack_require__.r, __webpack_exports__, __webpack_require__.* */
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _images_file_png__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./images/file.png */ 1);
/* harmony import */ var _images_file_jpg__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./images/file.jpg */ 2);
/* harmony import */ var _images_file_svg__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./images/file.svg */ 3);
/* harmony import */ var _content_file_text__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./content/file.text */ 5);
/* harmony import */ var _content_bytes_svg__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./content/bytes.svg */ 6);
// There are different ways to use files:
// 1. Using `import something from "./file.ext";`
// return URLs or Data URL, depends on your configuration
// 2. Using `import something from "./file.ext"; with { type: "text" }` or `import something from "./file.ext"; with { type: "bytes" }`
// You don't need extra options in your configuration for these imports, they work out of the box
// returns the content as text
// returns the content as `Uint8Array`
// 3. Using `new URL("./file.ext", import.meta.url);`
// You don't need extra options in your configuration for `new URL(...)` construction, they work out of the box
const url = new URL(/* asset import */ __webpack_require__(/*! ./images/url.svg */ 4), __webpack_require__.b);
const container = document.createElement("div");
Object.assign(container.style, {
display: "flex",
flexWrap: "wrap",
justifyContent: "center"
});
document.body.appendChild(container);
function createImageElement(div, data) {
const img = document.createElement("img");
img.setAttribute("src", data);
img.setAttribute("width", "150");
div.appendChild(img);
container.appendChild(div);
}
function createTextElement(div, data) {
const context = document.createElement("div");
context.textContent = data;
div.appendChild(context);
container.appendChild(div);
}
function createBlobElement(div, data) {
const blob = new Blob([data], { type: 'image/svg+xml' });
const blobUrl = URL.createObjectURL(blob);
const img = document.createElement("img");
img.setAttribute("src", blobUrl);
img.setAttribute("width", "150");
div.appendChild(img);
container.appendChild(div);
img.addEventListener(
'load',
() => { URL.revokeObjectURL(blobUrl) },
{ once: true }
);
}
const files = [
{
title: "import png from \"./images/file.png\";",
data: _images_file_png__WEBPACK_IMPORTED_MODULE_0__,
render: createImageElement,
},
{
title: "import jpg from \"./images/file.jpg\";",
data: _images_file_jpg__WEBPACK_IMPORTED_MODULE_1__,
render: createImageElement,
},
{
title: "import svg from \"./images/file.svg\";",
data: _images_file_svg__WEBPACK_IMPORTED_MODULE_2__,
render: createImageElement,
},
{
title: "import text from \"./content/file.text\" with { type: \"text\" };",
data: _content_file_text__WEBPACK_IMPORTED_MODULE_3__,
render: createTextElement,
},
{
title: "import bytes from \"./content/file.text\" with { type: \"bytes\" };",
data: _content_bytes_svg__WEBPACK_IMPORTED_MODULE_4__,
render: createBlobElement,
},
{
title: "new URL(\"./url.svg\", import.meta.url);",
data: url,
render: createImageElement,
},
];
function render(title, data, fn) {
const div = document.createElement("div");
div.style.textAlign = "center";
div.style.width = "50%";
const h2 = document.createElement("h2");
h2.textContent = title;
div.appendChild(h2);
fn(div, data)
}
files.forEach(item => {
render(item.title, item.data, item.render);
});
})();
/******/ })()
;
```
# Info
## webpack output
```
asset output.js 19.2 KiB [emitted] (name: main)
asset images/89a353e9c515885abd8e.png 14.6 KiB [emitted] [immutable] [from: images/file.png] (auxiliary name: main)
asset images/afc10c70ed4ce2b33593.svg 656 bytes [emitted] [immutable] [from: images/url.svg] (auxiliary name: main)
chunk (runtime: main) output.js (main) 12.4 KiB (javascript) 15.2 KiB (asset) 1.46 KiB (runtime) [entry] [rendered]
> ./example.js main
dependent modules 9.59 KiB (javascript) 15.2 KiB (asset) [dependent] 6 modules
runtime modules 1.46 KiB 5 modules
./example.js 2.85 KiB [built] [code generated]
[no exports]
[used exports unknown]
entry ./example.js main
webpack X.X.X compiled successfully
```

View File

Before

Width:  |  Height:  |  Size: 656 B

After

Width:  |  Height:  |  Size: 656 B

View File

@ -0,0 +1 @@
a Ā 𐀀 文 🦄 Text

116
examples/asset/example.js Normal file
View File

@ -0,0 +1,116 @@
// There are different ways to use files:
// 1. Using `import something from "./file.ext";`
// return URLs or Data URL, depends on your configuration
import png from "./images/file.png";
import jpg from "./images/file.jpg";
import svg from "./images/file.svg";
// 2. Using `import something from "./file.ext"; with { type: "text" }` or `import something from "./file.ext"; with { type: "bytes" }`
// You don't need extra options in your configuration for these imports, they work out of the box
// returns the content as text
import text from "./content/file.text" with { type: "text" };
// returns the content as `Uint8Array`
import bytes from "./content/bytes.svg" with { type: "bytes" };
// 3. Using `new URL("./file.ext", import.meta.url);`
// You don't need extra options in your configuration for `new URL(...)` construction, they work out of the box
const url = new URL("./images/url.svg", import.meta.url);
const container = document.createElement("div");
Object.assign(container.style, {
display: "flex",
flexWrap: "wrap",
justifyContent: "center"
});
document.body.appendChild(container);
function createImageElement(div, data) {
const img = document.createElement("img");
img.setAttribute("src", data);
img.setAttribute("width", "150");
div.appendChild(img);
container.appendChild(div);
}
function createTextElement(div, data) {
const context = document.createElement("div");
context.textContent = data;
div.appendChild(context);
container.appendChild(div);
}
function createBlobElement(div, data) {
const blob = new Blob([data], { type: 'image/svg+xml' });
const blobUrl = URL.createObjectURL(blob);
const img = document.createElement("img");
img.setAttribute("src", blobUrl);
img.setAttribute("width", "150");
div.appendChild(img);
container.appendChild(div);
img.addEventListener(
'load',
() => { URL.revokeObjectURL(blobUrl) },
{ once: true }
);
}
const files = [
{
title: "import png from \"./images/file.png\";",
data: png,
render: createImageElement,
},
{
title: "import jpg from \"./images/file.jpg\";",
data: jpg,
render: createImageElement,
},
{
title: "import svg from \"./images/file.svg\";",
data: svg,
render: createImageElement,
},
{
title: "import text from \"./content/file.text\" with { type: \"text\" };",
data: text,
render: createTextElement,
},
{
title: "import bytes from \"./content/file.text\" with { type: \"bytes\" };",
data: bytes,
render: createBlobElement,
},
{
title: "new URL(\"./url.svg\", import.meta.url);",
data: url,
render: createImageElement,
},
];
function render(title, data, fn) {
const div = document.createElement("div");
div.style.textAlign = "center";
div.style.width = "50%";
const h2 = document.createElement("h2");
h2.textContent = title;
div.appendChild(h2);
fn(div, data)
}
files.forEach(item => {
render(item.title, item.data, item.render);
});

View File

Before

Width:  |  Height:  |  Size: 5.9 KiB

After

Width:  |  Height:  |  Size: 5.9 KiB

View File

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 600"><title>icon-square-small</title><path fill="#FFF" d="M300 .1L565 150v299.9L300 599.8 35 449.9V150z"/><path fill="#8ED6FB" d="M517.7 439.5L308.8 557.8v-92L439 394.1l78.7 45.4zm14.3-12.9V179.4l-76.4 44.1v159l76.4 44.1zM81.5 439.5l208.9 118.2v-92l-130.2-71.6-78.7 45.4zm-14.3-12.9V179.4l76.4 44.1v159l-76.4 44.1zm8.9-263.2L290.4 42.2v89l-137.3 75.5-1.1.6-75.9-43.9zm446.9 0L308.8 42.2v89L446 206.8l1.1.6 75.9-44z"/><path fill="#1C78C0" d="M290.4 444.8L162 374.1V234.2l128.4 74.1v136.5zm18.4 0l128.4-70.6v-140l-128.4 74.1v136.5zM299.6 303zm-129-85l129-70.9L428.5 218l-128.9 74.4-129-74.4z"/></svg>

After

Width:  |  Height:  |  Size: 656 B

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 600"><title>icon-square-small</title><path fill="#FFF" d="M300 .1L565 150v299.9L300 599.8 35 449.9V150z"/><path fill="#8ED6FB" d="M517.7 439.5L308.8 557.8v-92L439 394.1l78.7 45.4zm14.3-12.9V179.4l-76.4 44.1v159l76.4 44.1zM81.5 439.5l208.9 118.2v-92l-130.2-71.6-78.7 45.4zm-14.3-12.9V179.4l76.4 44.1v159l-76.4 44.1zm8.9-263.2L290.4 42.2v89l-137.3 75.5-1.1.6-75.9-43.9zm446.9 0L308.8 42.2v89L446 206.8l1.1.6 75.9-44z"/><path fill="#1C78C0" d="M290.4 444.8L162 374.1V234.2l128.4 74.1v136.5zm18.4 0l128.4-70.6v-140l-128.4 74.1v136.5zM299.6 303zm-129-85l129-70.9L428.5 218l-128.9 74.4-129-74.4z"/></svg>

After

Width:  |  Height:  |  Size: 656 B

View File

@ -7,9 +7,9 @@ module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|svg)$/,
test: /file\.(png|jpg|svg)$/,
type: "asset"
}
},
]
}
};

View File

@ -89,6 +89,12 @@ const ASSET_MODULE_TYPE_RESOURCE = "asset/resource";
*/
const ASSET_MODULE_TYPE_SOURCE = "asset/source";
/**
* @type {Readonly<"asset/bytes">}
* This is the module type used for assets that are imported as Uint8Array.
*/
const ASSET_MODULE_TYPE_BYTES = "asset/bytes";
/**
* @type {Readonly<"asset/raw-data-url">}
* TODO: Document what this asset type is for. See css-loader tests for its usage.
@ -144,6 +150,7 @@ const WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY = "lazy-compilation-proxy";
/** @typedef {JavaScriptModuleTypes | JSONModuleType | WebAssemblyModuleTypes | CSSModuleTypes | AssetModuleTypes | WebpackModuleTypes | UnknownModuleTypes} ModuleTypes */
module.exports.ASSET_MODULE_TYPE = ASSET_MODULE_TYPE;
module.exports.ASSET_MODULE_TYPE_BYTES = ASSET_MODULE_TYPE_BYTES;
module.exports.ASSET_MODULE_TYPE_INLINE = ASSET_MODULE_TYPE_INLINE;
module.exports.ASSET_MODULE_TYPE_RAW_DATA_URL = ASSET_MODULE_TYPE_RAW_DATA_URL;
module.exports.ASSET_MODULE_TYPE_RESOURCE = ASSET_MODULE_TYPE_RESOURCE;

View File

@ -416,6 +416,11 @@ module.exports.systemContext = "__webpack_require__.y";
*/
module.exports.thisAsExports = "top-level-this-exports";
/**
* to binary helper, convert base64 to Uint8Array
*/
module.exports.toBinary = "__webpack_require__.tb";
/**
* the uncaught error handler for the webpack runtime
*/

View File

@ -32,6 +32,7 @@ const PublicPathRuntimeModule = require("./runtime/PublicPathRuntimeModule");
const RelativeUrlRuntimeModule = require("./runtime/RelativeUrlRuntimeModule");
const RuntimeIdRuntimeModule = require("./runtime/RuntimeIdRuntimeModule");
const SystemContextRuntimeModule = require("./runtime/SystemContextRuntimeModule");
const ToBinaryRuntimeModule = require("./runtime/ToBinaryRuntimeModule");
const ShareRuntimeModule = require("./sharing/ShareRuntimeModule");
const StringXor = require("./util/StringXor");
const memoize = require("./util/memoize");
@ -489,6 +490,12 @@ class RuntimePlugin {
compilation.addRuntimeModule(chunk, new NonceRuntimeModule());
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.toBinary)
.tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(chunk, new ToBinaryRuntimeModule());
return true;
});
// TODO webpack 6: remove CompatRuntimeModule
compilation.hooks.additionalTreeRuntimeRequirements.tap(
PLUGIN_NAME,

View File

@ -107,7 +107,7 @@ class RuntimeTemplate {
isNeutralPlatform() {
return (
!this.outputOptions.environment.document &&
!this.compilation.compiler.platform.web &&
!this.compilation.compiler.platform.node
);
}

View File

@ -0,0 +1,166 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Alexander Akait @alexander-akait
*/
"use strict";
const { RawSource } = require("webpack-sources");
const ConcatenationScope = require("../ConcatenationScope");
const Generator = require("../Generator");
const {
CSS_URL_TYPES,
JS_AND_CSS_URL_TYPES,
JS_TYPES,
NO_TYPES
} = require("../ModuleSourceTypesConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../Generator").GenerateContext} GenerateContext */
/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("../Module").SourceTypes} SourceTypes */
/** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../NormalModule")} NormalModule */
class AssetSourceGenerator extends Generator {
/**
* @param {ModuleGraph} moduleGraph the module graph
*/
constructor(moduleGraph) {
super();
this._moduleGraph = moduleGraph;
}
/**
* @param {NormalModule} module module for which the code should be generated
* @param {GenerateContext} generateContext context for generate
* @returns {Source | null} generated code
*/
generate(
module,
{ type, concatenationScope, getData, runtimeTemplate, runtimeRequirements }
) {
const originalSource = module.originalSource();
const data = getData ? getData() : undefined;
switch (type) {
case "javascript": {
if (!originalSource) {
return new RawSource("");
}
const encodedSource = originalSource.buffer().toString("base64");
runtimeRequirements.add(RuntimeGlobals.toBinary);
let sourceContent;
if (concatenationScope) {
concatenationScope.registerNamespaceExport(
ConcatenationScope.NAMESPACE_OBJECT_EXPORT
);
sourceContent = `${runtimeTemplate.renderConst()} ${
ConcatenationScope.NAMESPACE_OBJECT_EXPORT
} = ${RuntimeGlobals.toBinary}(${JSON.stringify(encodedSource)});`;
} else {
runtimeRequirements.add(RuntimeGlobals.module);
sourceContent = `${RuntimeGlobals.module}.exports = ${RuntimeGlobals.toBinary}(${JSON.stringify(
encodedSource
)});`;
}
return new RawSource(sourceContent);
}
case "css-url": {
if (!originalSource) {
return null;
}
const encodedSource = originalSource.buffer().toString("base64");
if (data) {
data.set("url", {
[type]: `data:application/octet-stream;base64,${encodedSource}`
});
}
return null;
}
default:
return null;
}
}
/**
* @param {Error} error the error
* @param {NormalModule} module module for which the code should be generated
* @param {GenerateContext} generateContext context for generate
* @returns {Source | null} generated code
*/
generateError(error, module, generateContext) {
switch (generateContext.type) {
case "javascript": {
return new RawSource(
`throw new Error(${JSON.stringify(error.message)});`
);
}
default:
return null;
}
}
/**
* @param {NormalModule} module module for which the bailout reason should be determined
* @param {ConcatenationBailoutReasonContext} context context
* @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
*/
getConcatenationBailoutReason(module, context) {
return undefined;
}
/**
* @param {NormalModule} module fresh module
* @returns {SourceTypes} available types (do not mutate)
*/
getTypes(module) {
/** @type {Set<string>} */
const sourceTypes = new Set();
const connections = this._moduleGraph.getIncomingConnections(module);
for (const connection of connections) {
if (!connection.originModule) {
continue;
}
sourceTypes.add(connection.originModule.type.split("/")[0]);
}
if (sourceTypes.size > 0) {
if (sourceTypes.has("javascript") && sourceTypes.has("css")) {
return JS_AND_CSS_URL_TYPES;
} else if (sourceTypes.has("css")) {
return CSS_URL_TYPES;
}
return JS_TYPES;
}
return NO_TYPES;
}
/**
* @param {NormalModule} module the module
* @param {string=} type source type
* @returns {number} estimate size of the module
*/
getSize(module, type) {
const originalSource = module.originalSource();
if (!originalSource) {
return 0;
}
// Example: m.exports="abcd"
return originalSource.size() + 12;
}
}
module.exports = AssetSourceGenerator;

View File

@ -0,0 +1,37 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Alexander Akait @alexander-akait
*/
"use strict";
const Parser = require("../Parser");
/** @typedef {import("../Module").BuildInfo} BuildInfo */
/** @typedef {import("../Module").BuildMeta} BuildMeta */
/** @typedef {import("../Parser").ParserState} ParserState */
/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
class AssetBytesParser extends Parser {
/**
* @param {string | Buffer | PreparsedAst} source the source to parse
* @param {ParserState} state the parser state
* @returns {ParserState} the parser state
*/
parse(source, state) {
if (typeof source === "object" && !Buffer.isBuffer(source)) {
throw new Error("AssetBytesParser doesn't accept preparsed AST");
}
const { module } = state;
/** @type {BuildInfo} */
(module.buildInfo).strict = true;
/** @type {BuildMeta} */
(module.buildMeta).exportsType = "default";
/** @type {BuildMeta} */
(state.module.buildMeta).defaultObject = false;
return state;
}
}
module.exports = AssetBytesParser;

View File

@ -7,6 +7,7 @@
const {
ASSET_MODULE_TYPE,
ASSET_MODULE_TYPE_BYTES,
ASSET_MODULE_TYPE_INLINE,
ASSET_MODULE_TYPE_RESOURCE,
ASSET_MODULE_TYPE_SOURCE
@ -70,9 +71,11 @@ const validateParserOptions = createSchemaValidation(
const getAssetGenerator = memoize(() => require("./AssetGenerator"));
const getAssetParser = memoize(() => require("./AssetParser"));
const getAssetSourceParser = memoize(() => require("./AssetSourceParser"));
const getAssetBytesParser = memoize(() => require("./AssetBytesParser"));
const getAssetSourceGenerator = memoize(() =>
require("./AssetSourceGenerator")
);
const getAssetBytesGenerator = memoize(() => require("./AssetBytesGenerator"));
const type = ASSET_MODULE_TYPE;
const PLUGIN_NAME = "AssetModulesPlugin";
@ -125,6 +128,13 @@ class AssetModulesPlugin {
return new AssetSourceParser();
});
normalModuleFactory.hooks.createParser
.for(ASSET_MODULE_TYPE_BYTES)
.tap(PLUGIN_NAME, (_parserOptions) => {
const AssetBytesParser = getAssetBytesParser();
return new AssetBytesParser();
});
for (const type of [
ASSET_MODULE_TYPE,
@ -177,6 +187,14 @@ class AssetModulesPlugin {
return new AssetSourceGenerator(compilation.moduleGraph);
});
normalModuleFactory.hooks.createGenerator
.for(ASSET_MODULE_TYPE_BYTES)
.tap(PLUGIN_NAME, () => {
const AssetBytesGenerator = getAssetBytesGenerator();
return new AssetBytesGenerator(compilation.moduleGraph);
});
compilation.hooks.renderManifest.tap(PLUGIN_NAME, (result, options) => {
const { chunkGraph } = compilation;
const { chunk, codeGenerationResults, runtimeTemplate } = options;

View File

@ -9,6 +9,7 @@ const fs = require("fs");
const path = require("path");
const {
ASSET_MODULE_TYPE,
ASSET_MODULE_TYPE_BYTES,
ASSET_MODULE_TYPE_INLINE,
ASSET_MODULE_TYPE_RESOURCE,
ASSET_MODULE_TYPE_SOURCE,
@ -1066,6 +1067,10 @@ const applyModuleDefaults = (
{
with: { type: "text" },
type: ASSET_MODULE_TYPE_SOURCE
},
{
with: { type: "bytes" },
type: ASSET_MODULE_TYPE_BYTES
}
);
return rules;

View File

@ -0,0 +1,64 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Alexander Akait @alexander-akait
*/
"use strict";
const RuntimeGlobals = require("../RuntimeGlobals");
const RuntimeModule = require("../RuntimeModule");
const Template = require("../Template");
/** @typedef {import("../Compilation")} Compilation */
class ToBinaryRuntimeModule extends RuntimeModule {
constructor() {
super("to binary");
}
/**
* @returns {string | null} runtime code
*/
generate() {
const compilation = /** @type {Compilation} */ (this.compilation);
const fn = RuntimeGlobals.toBinary;
const { runtimeTemplate } = compilation;
// Inspired by esbuild
const isNodePlatform = compilation.compiler.platform.node;
const isWebPlatform = compilation.compiler.platform.web;
const isNeutralPlatform = runtimeTemplate.isNeutralPlatform();
return Template.asString([
"// define to binary helper",
`${fn} = ${isNeutralPlatform ? "typeof Buffer !== 'undefined' ? " : ""}${
isNodePlatform || isNeutralPlatform
? `${runtimeTemplate.returningFunction("new Uint8Array(Buffer.from(base64, 'base64'))", "base64")}`
: ""
} ${isNeutralPlatform ? ": " : ""}${
isWebPlatform || isNeutralPlatform
? `(${runtimeTemplate.basicFunction("", [
"var table = new Uint8Array(128);",
"for (var i = 0; i < 64; i++) table[i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i * 4 - 205] = i;",
`return ${runtimeTemplate.basicFunction("base64", [
"var n = base64.length, bytes = new Uint8Array((n - (base64[n - 1] == '=') - (base64[n - 2] == '=')) * 3 / 4 | 0);",
"for (var i = 0, j = 0; i < n;) {",
Template.indent([
"var c0 = table[base64.charCodeAt(i++)], c1 = table[base64.charCodeAt(i++)];",
"var c2 = table[base64.charCodeAt(i++)], c3 = table[base64.charCodeAt(i++)];",
"bytes[j++] = (c0 << 2) | (c1 >> 4);",
"bytes[j++] = (c1 << 4) | (c2 >> 2);",
"bytes[j++] = (c2 << 6) | c3;"
]),
"}",
"return bytes"
])}`
])})();`
: ""
}`
]);
}
}
module.exports = ToBinaryRuntimeModule;

File diff suppressed because one or more lines are too long

View File

@ -1521,12 +1521,18 @@
"asset": {
"$ref": "#/definitions/AssetGeneratorOptions"
},
"asset/bytes": {
"$ref": "#/definitions/EmptyGeneratorOptions"
},
"asset/inline": {
"$ref": "#/definitions/AssetInlineGeneratorOptions"
},
"asset/resource": {
"$ref": "#/definitions/AssetResourceGeneratorOptions"
},
"asset/source": {
"$ref": "#/definitions/EmptyGeneratorOptions"
},
"css": {
"$ref": "#/definitions/CssGeneratorOptions"
},
@ -3887,6 +3893,9 @@
"asset": {
"$ref": "#/definitions/AssetParserOptions"
},
"asset/bytes": {
"$ref": "#/definitions/EmptyParserOptions"
},
"asset/inline": {
"$ref": "#/definitions/EmptyParserOptions"
},

View File

@ -232,6 +232,12 @@ describe("snapshots", () => {
"type": "text",
},
},
Object {
"type": "asset/bytes",
"with": Object {
"type": "bytes",
},
},
],
"generator": Object {
"json": Object {

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 600"><title>icon-square-small</title><path fill="#FFF" d="M300 .1L565 150v299.9L300 599.8 35 449.9V150z"/><path fill="#8ED6FB" d="M517.7 439.5L308.8 557.8v-92L439 394.1l78.7 45.4zm14.3-12.9V179.4l-76.4 44.1v159l76.4 44.1zM81.5 439.5l208.9 118.2v-92l-130.2-71.6-78.7 45.4zm-14.3-12.9V179.4l76.4 44.1v159l-76.4 44.1zm8.9-263.2L290.4 42.2v89l-137.3 75.5-1.1.6-75.9-43.9zm446.9 0L308.8 42.2v89L446 206.8l1.1.6 75.9-44z"/><path fill="#1C78C0" d="M290.4 444.8L162 374.1V234.2l128.4 74.1v136.5zm18.4 0l128.4-70.6v-140l-128.4 74.1v136.5zM299.6 303zm-129-85l129-70.9L428.5 218l-128.9 74.4-129-74.4z"/></svg>

After

Width:  |  Height:  |  Size: 655 B

View File

@ -0,0 +1 @@
a Ā 𐀀 文 🦄 Text

View File

@ -0,0 +1,14 @@
import * as style from "./style.css";
import file from "./file.text" with { type: "bytes" };
it("should work", () => {
const decoder = new TextDecoder('utf-8');
const text = decoder.decode(file);
expect(text).toBe("a Ā 𐀀 文 🦄 Text");
if (typeof getComputedStyle === "function") {
const style = getComputedStyle(document.body);
expect(style.getPropertyValue("--my-url")).toBe(" url(data:application/octet-stream;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2MDAgNjAwIj48dGl0bGU+aWNvbi1zcXVhcmUtc21hbGw8L3RpdGxlPjxwYXRoIGZpbGw9IiNGRkYiIGQ9Ik0zMDAgLjFMNTY1IDE1MHYyOTkuOUwzMDAgNTk5LjggMzUgNDQ5LjlWMTUweiIvPjxwYXRoIGZpbGw9IiM4RUQ2RkIiIGQ9Ik01MTcuNyA0MzkuNUwzMDguOCA1NTcuOHYtOTJMNDM5IDM5NC4xbDc4LjcgNDUuNHptMTQuMy0xMi45VjE3OS40bC03Ni40IDQ0LjF2MTU5bDc2LjQgNDQuMXpNODEuNSA0MzkuNWwyMDguOSAxMTguMnYtOTJsLTEzMC4yLTcxLjYtNzguNyA0NS40em0tMTQuMy0xMi45VjE3OS40bDc2LjQgNDQuMXYxNTlsLTc2LjQgNDQuMXptOC45LTI2My4yTDI5MC40IDQyLjJ2ODlsLTEzNy4zIDc1LjUtMS4xLjYtNzUuOS00My45em00NDYuOSAwTDMwOC44IDQyLjJ2ODlMNDQ2IDIwNi44bDEuMS42IDc1LjktNDR6Ii8+PHBhdGggZmlsbD0iIzFDNzhDMCIgZD0iTTI5MC40IDQ0NC44TDE2MiAzNzQuMVYyMzQuMmwxMjguNCA3NC4xdjEzNi41em0xOC40IDBsMTI4LjQtNzAuNnYtMTQwbC0xMjguNCA3NC4xdjEzNi41ek0yOTkuNiAzMDN6bS0xMjktODVsMTI5LTcwLjlMNDI4LjUgMjE4bC0xMjguOSA3NC40LTEyOS03NC40eiIvPjwvc3ZnPg==)");
}
});

View File

@ -0,0 +1,3 @@
body {
--my-url: url("./file.svg");
}

View File

@ -0,0 +1,18 @@
"use strict";
let run = 0;
module.exports = {
moduleScope(scope, options) {
if (!scope.window) {
return;
}
const link = scope.window.document.createElement("link");
link.rel = "stylesheet";
link.href = `bundle${run === 0 ? "0" : "2"}.css`;
scope.window.document.head.appendChild(link);
run++;
}
};

View File

@ -0,0 +1,5 @@
"use strict";
const supportsTextDecoder = require("../../../helpers/supportsTextDecoder");
module.exports = () => supportsTextDecoder();

View File

@ -0,0 +1,54 @@
"use strict";
/** @type {import("../../../../").Configuration[]} */
module.exports = [
{
name: "web",
mode: "development",
target: "web",
experiments: {
css: true
},
module: {
rules: [
{
test: /\.svg$/,
type: "asset/bytes"
}
]
}
},
{
name: "node",
mode: "development",
target: "node",
experiments: {
css: true
},
module: {
rules: [
{
test: /\.svg$/,
type: "asset/bytes"
}
]
}
},
{
name: "universal",
mode: "development",
target: ["web", "node"],
experiments: {
outputModule: true,
css: true
},
module: {
rules: [
{
test: /\.svg$/,
type: "asset/bytes"
}
]
}
}
];

View File

@ -0,0 +1,9 @@
"use strict";
module.exports = function supportsTextDecoder() {
try {
return typeof TextDecoder !== "undefined";
} catch (_err) {
return false;
}
};

View File

@ -130,11 +130,11 @@ class TestRunner {
/** @type {EXPECTED_ANY} */
this._globalContext = this.createBaseGlobalContext();
/** @type {EXPECTED_ANY} */
this._esmContext = this.createBaseEsmContext();
/** @type {EXPECTED_ANY} */
this._moduleScope = this.createBaseModuleScope();
/** @type {ModuleRunner} */
this._moduleRunners = this.createModuleRunners();
/** @type {EXPECTED_ANY} */
this._esmContext = this.createBaseEsmContext();
}
/**
@ -153,7 +153,14 @@ class TestRunner {
* @returns {EXPECTED_ANY} globalContext
*/
createBaseGlobalContext() {
const base = { console, expect, setTimeout, clearTimeout };
const base = {
console,
expect,
setTimeout,
clearTimeout,
setInterval,
clearInterval
};
Object.assign(base, this.setupEnv());
return base;
}
@ -216,6 +223,7 @@ class TestRunner {
global,
process,
setTimeout,
clearTimeout,
setImmediate,
URL,
Buffer
@ -550,6 +558,16 @@ class TestRunner {
outputDirectory
}),
URL,
TextEncoder:
typeof TextEncoder !== "undefined"
? TextEncoder
: // eslint-disable-next-line n/prefer-global/text-encoder
require("util").TextEncoder,
TextDecoder:
typeof TextDecoder !== "undefined"
? TextDecoder
: // eslint-disable-next-line n/prefer-global/text-decoder
require("util").TextDecoder,
EventSource,
clearTimeout,
fetch

16
types.d.ts vendored
View File

@ -5917,6 +5917,11 @@ declare interface GeneratorOptionsByModuleTypeKnown {
*/
asset?: AssetGeneratorOptions;
/**
* No generator options are supported for this module type.
*/
"asset/bytes"?: EmptyGeneratorOptions;
/**
* Generator options for asset/inline modules.
*/
@ -5927,6 +5932,11 @@ declare interface GeneratorOptionsByModuleTypeKnown {
*/
"asset/resource"?: AssetResourceGeneratorOptions;
/**
* No generator options are supported for this module type.
*/
"asset/source"?: EmptyGeneratorOptions;
/**
* Generator options for css modules.
*/
@ -12934,6 +12944,11 @@ declare interface ParserOptionsByModuleTypeKnown {
*/
asset?: AssetParserOptions;
/**
* No parser options are supported for this module type.
*/
"asset/bytes"?: EmptyParserOptions;
/**
* No parser options are supported for this module type.
*/
@ -18436,6 +18451,7 @@ declare namespace exports {
export let system: "__webpack_require__.System";
export let systemContext: "__webpack_require__.y";
export let thisAsExports: "top-level-this-exports";
export let toBinary: "__webpack_require__.tb";
export let uncaughtErrorHandler: "__webpack_require__.oe";
export let wasmInstances: "__webpack_require__.w";
}