UNPKG

2.45 kBPlain TextView Raw
1import { resolve } from 'path';
2import { Plugin, Compiler, BannerPlugin, DefinePlugin } from 'webpack';
3import { wrapPilet, setEnvironment, getDefineVariables, getVariables } from './helpers';
4
5const pluginName = 'PiletWebpackPlugin';
6
7export interface PiletWebpackPluginOptions {
8 variables?: Record<string, string>;
9}
10
11export class PiletWebpackPlugin implements Plugin {
12 constructor(private piletPackage: any, private options: PiletWebpackPluginOptions = {}) {}
13
14 apply(compiler: Compiler) {
15 const piletPkg = this.piletPackage;
16 const shellPkg = require(`${piletPkg.piral.name}/package.json`);
17 const shortName = piletPkg.name.replace(/\W/gi, '');
18 const jsonpFunction = `pr_${shortName}`;
19 const environment = process.env.NODE_ENV || 'development';
20 const piralExternals = shellPkg.pilets?.externals ?? [];
21 const piletExternals = piletPkg.externals ?? [];
22 const peerDependencies = Object.keys(piletPkg.peerDependencies ?? {});
23 const externals = [...piralExternals, ...piletExternals, ...peerDependencies];
24 const variables = {
25 ...getVariables(piletPkg, environment),
26 ...this.options.variables,
27 };
28 const plugins = [
29 new BannerPlugin({
30 banner: `//@pilet v:1(${jsonpFunction})`,
31 entryOnly: true,
32 raw: true,
33 }),
34 new DefinePlugin(getDefineVariables(variables)),
35 ];
36
37 setEnvironment(variables);
38
39 plugins.forEach(plugin => plugin.apply(compiler));
40
41 compiler.hooks.done.tap(pluginName, statsData => {
42 if (!statsData.hasErrors()) {
43 const { path, filename } = compiler.options.output;
44
45 if (typeof filename === 'string') {
46 const file = resolve(path, filename);
47 wrapPilet(file, jsonpFunction);
48 } else {
49 const [main] = statsData.compilation.chunks.filter(m => m.entryModule).map(m => m.files[0]);
50 const file = resolve(compiler.outputPath, main);
51 wrapPilet(file, jsonpFunction);
52 }
53 }
54 });
55
56 compiler.hooks.afterEnvironment.tap(pluginName, () => {
57 const current = compiler.options.externals;
58 compiler.options.output.jsonpFunction = jsonpFunction;
59 compiler.options.output.libraryTarget = 'umd';
60 compiler.options.output.library = piletPkg.name;
61 compiler.options.externals = Array.isArray(current)
62 ? [...current, ...externals]
63 : current
64 ? [current, ...externals]
65 : externals;
66 });
67 }
68}