Webpack+SemanticUI+React遇process未定义,能否将核心库设为externals?
process Error) Great question! The short answer is yes, you absolutely can use Webpack externals to avoid bundling large libraries like React, ReactDOM, and semantic-ui-react—this is exactly what externals are designed for, and it will keep your bundle size tiny (far under 4MB). The issue you're hitting is specific to how you're loading React from a CDN, not the externals feature itself.
Why Your Current DefinePlugin Fix Isn't Working
The process.env.NODE_ENV check that's failing lives in the CDN-hosted React development build (react.development.js), not in your Webpack bundle. Webpack's DefinePlugin only modifies code that gets bundled into your bundle.js file—it has no way to alter scripts loaded directly from a CDN. That's why adding the plugin didn't fix the error.
Fix 1: Use Production CDN Builds (Recommended)
The simplest fix is to switch to the production builds of React and ReactDOM from your CDN. Production builds don't include the process.env.NODE_ENV checks that are causing the error, and they're smaller too.
Step 1: Update Your HTML Script Tags
Replace your React/ReactDOM CDN links with the production versions:
<!-- Production builds (no process dependency) --> <script src="https://unpkg.com/react@18/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script> <script src="https://unpkg.com/semantic-ui-react@2/dist/umd/semantic-ui-react.min.js"></script>
Step 2: Fix Your Externals Configuration
You have a small mistake in your externals for semantic-ui-react: its global variable name is semanticUIReact (not semantic-ui-react). Update your webpack.config.js externals section:
externals: { 'jquery': 'jQuery', 'lodash': '_', 'react': 'React', 'react-dom': 'ReactDOM', 'semantic-ui-react': 'semanticUIReact' // Corrected global variable name }
Fix 2: Keep Using Development Builds (For Debugging)
If you need to use the React development build for debugging, you can manually define the process variable in the browser before loading React. Add this script before your React CDN links in your HTML:
<!-- Manually define process for React's development build --> <script> window.process = { env: { NODE_ENV: 'development' } }; </script> <!-- Development builds (now have access to process) --> <script src="https://unpkg.com/react@18/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> <script src="https://unpkg.com/semantic-ui-react@2/dist/umd/semantic-ui-react.min.js"></script>
This will make the process.env.NODE_ENV check in React's development build pass without issue.
Verify the Fix
After making these changes, run your dev server again:
yarn run serve
Open localhost:3000—the process is not defined error should be gone, and semantic-ui-react will work correctly while staying out of your bundle.
内容的提问来源于stack exchange,提问作者Jonathan H

