如何解决通过用TypeScript编写的Webpack插件创建其他资产
我想根据生成的资产生成一个页面。所以我创建了一个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,{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",value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,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
没有发出?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。