Webpack 2:静态站点生成器插件“自身未定义”

Ent*_*Guy 4 reactjs webpack webpack-2

我在static-site-generator-webpack-plugin上遇到了一些问题。

在我的项目中,我正在使用:

  • webpack v2.1.0-beta.27
  • 静态站点生成器Webpack插件 v3.1.0
  • react and react-dom v15.4.1

这是一个单页网站。

这是webpack.config.babel.js文件的一部分:

import StaticSiteGeneratorPlugin from 'static-site-generator-webpack-plugin'
  
export default {
    entry: {
        main: './components/Root/index.jsx',
    },
    output: {
        path: path.join(process.cwd(), './public'),
        filename: '[name].[hash].js',
        libraryTarget: 'umd',
    },
  
      plugins: [
        // ...
        new StaticSiteGeneratorPlugin('main', '/', {}),
      ]
        // ...
  }
Run Code Online (Sandbox Code Playgroud)

这是./components/Root/index.jsx文件:

import React from 'react'
import ReactDOMServer from 'react-dom/server'
import HTMLDocument from 'react-html-document'

import App from '../App/index.jsx'

export default function (locals, callback) {
    const MyHtml = (
        <HTMLDocument
            title='My Page'
            metatags={[
              { name: 'description', content: 'My description' },
            ]}
            scripts={[ `${locals.assets.main}` ]}>
            <App />
        </HTMLDocument>
    )

    const html = ReactDOMServer.renderToStaticMarkup(MyHtml, locals.assets)
    callback(null, '<!doctype html>' + html)
}
Run Code Online (Sandbox Code Playgroud)

当我尝试使用它时,我会看到错误消息:ERROR in ReferenceError: self is not defined。这是什么意思?

Den*_*Den 6

我在webpack-dev-server中遇到了同样的错误。此错误的原因是在服务器上呈现。服务器没有对象self。您可以使用scope选项(https://github.com/markdalgleish/static-site-generator-webpack-plugin#scope),也可以避免在服务器上使用static-site-generator-webpack-plugin。

如果使用webpack-dev-server解决此错误,则必须进行设置inline: falsehttps://github.com/webpack/docs/wiki/webpack-dev-server#inline-mode)。如果要在没有iframe的情况下在根URL中使用热重装,只需将其添加<script src="http://localhost:8080/webpack-dev-server.js"></script>到页面中(https://github.com/webpack/docs/wiki/webpack-dev-server#inline-mode-in-html) 。