Angular 14微前端MFE加载remoteEntry.js时出现import.meta报错
解决Angular 14 MFE加载remoteEntry.js时的"import.meta outside a module"错误
核心原因
这个错误是因为remoteEntry.js是ES模块格式(使用了import.meta特性),但被以普通脚本的方式加载,或者webpack配置存在语法错误导致生成的文件不符合模块规范。
解决方案
1. 修正webpack配置的语法错误
你的webpack配置存在语法错误,exports.module是错误的导出方式,应该改为module.exports,并且确保正确引入Module Federation插件:
如果使用@angular-architects/module-federation工具(推荐方式),完整配置如下:
const { shareAll, withModuleFederationPlugin } = require('@angular-architects/module-federation/webpack'); module.exports = withModuleFederationPlugin({ name: "mfeProfile", filename: "remoteEntry.js", exposes: { './Module': './projects/project-name/src/app/profile/profile.module.ts' }, shared: { ...shareAll({ singleton: true, strictVersion: true, requiredVersion: 'auto' }), }, });
如果手动配置webpack,需确保正确使用ModuleFederationPlugin:
const { ModuleFederationPlugin } = require('webpack').container; module.exports = { // 其他基础webpack配置(如entry、output等) plugins: [ new ModuleFederationPlugin({ name: "mfeProfile", filename: "remoteEntry.js", exposes: { './Module': './projects/project-name/src/app/profile/profile.module.ts' }, // 配置共享依赖 shared: { '@angular/core': { singleton: true, strictVersion: true }, '@angular/common': { singleton: true, strictVersion: true }, '@angular/router': { singleton: true, strictVersion: true } } }) ] };
2. 确保以ES模块方式加载remoteEntry.js
主应用加载remoteEntry.js时,必须指定脚本类型为module:
静态加载(index.html中)
<script type="module" src="http://localhost:4201/remoteEntry.js"></script>
动态加载(代码中)
const loadRemoteEntry = async () => { const script = document.createElement('script'); script.type = 'module'; script.src = 'http://localhost:4201/remoteEntry.js'; document.head.appendChild(script); await new Promise(resolve => script.onload = resolve); }; loadRemoteEntry();
3. 调整Angular构建配置
在angular.json的remote应用build选项中,确保:
target设置为es2020或更高版本(支持import.meta)outputHashing设为none(避免文件名哈希导致加载路径问题)
示例配置:
"build": { "builder": "@angular-devkit/build-angular:browser", "options": { "outputPath": "dist/mfe-profile", "index": "projects/project-name/src/index.html", "main": "projects/project-name/src/main.ts", "polyfills": "projects/project-name/src/polyfills.ts", "tsConfig": "projects/project-name/tsconfig.app.json", "assets": [ "projects/project-name/src/favicon.ico", "projects/project-name/src/assets" ], "styles": [ "projects/project-name/src/styles.css" ], "scripts": [], "outputHashing": "none", "target": "es2020" } }
4. 清理缓存并重新构建
删除remote和主应用的dist文件夹,执行npm run build重新构建两个应用,避免旧编译文件干扰。
内容的提问来源于stack exchange,提问作者Vino
相关产品推荐
相关产品推荐

