jantimon/html-webpack-plugin

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 ?

Let's fix it, I agree, it is a bug