dungreact
dungreact

Reputation: 534

How to fix ReferenceError: window is not defined in ReactJS

I'm using tui-calendar for my project https://github.com/nhn/toast-ui.react-calendar and got bug "ReferenceError: window is not defined" when I try to "yarn start"

})(window, function(__WEBPACK_EXTERNAL_MODULE_tui_code_snippet__, __WEBPACK_EXTERNAL_MODULE_tui_date_picker__) {
   ^

ReferenceError: window is not defined
    at Object.<anonymous> (C:\Users\Thao\Documents\Github\App\node_modules\tui-calendar\dist\tui-calendar.js:16:4)
    at Module._compile (internal/modules/cjs/loader.js:1200:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
    at Module.load (internal/modules/cjs/loader.js:1049:32)
    at Function.Module._load (internal/modules/cjs/loader.js:937:14)
    at Module.require (internal/modules/cjs/loader.js:1089:19)
    at require (internal/modules/cjs/helpers.js:73:18)
    at eval (webpack:///external_%22tui-calendar%22?:1:18)
    at Object.tui-calendar (C:\Users\Thao\Documents\Github\App\build\server.js:21026:1)
    at __webpack_require__ (C:\Users\Thao\Documents\Github\App\build\server.js:21:30)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

If I add Calendar component while the project is running so it's work.

import Calendar from "@toast-ui/react-calendar";

but it's can't start with "yarn start"

What is the root cause? Thanks

Upvotes: 3

Views: 8509

Answers (2)

Yilmaz
Yilmaz

Reputation: 49361

 yarn start 

I believe it is causing because of start script. You might be building app and then and your start script is like this:

"start":"node build/bundle.js" // path of bundle. 

When you do that there is no browser environment. "bundle.js" is just a regular javascript file, and in that file window is used but window is defined only in browser. So you have to serve your file with a server. Easier way, for development, use webpack-dev-server. Here is the config that you should add to the webpack.config.js:

devServer: {
historyApiFallback: true,
contentBase: path.join(__dirname, "build"), // build is output folder 
overlay: true,
 },

this is script that you should set in package.json:

 "start":""webpack-dev-server --open"

It will automatically open the browser at port 8080. This is for development environment. In production you should set a custom server like express server.

Upvotes: 0

AnLuoRidge
AnLuoRidge

Reputation: 76

I saw \build\server.js in your error log. So, the root cause is highly likely the SSR.

Your UI component is either not compatible with SSR or not correctly configured. When you run yarn start, there's no window object at server side. But as you noticed, you could still make it work by importing it in a running project, whose pages have been already rendered in the browser.

Upvotes: 3

Related Questions