Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions __tests__/HtmlInlineScriptPlugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import webpack from 'webpack';
import Self from '../dist';

import simpleConfig from './cases/simple/webpack.config';
import preserveConfig from './cases/preserveAsset/webpack.config';
import multipleInstanceConfig from './cases/multiple-instance/webpack.config';
import jsWithImportConfig from './cases/js-with-import/webpack.config';
import webWorkerConfig from './cases/web-worker/webpack.config';
Expand Down Expand Up @@ -48,6 +49,40 @@ describe('HtmlInlineScriptPlugin', () => {
await webpackPromise;
});

it('should preserve the output of an asset if requested', async () => {
const webpackPromise = new Promise((resolve) => {
const compiler = webpack(preserveConfig);
console.log(preserveConfig)

compiler.run((error, stats) => {
expect(error).toBeNull();

const statsErrors = stats?.compilation.errors;
expect(statsErrors?.length).toBe(0);

const result = fs.readFileSync(
path.join(__dirname, 'cases/preserveAsset/dist/index.html'),
'utf8',
);

const expected = fs.readFileSync(
path.join(__dirname, 'cases/preserveAsset/expected/index.html'),
'utf8',
);
expect(result).toBe(expected);

const expectedFileList = fs.readdirSync(path.join(__dirname, 'cases/preserveAsset/expected/'));
const generatedFileList = fs.readdirSync(path.join(__dirname, 'cases/preserveAsset/dist/'));
expect(expectedFileList.sort()).toEqual(generatedFileList.sort());

resolve(true);
});
});

await webpackPromise;
});


it('should build webpack config having multiple HTML webpack plugin instance without error', async () => {
const webpackPromise = new Promise((resolve) => {
const compiler = webpack(multipleInstanceConfig);
Expand Down
1 change: 1 addition & 0 deletions __tests__/cases/preserveAsset/expected/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"/><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><meta name="language" content="English"/><meta http-equiv="X-UA-Compatible" content="IE=edge"/><meta name="viewport" content="minimum-scale=1,initial-scale=1,width=device-width,shrink-to-fit=no"/><title>webpack test</title><script defer="defer">console.log("Hello world");</script></head><body><p>This is minimal code to demonstrate webpack usage</p></body></html>
1 change: 1 addition & 0 deletions __tests__/cases/preserveAsset/expected/ui.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log("Hello world");
14 changes: 14 additions & 0 deletions __tests__/cases/preserveAsset/fixtures/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="language" content="English" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no" />
<title>webpack test</title>
</head>
<body>
<p>This is minimal code to demonstrate webpack usage</p>
</body>
</html>
2 changes: 2 additions & 0 deletions __tests__/cases/preserveAsset/fixtures/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// eslint-disable-next-line no-console
console.log('Hello world');
26 changes: 26 additions & 0 deletions __tests__/cases/preserveAsset/webpack.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import path from 'path';
import type { Configuration } from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import Self from '../../../dist';

const config: Configuration = {
mode: 'production',
entry: {
ui: path.join(__dirname, './fixtures/index.js')
},
output: {
path: path.join(__dirname, './dist'),
filename: '[name].js'
},
plugins: [
new HtmlWebpackPlugin({
chunks: ['ui'],
template: path.resolve(__dirname, './fixtures/index.html')
}),
new Self({
assetPreservePattern: [/^ui[.]js$/]
})
]
};

export default config;
18 changes: 16 additions & 2 deletions src/HtmlInlineScriptPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { PLUGIN_PREFIX } from './constants';
export type PluginOptions = {
scriptMatchPattern?: RegExp[];
htmlMatchPattern?: RegExp[];
assetPreservePattern?: RegExp[];
};

class HtmlInlineScriptPlugin implements WebpackPluginInstance {
Expand All @@ -18,6 +19,8 @@ class HtmlInlineScriptPlugin implements WebpackPluginInstance {

ignoredHtmlFiles: string[];

assetPreservePattern: NonNullable<PluginOptions['assetPreservePattern']>;

constructor(options: PluginOptions = {}) {
if (options && Array.isArray(options)) {
// eslint-disable-next-line no-console
Expand All @@ -33,12 +36,14 @@ class HtmlInlineScriptPlugin implements WebpackPluginInstance {

const {
scriptMatchPattern = [/.+[.]js$/],
htmlMatchPattern = [/.+[.]html$/]
htmlMatchPattern = [/.+[.]html$/],
assetPreservePattern = [],
} = options;

this.scriptMatchPattern = scriptMatchPattern;
this.htmlMatchPattern = htmlMatchPattern;
this.processedScriptFiles = [];
this.assetPreservePattern = assetPreservePattern;
this.ignoredHtmlFiles = [];
}

Expand All @@ -48,6 +53,13 @@ class HtmlInlineScriptPlugin implements WebpackPluginInstance {
return this.scriptMatchPattern.some((test) => assetName.match(test));
}

isFileNeedsToBePreserved(
assetName: string
): boolean {
return this.assetPreservePattern.some((test) => assetName.match(test));
}


shouldProcessHtml(
templateName: string
): boolean {
Expand Down Expand Up @@ -120,7 +132,9 @@ class HtmlInlineScriptPlugin implements WebpackPluginInstance {
}, (assets) => {
if (this.ignoredHtmlFiles.length === 0) {
this.processedScriptFiles.forEach((assetName) => {
delete assets[assetName];
if (!this.isFileNeedsToBePreserved(assetName)) {
delete assets[assetName];
}
});
}
});
Expand Down