Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vue Webpack4 SSR server.bundle.js报错document is not defined #6

Open
SkyBlueFeet opened this issue Feb 14, 2020 · 1 comment
Open

Comments

@SkyBlueFeet
Copy link
Owner

SkyBlueFeet commented Feb 14, 2020

Vue Webpack4 SSR server.bundle.js 报错 document is not defined

Detailed description of the problem

  • 运行环境:Vue 服务端渲染(SSR)
  • 条件:使用异步组件
  • 前提条件:使用了mini-css-extract-pluginextract-css-chunks-webpack-plugin等用来抽取 CSS 代码的 webpack 插件
  • 错误:报错document is not defined
  • 位置: server bundle 等服务端打包后代码,

Problem Causes

是由于运行上述插件后异步导入组件时服务端代码会执行 document.createElement 方法插入 link 标签,但是此时 document 对象为 undefined,因此会出现该错误。作为验证,当你检查打包后的服务端代码时会发现有大量多余的 document 对象方法,服务端代码则无法运行。

Solution

Indirect Method:

  • 不使用异步组件
  • 使用 Babel 插件 babel-plugin-dynamic-import-node 将 import() 方法转化成 require

Direct Method:

  • 使用 vue-style-loader 替代,但是无法抽取 CSS 代码

  • null-loader or css-loader/locals (for CSS modules),未验证

  • 重写 mini-css-extract-plugingetCssChunkObject方法,已验证可完美解决

class ServerMiniCssExtractPlugin extends MiniCssExtractPlugin {
    getCssChunkObject(mainChunk) {
        return {};
    }
}

Reference

Unsolved

extract-css-chunks-webpack-plugin文档中提到该插件 SSR 友好,应当也会支持 SSR 的异步组件,但直接替换mini-css-extract-plugin并没有解决问题,不清楚是否需要进行特殊配置

Supplement

SkyBlueFeet added a commit that referenced this issue Feb 14, 2020
由于运行mini-css-extract-plugin提取CSS,异步导入组件时服务端代码会执行 document.createElement 方法插入 link 标签,但是此时 document
对象为 undefined,因此会出现该错误

fix #6
SkyBlueFeet added a commit that referenced this issue Feb 14, 2020
@ItsRyanWu
Copy link

ItsRyanWu commented May 29, 2020

for that unsolved problem you need to add

new webpack.optimize.LimitChunkCountPlugin({
    maxChunks: 1
})

in your webpack.server config file plugins then it just works

I don't know exactly what's the relation between them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants