如何将React组件捆绑为可用于服务器端渲染的NPM包?

时间:2020-07-29 19:12:40

标签: javascript reactjs npm webpack server-side-rendering

我创建了一个React组件,并将其作为软件包发布在NPM上。它按客户端的计划工作,但是,当我尝试对next.js执行ssr时,它崩溃并显示错误ReferenceError: document is not defined。通过简单的搜索,我发现我的捆绑包和组件取决于document的存在。重要的是要注意我的程序包不使用react-dom。

我如何将组件与webpack捆绑在一起,以便可以将该包导入并在ssr应用程序中使用?

我尝试更改target和libraryTarget,但无法实现所需的功能。另外,通过研究,我发现人们经常在其程序包中编写两个不同的代码以进行客户端和服务器端渲染。但是,我找不到如何为ssr编写react组件以及如何将其排除在文档之外。如果确实需要为服务器编写React组件,那该怎么办呢?

以下是我要发送的Webpack配置。

Webpack

const nodeExternals = require('webpack-node-externals')

const web = {
  mode: 'production',
  entry: './src/index.ts',
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'index.js',
    libraryTarget: 'commonjs2',
  },
  resolve: {
    extensions: ['.ts', '.tsx'],
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: path.resolve(__dirname, 'src'),
        exclude: /(node_modules|bower_components)/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-env'],
            },
          },
        ],
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.ts$|.tsx$/,
        use: 'ts-loader',
      },
    ],
  },
  externals: {
    react: 'commonjs react',
    'react-apollo': 'commonjs react-apollo',
    graphql: 'commonjs graphql',
    'graphql-tag': 'commonjs graphql-tag',
  },
}

const node = {
  mode: 'production',
  entry: './src/index.ts',
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'index.node.js',
    libraryTarget: 'commonjs2',
  },
  resolve: {
    extensions: ['.ts', '.tsx'],
  },
  target: 'node',
  module: {
    rules: [
      {
        test: /\.js$/,
        include: path.resolve(__dirname, 'src'),
        exclude: /(node_modules|bower_components)/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-env'],
            },
          },
        ],
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.ts$|.tsx$/,
        use: 'ts-loader',
      },
    ],
  },
  externals: [
    nodeExternals(),
    {
      react: 'commonjs react',
      'react-apollo': 'commonjs react-apollo',
      graphql: 'commonjs graphql',
      'graphql-tag': 'commonjs graphql-tag',
    },
  ],
}

module.exports = [web, node]```

0 个答案:

没有答案