markdalgleish / react-to-html-webpack-plugin

Webpack plugin that renders React components to HTML files
MIT License
168 stars 14 forks source link

Avoiding ReferenceError for console and window objects #2

Closed pe3 closed 9 years ago

pe3 commented 9 years ago

I originally wrote an issue to css-modules/webpack-demo but now I understand this is the right repo. Is there any way to make the plugin easier to use?

  1. I run the demo with npm start
  2. If I add window.React = React; to src/index.js I get this error:
webpack: bundle is now INVALID.
evalmachine.<anonymous>:80
    console.log('hello');
    ^
ReferenceError: console is not defined
    at Object.<anonymous> (evalmachine.<anonymous>:80:2)
    at __webpack_require__ (evalmachine.<anonymous>:30:30)
    at Object.defineProperty.value (evalmachine.<anonymous>:50:18)
    at evalmachine.<anonymous>:53:10
    at webpackUniversalModuleDefinition (evalmachine.<anonymous>:3:20)
    at evalmachine.<anonymous>:10:3
    at ContextifyScript.Script.runInNewContext (vm.js:18:15)
    at module.exports (/private/tmp/webpack-demo/node_modules/react-to-html-webpack-plugin/node_modules/eval/eval.js:56:8)
    at ReactToHtmlWebpackPlugin.<anonymous> (/private/tmp/webpack-demo/node_modules/react-to-html-webpack-plugin/index.js:21:23)
    at Tapable.applyPluginsAsync (/private/tmp/webpack-demo/node_modules/webpack/node_modules/tapable/lib/Tapable.js:71:13)

Adding console.log('hello'); causes a similar error.

Can be avoided with:

if (typeof window !== 'undefined') {
  console.log('hello');
}

Could this be avoided somehow? It's a bit unconventional and can for example cause hard to understand problems for people who test you code.

pe3 commented 9 years ago

I would love to help if you can help me understand what to do. To me it seems the eval-module is throwing the error. For me something like this comes to mind:

var eval = require('eval')
var eval2 = function(str) {
    var cleared = str.replace(/console.*\)\;/, "");
    return _eval(cleared);
}
var res = eval2('var x = 123; console.log(x); exports.x = x')
console.log(res);
jokull commented 9 years ago

I’m getting a similar error. require is not defined.

markdalgleish commented 9 years ago

This should be fixed in v2.2.0. Please let me know if you're still having issues.