我想根据生成的资产生成一个页面。所以我创建了一个 Webpack 插件。
import { readFile } from 'fs';
import webpack, { Plugin } from 'webpack';
import ejs from 'ejs';
interface Configuration {
template: string;
}
interface Assets {
[key: string]: {
source: () => string,
size: () => number
}
}
class BookmarkletPagePlugin implements Plugin {
public constructor(protected configuration: Configuration) { }
public apply(compiler: webpack.Compiler) {
compiler.hooks.emit.tapAsync('BookmarkletPagePlugin', (compilation, callback) => {
readFile(this.configuration.template, 'utf8', (_err, template) => {
const assets = compilation.assets as Assets;
const data = {bookmarklets: []};
const page = ejs.render(template, data);
assets['index.html'] = {
source: () => page,
size: () => page.length
};
compilation.assets = assets;
console.log(compilation.assets);
});
callback();
});
}
}
export = BookmarkletPagePlugin;
它可以工作,但不会生成新资产index.html
。日志的输出是:
yarn run v1.22.5
$ webpack --config webpack.config.ts --mode production
{
'informAboutAbsentee.js': RawSource {
_value: 'javascript:(function(){!function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=0)}([function(e,t){alert("joho")}]);})();',
existsAt: '/home/codespace/workspace/zli-bookmarklets/dist/informAboutAbsentee.js',
emitted: true
},
'index.md': { source: [Function: source], size: [Function: size] }
}
Hash: 195cb165b27f63c3d5a8
Version: webpack 4.44.2
Time: 54ms
Built at: 09/24/2020 6:42:40 AM
Asset Size Chunks Chunk Names
informAboutAbsentee.js 971 bytes 0 [emitted] informAboutAbsentee
+ 1 hidden asset
Entrypoint informAboutAbsentee = informAboutAbsentee.js
[0] ./src/informAboutAbsentee.ts 15 bytes {0} [built]
Done in 2.50s.
我从官方教程中获取了大部分内容:https ://webpack.js.org/contribute/writing-a-plugin/#example
我的最后一个问题:为什么index.html
不发出?