Globals TextEncoder and TextDecoder are not accessible from inside template code
Josan-Coba opened this issue ยท 3 comments
Current behaviour ๐ฃ
Globals TextEncoder
and TextDecoder
are not accessible from inside template code.
I'm currently using react as a template builder via renderToStaticMarkup()
, but after updating to v18 it started complaining that 'ReferenceError: TextEncoder is not defined'.
Both of them should be available as globals in nodejs v12+ but after some research I've found that when the plugin runs vm.createContext()
( https://github.com/jantimon/html-webpack-plugin/blob/main/index.js#L131 ) the global
object is being copied with { ...global }
and so only its enumerable properties are being passed along.
Expected behaviour โ๏ธ
Globals should be available inside template code
Reproduction Example ๐พ
Reproducing the error only requires calling TextEncoder from inside a template:
package.json
{
"devDependencies": {
"html-webpack-plugin": "5.5.0",
"webpack": "5.72.0",
"webpack-cli": "4.9.2"
}
}
webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
plugins: [
new HtmlWebpackPlugin({
template: 'src/template.js',
}),
],
}
src/template.js
export default function template() {
const encoder = new TextEncoder()
}
Environment ๐ฅ
$ node -e "var os=require('os');console.log('Node.js ' + process.version + '\n' + os.platform() + ' ' + os.release())"
Node.js v14.19.1
linux 5.10.102.1-microsoft-standard-WSL2
$ npm --version
8.9.0
$ npm ls webpack
test-repo@ /home/josan/projects/test-repo
โโโฌ html-webpack-plugin@5.5.0
โ โโโ webpack@5.72.0 deduped
โโโฌ webpack-cli@4.9.2
โ โโโฌ @webpack-cli/configtest@1.1.1
โ โ โโโ webpack@5.72.0 deduped
โ โโโ webpack@5.72.0 deduped
โโโฌ webpack@5.72.0
โโโฌ terser-webpack-plugin@5.3.1
โโโ webpack@5.72.0 deduped
$ npm ls html-webpack-plugin
test-repo@ /home/josan/projects/test-repo
โโโ html-webpack-plugin@5.5.0
Possible fix
I have added both TextEncoder and TextDecoder to the context and it effectively fixes my original problem ( https://github.com/Josan-Coba/html-webpack-plugin/blob/main/index.js#L138 ) without breaking anything (const { TextEncoder, TextDecoder } = require('util');
is required if nodejs v10 is to be supported).
I have also tried to add every non-enumerable global to the context, but it makes some tests fail ๐คท๐ผโโ๏ธ
I have the same problem. Is it possible to fix without forking the html-webpack-plugin
?
Thanks Josan-Coba it's a forked one
https://www.npmjs.com/package/html-webpack-plugin-react-18
Let's fix it, I agree, it is a bug