开发的Angular 6嵌入脚本无法在React 16.4应用运行,如何解决?
The root cause here is that both your Angular app (bundled with webpack) and the React 16.4 app are using the default global webpackJsonp variable for chunk loading. When you embed the Angular script into the React app, they overwrite each other's webpackJsonp reference, leading to the error you're seeing.
Since you can only modify the Angular code, here's how to resolve this by customizing the webpack jsonp function name for your Angular build:
Step 1: Use Custom Webpack Builder (for Angular CLI Projects)
If you're using Angular CLI (the most common setup), you can't directly edit the default webpack config, so we'll use @angular-builders/custom-webpack to extend it:
- Install the dependency:
npm install @angular-builders/custom-webpack --save-dev
- Create a custom webpack config file (e.g.,
extra-webpack.config.js) in your project root:
module.exports = { output: { // Choose a unique name that won't clash with the React app's webpackJsonp jsonpFunction: 'angularWebpackJsonp' } };
- Update your
angular.jsonto use the custom builder:- Find the
architect > buildsection, replace the default builder with@angular-builders/custom-webpack:browser, and add the custom config reference:
"build": { "builder": "@angular-builders/custom-webpack:browser", "options": { "customWebpackConfig": { "path": "./extra-webpack.config.js" }, // Keep all your existing build options (outputPath, index, main, etc.) } }- Do the same for the
architect > servesection to use@angular-builders/custom-webpack:dev-serverfor local development:
"serve": { "builder": "@angular-builders/custom-webpack:dev-server", "options": { "customWebpackConfig": { "path": "./extra-webpack.config.js" }, // Keep your existing serve options } } - Find the
Step 2: Direct Webpack Config Edit (for Non-CLI Angular Projects)
If you're managing your webpack config directly (not using Angular CLI), simply modify your webpack.config.js to set a custom jsonpFunction in the output section:
module.exports = { // ... other configs output: { filename: '[name].bundle.js', chunkFilename: '[id].chunk.js', jsonpFunction: 'angularWebpackJsonp' // Unique name here } };
Why This Works
Webpack uses the jsonpFunction global variable to handle asynchronous chunk loading. By assigning a unique name to your Angular app's jsonpFunction, you avoid conflicting with the React app's own webpackJsonp variable. After rebuilding your Angular app, the bundled scripts will use your custom global variable instead of the default webpackJsonp, eliminating the clash.
Verify the Fix
After rebuilding your Angular app, check the bundled files (look for the polyfills or bootstrap sections) — you should see your custom angularWebpackJsonp variable being used instead of the default webpackJsonp. Now embedding this script into your React 16.4 app should no longer throw the error.
内容的提问来源于stack exchange,提问作者YASH DAVE

