样式加载器在React SSR中失败

时间:2020-07-18 05:18:15

标签: javascript reactjs webpack server-side-rendering webpack-style-loader

创建了可重用的react库,当前它仅在客户端运行。如果尝试在服务器端运行,由于style-loader,它将抛出以下错误。基本上我想将css和js捆绑到单个文件(UMD)中。这样对于消费者来说将很容易。那可能吗?我考虑过样式化组件和情感js,但不确定是否会在主应用程序中创建任何其他依赖项。寻找更好的捆绑方式。

ReferenceError: window is not defined
at t (/Users/srisukum/Documents/dev/react-library/react-reusable-lib/build/index.js:1:1925)
at B (/Users/srisukum/Documents/dev/react-library/react-reusable-lib/build/index.js:1:2013)
at A.exports (/Users/srisukum/Documents/dev/react-library/react-reusable-lib/build/index.js:1:5558)
at Object.<anonymous> (/Users/srisukum/Documents/dev/react-library/react-reusable-lib/build/index.js:1:990)
at s (/Users/srisukum/Documents/dev/react-library/react-reusable-lib/build/index.js:1:62)
at Module.<anonymous> (/Users/srisukum/Documents/dev/react-library/react-reusable-lib/build/index.js:1:14364)
at s (/Users/srisukum/Documents/dev/react-library/react-reusable-lib/build/index.js:1:62)
at /Users/srisukum/Documents/dev/react-library/react-reusable-lib/build/index.js:1:861
at Object.<anonymous> (/Users/srisukum/Documents/dev/react-library/react-reusable-lib/build/index.js:1:870)
at Module._compile (internal/modules/cjs/loader.js:776:30)

Webpack.config.js

output: {
path: path.resolve(__dirname, 'build'),
filename: "index.js",
libraryTarget: 'commonjs2'
},
module: {
 rules: [
  {
    test: /\.js$/,
    exclude: /(node_modules|bower_components|build|dist)/,
    use: {
      loader: "babel-loader"
    }
  },
  {
    test: /\.css$/,
    use: [
      "style-loader",
      {
        loader: "css-loader",
        options: {
          modules: true
        }
      }
    ]
  },
  { 
    test: /\.(png|woff|woff2|eot|ttf|svg)$/, 
    loader: 'url-loader?limit=100000' 
  }
]
},
optimization: {
 minimizer: [
  new UglifyJsPlugin({
    cache: false,
    parallel: true,
    uglifyOptions: {
      compress: true,
      ecma: 6,
      mangle: true
    }
  })
 ]
},
externals: {
  'react': 'commonjs react'
}

1 个答案:

答案 0 :(得分:0)

您应该在SSR中使用isomorphic-style-loader