Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
icelam committed Jun 2, 2023
2 parents 3060595 + 7c38441 commit 7aff2e7
Show file tree
Hide file tree
Showing 16 changed files with 802 additions and 349 deletions.
10 changes: 10 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,13 @@ updates:
reviewers:
- "icelam"
open-pull-requests-limit: 10
- package-ecosystem: "github-actions"
directory: "/"
target-branch: "develop"
schedule:
interval: "monthly"
commit-message:
prefix: "ci"
rebase-strategy: "auto"
reviewers:
- "icelam"
8 changes: 4 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,16 @@ jobs:
HUSKY: 0
steps:
- name: Checkout repo
uses: actions/checkout@main
uses: actions/checkout@v3
- name: Setup Node.js version ${{ matrix.node-version }}
uses: actions/setup-node@main
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT
- name: Restore yarn cache
uses: actions/cache@v1
uses: actions/cache@v3
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
Expand Down
46 changes: 46 additions & 0 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
name: "CodeQL"

on:
push:
branches:
- master
- develop
tags-ignore:
- '**' #prevent double build on release tag
pull_request:
branches:
- '**'
schedule:
- cron: "14 14 * * 0"

jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write

strategy:
fail-fast: false
matrix:
language: [javascript]

steps:
- name: Checkout
uses: actions/checkout@v3

- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
queries: +security-and-quality

- name: Autobuild
uses: github/codeql-action/autobuild@v2

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
with:
category: "/language:${{ matrix.language }}"
4 changes: 2 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ jobs:

steps:
- name: Checkout repo
uses: actions/checkout@main
uses: actions/checkout@v3
- name: Setup Node.js version
uses: actions/setup-node@main
uses: actions/setup-node@v3
with:
node-version-file: '.nvmrc'

Expand Down
1 change: 0 additions & 1 deletion .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ commitlint.config.js
yarn-error.log
yarn.lock
.github
lgtm.yml
/__tests__
.husky
/scripts
Expand Down
60 changes: 42 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
[![Install size](https://packagephobia.com/badge?p=html-inline-script-webpack-plugin)](https://packagephobia.com/result?p=html-inline-script-webpack-plugin)
![ci](https://github.com/icelam/html-inline-script-webpack-plugin/workflows/ci/badge.svg)
[![Package quality](https://npm.packagequality.com/shield/html-inline-script-webpack-plugin.svg)](https://packagequality.com/#?package=html-inline-script-webpack-plugin)
[![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/icelam/html-inline-script-webpack-plugin.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/icelam/html-inline-script-webpack-plugin/context:javascript)

[![NPM](https://nodei.co/npm/html-inline-script-webpack-plugin.png?compact=true)](https://npmjs.org/package/html-inline-script-webpack-plugin)

Expand All @@ -17,35 +16,19 @@ Inspired by [react-dev-utils](https://github.com/facebook/create-react-app/blob/

### Webpack5

#### NPM

```bash
npm i html-inline-script-webpack-plugin -D
```

#### Yarn

```bash
yarn add html-inline-script-webpack-plugin -D
```

### Webpack4

#### NPM

```bash
npm i html-inline-script-webpack-plugin@^1 -D
```

#### Yarn

```bash
yarn add html-inline-script-webpack-plugin@^1 -D
```

## Usage

By default, the plugin will convert all the external script files to inline script block.
By default, the plugin will convert all the external script files to inline script block, and remove the original script file from build assets.

```js
const HtmlWebpackPlugin = require('html-webpack-plugin');
Expand All @@ -64,6 +47,7 @@ Below are lists of options supported by this plugin:
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| scriptMatchPattern | List of script files that should be processed and inject as inline script. This will be filtered using the output file name. | RegExp[] |
| htmlMatchPattern | List of HTML template files that should be processed by this plugin. Useful when you have multiple `html-webpack-plugin` initialized. This will be filtered using the [`options?.filename`](https://github.com/jantimon/html-webpack-plugin#options) provided by `html-webpack-plugin`. | RegExp[] |
| assetPreservePattern | List of script files that should be preserved by this plugin after inserting them inline. This will be filtered using the output file name. | RegExp[] |

Here are some examples illustrating how to use these options:

Expand Down Expand Up @@ -129,3 +113,43 @@ module.exports = {
],
};
```
##### Process any script files but preserve `main.js` from build assets

```js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlInlineScriptPlugin = require('html-inline-script-webpack-plugin');

module.exports = {
plugins: [
new HtmlWebpackPlugin(),
new HtmlInlineScriptPlugin({
assetPreservePattern: [/main.js$/],
}),
],
};
```

## Contributors

Thanks goes to these wonderful people:

<table>
<tbody>
<tr>
<td align="center" valign="top" width="20%">
<a href="https://github.com/kmalakoff">
<img src="https://avatars.githubusercontent.com/u/756520?s=120&v=4" width="60px;" alt="@kmalakoff"/>
<br />
<b>@kmalakoff</b>
</a>
</td>
<td align="center" valign="top" width="20%">
<a href="https://github.com/SorsOps">
<img src="https://avatars.githubusercontent.com/u/80043879?s=120&v=4" width="60px;" alt="@kmalakoff"/>
<br />
<b>@SorsOps</b>
</a>
</td>
</tr>
</tbody>
</table>
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;
6 changes: 0 additions & 6 deletions lgtm.yml

This file was deleted.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
"eslint": "^7.4.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-jest": "^26.1.1",
"eslint-plugin-jest": "^27.1.4",
"husky": "^8.0.1",
"install-peers-cli": "^2.2.0",
"jest": "^26.6.3",
Expand Down
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
Loading

0 comments on commit 7aff2e7

Please sign in to comment.