How to add attribute to script tags? #1766
-
Hi, I'd like to add an I know Is adding a new webpack plugin as simple as appending it to // preact.config.js
import MyPlugin from './webpack-plugin.js';
export default function (config, env, helpers, options) {
// Is this how you add a Webpack plugin?
config.plugins.push(new MyPlugin());
} I tried doing this and am seeing some logs showing up from my plugin but not others: // webpack-plugin.js
import HtmlWebpackPlugin from 'html-webpack-plugin';
// Code adapted from README: https://github.com/jantimon/html-webpack-plugin#afteremit-hook
export default class MyPlugin {
apply(compiler) {
compiler.hooks.compilation.tap('MyPlugin', (compilation) => {
console.log('good news, this is logged');
HtmlWebpackPlugin.getHooks(compilation).alterAssetTags.tapAsync(
'MyPlugin',
(data, cb) => {
console.log('...but this is never logged!');
cb(null, data);
}
);
});
}
} It seems that the Thanks a million! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
I'll go through why this doesn't work first, feel free to skip to the end to get my recommended solution though. First things first, yes, that is a valid way to add a plugin to the Webpack config. However, Preact-CLI has two distinct builds: the server, bundling content for execution in Node to prerender your app, and the client, which is the stuff destined for the browser. As such, // preact.config.js
import MyPlugin from './webpack-plugin.js';
export default function (config, env, helpers, options) {
if (!env.isServer) {
config.plugins.push(new MyPlugin());
}
} Secondly, you're using an incorrect version of This should do the trick however: // Code adapted from README: https://github.com/jantimon/html-webpack-plugin#afteremit-hook
export default class MyPlugin {
apply(compiler) {
compiler.hooks.compilation.tap('MyPlugin', (compilation) => {
console.log('good news, this is logged');
compilation.hooks.htmlWebpackPluginAlterAssetTags.tapAsync(
'MyPlugin',
(data, cb) => {
console.log('great news, this is logged too!');
cb(null, data);
}
);
});
}
} But, is there a particular reason you are not just editing your If you weren't aware, This has the added benefit of not requiring you mess with Webpack plugins, but up to you of course. |
Beta Was this translation helpful? Give feedback.
I'll go through why this doesn't work first, feel free to skip to the end to get my recommended solution though.
First things first, yes, that is a valid way to add a plugin to the Webpack config. However, Preact-CLI has two distinct builds: the server, bundling content for execution in Node to prerender your app, and the client, which is the stuff destined for the browser. As such,
html-webpack-plugin
is not ran on the server builds (as HTML is strictly for the browser). We'd adjust your config to look like the following: