简体   繁体   中英

document is not defined, react ssr

I am using react and doing server-side rendering using node but when I run my server.js file, I get this error that the document is not defined. Here I know that in node document does not exist like on the browser, what should I do to solve this error?

THIS IS MY WEBPACK.SERVER.JS FILE

const path = require('path');
const nodeExternals = require('webpack-node-externals');
module.exports = {
    entry: './server/index.js',
    target: 'node',
    externals: [nodeExternals()],
    output: {
      path: path.resolve('server-build'),
      filename: '[name].js',
      chunkFilename: '[id].[chunkhash].js'

},
module: {
    rules: [
        {
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            use: 'babel-loader'
        },
        {
            test: /\.css$/,
            use: ['style-loader', 'css-loader']
        },
        {
            test: /\.(jpg|png|gif|woff|woff2|eot|ttf|svg)$/,
            use: {
                loader: 'file-loader',
                options: {
                    name: '[name].[ext]'
                }
            }
        }
    ]
},
resolve: {
    extensions: ['.js', '.jsx', '*']
},
optimization: {
    splitChunks: {
        cacheGroups: {
            vendor: {
                test: /node_modules/,
                name: 'vendor',
                chunks: 'initial',
                enforce: true
            }
        }
    }
}

}

THIS IS THE ERROR I AM GETTING

[nodemon] starting node./server-build/main.js webpack://frontend/./node_modules/style-loader/dist/runtime/insertStyleElement.js?:5

var element = document.createElement("style"); ^

ReferenceError: document is not defined at Object.insertStyleElement (webpack://frontend/./node_modules/style-loader/dist/runtime/insertStyleElement.js?:5:17) at Object.domAPI (webpack://frontend/./node_modules/style-loader/dist/runtime/styleDomAPI.js?:59:30)
at addElementStyle (webpack://frontend/./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.

You have 3 options:

  1. Move the code to the client, if you want to change the DOM elements. Because document relates to the DOM (Document Object Model) in a web browser.

  2. Use an external library like jsdom .

  3. Use something like browserify to include Node.js modules in your client-side code (not recommended in you case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM