首页 > 解决方案 > 在浏览器中使用时,汇总的 UMD 模块输出为空对象

问题描述

我正在尝试使用 Rollup 制作一个 npm 包的 umd 版本。我已经设置了汇总配置,它似乎产生了一个有效的 umd 输出,但是当我将它加载到脚本标签中并尝试在浏览器中进行控制台登录时,我得到一个空对象。我克隆的包是react-native-web(我克隆它的原因是因为 repo 的所有者说他们不打算支持 UMD 构建)。我的 repo 版本可在此处获得:https ://github.com/ChristopherHButler/react-native-umd 。我认为在此处粘贴内联源代码没有意义,但如果有人想克隆它以查看,我将添加汇总配置、输出链接以及在项目中运行的正确命令,即:npm run prepublish. 该包也发布到 npm 并且 umd 构建在 jsDelivr 上可用:https ://www.jsdelivr.com/package/npm/react-native-umd 。在测试期间,我将它添加到这样的页面中:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
  <script src="https://cdn.jsdelivr.net/npm/react-is@17.0.2/umd/react-is.development.js" crossorigin></script>
  <script src="./dist/umd/index.umd.js"></script>
</head>
<body>
  <Script type="text/javascript">
    console.log(window.ReactNative)
  </Script>
</body>
</html>

最后我的汇总配置:

/* eslint-disable */
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import json from '@rollup/plugin-json';
import { terser } from 'rollup-plugin-terser';

import packageJSON from './package.json';


const config = {
  input: './packages/react-native-web/dist/index.js',
  output: [
    {
      file: packageJSON.browser, // file: './packages/react-native-web/dist/umd/index.umd.js',
      format: 'umd',
      name: 'ReactNative',
      sourcemap: true,
      globals: {
        react: "React",
        ['react-dom']: "ReactDOM",
        ['react-is']: "ReactIs",
      }
    }
  ],
  plugins: [
    resolve({ extensions: ['.jsx', '.js', '.tsx', 'ts'] }),
    commonjs(), // To use CommonJS syntax
    json(),     // To import json
  ],
  external: ['react', 'react-is', 'react-dom']
};

// Set the environment variable before you run the build command:
// > NODE_ENV=production npm run build
if (process.env.NODE_ENV === 'production') {
  config.plugins.push(terser());
}

export default config;

标签: react-nativenpmrollupjsumd

解决方案


推荐阅读