8000 Globals TextEncoder and TextDecoder are not accessible from inside template code · Issue #1747 · jantimon/html-webpack-plugin · GitHub
[go: up one dir, main page]

Skip to content
Globals TextEncoder and TextDecoder are not accessible from inside template code #1747
@Josan-Coba

Description

@Josan-Coba

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 🤷🏼‍♀️

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0