Dependency management of outputted UMD files

197 Views Asked by At

I'm looking to take an NPM package and output it as UMD so it can be used directly in browser, via a script tag or SystemJS import.

The issue I have is that the NPM package is a react-component library, meaning it has dependencies on react and react-dom. The package itself marks both react and react-dom as peer dependencies.

If I update webpack.config.js with

externals: ['react-spinners']

and load the umd file via a script tag

<script crossorigin src="https://unpkg.com/[email protected]/umd/index.js"></script>

I get an error say

ReferenceError: react is not defined

Is there a way to use tsc to output a UMD module and specify certain dependencies are necessary? something along the lines of

tsc --project tsconfig.umd.json --outDir umd --addDeps react,react-dom

so that when this package is loaded, it'll check both react and react-dom exist first before executing?

      <script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
      <script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
      <script src="https://unpkg.com/[email protected]/umd/index.js"></script>

i tried something like this but still received the same react error

build command

"build:umd": "tsc --project tsconfig.umd.json --outDir umd"

tsconfig

{
  "compilerOptions": {
    "alwaysStrict": true,
    "sourceMap": false,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "module": "umd",
    "jsx": "react",
    "target": "es5",
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "declaration": true,
    "lib": ["dom", "es2017", "es5", "es6", "es7"],
    "outDir": ".",
    "strict": true,
    "noImplicitAny": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true
  },
  "exclude": ["docs/*", "webpack.config.*", "*.js", "__tests__", "examples"]
}

peer deps

  "peerDependencies": {
    "react": "^16.0.0 || ^17.0.0",
    "react-dom": "^16.0.0 || ^17.0.0"
  },
0

There are 0 best solutions below