57 lines
1.6 KiB
JavaScript
57 lines
1.6 KiB
JavaScript
'use strict';
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const HtmlWebpackPlugin = require('html-webpack-plugin');
|
|
|
|
class InjectScriptWebpackPlugin {
|
|
constructor(options = {}) {
|
|
this.injectsDir = options.injectsDir || './injects';
|
|
}
|
|
|
|
apply(compiler) {
|
|
compiler.hooks.compilation.tap('InjectScriptWebpackPlugin', (compilation) => {
|
|
HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync(
|
|
'InjectScriptWebpackPlugin',
|
|
(data, cb) => {
|
|
const injectScripts = this.getInjectScripts();
|
|
|
|
if (injectScripts.length > 0) {
|
|
const scriptsToInject = injectScripts.map(script =>
|
|
`<script>${script}</script>`
|
|
).join('\n');
|
|
|
|
// 在</body>标签前插入脚本
|
|
data.html = data.html.replace('</body>', `${scriptsToInject}</body>`);
|
|
}
|
|
|
|
cb(null, data);
|
|
}
|
|
);
|
|
});
|
|
}
|
|
|
|
getInjectScripts() {
|
|
const injectScripts = [];
|
|
// 使用 __dirname 获取当前文件的目录
|
|
const injectsPath = path.resolve(__dirname, this.injectsDir);
|
|
|
|
if (fs.existsSync(injectsPath)) {
|
|
const files = fs.readdirSync(injectsPath);
|
|
|
|
files.forEach(file => {
|
|
if (path.extname(file).toLowerCase() === '.js') {
|
|
const filePath = path.join(injectsPath, file);
|
|
const content = fs.readFileSync(filePath, 'utf-8');
|
|
injectScripts.push(content);
|
|
}
|
|
});
|
|
} else {
|
|
console.warn(`Injects directory not found: ${injectsPath}`);
|
|
}
|
|
|
|
return injectScripts;
|
|
}
|
|
}
|
|
|
|
module.exports = InjectScriptWebpackPlugin;
|