如何在SPFX(TypeScript+Webpack)中引入ES5打包的Angular 1.x旧应用
在SPFX中集成已打包的Angular 1.x ES5应用(最小改造方案)
1. 放置静态资源
- 在项目
src目录下新建lib文件夹,将你的app.js以及依赖的非npm组件(如fullcalendar、jquery-minicolors的JS/CSS文件)复制进去。 - 若依赖组件有稳定CDN地址,可直接用CDN加载,无需本地存放。
2. 排除TypeScript编译
修改项目根目录的tsconfig.json,在exclude数组中添加app.js的路径,避免TypeScript尝试编译它:
{ "exclude": [ "node_modules", "src/lib/app.js" ] }
3. 让Webpack忽略未安装的依赖
app.js中打包的依赖(如fullcalendar、jquery-minicolors)未通过npm安装,Webpack会报错找不到模块。需将这些依赖标记为外部全局变量,让Webpack跳过解析:
在项目根目录新建webpack.config.js,添加如下配置:
module.exports = { externals: { jquery: 'jQuery', fullcalendar: 'FullCalendar', 'jquery-minicolors': '$.minicolors' // 注意:根据组件实际暴露的全局变量名调整,比如部分组件挂载在window对象下 } };
4. 配置资源复制(可选,针对本地资源)
若使用本地存放的依赖文件,修改config/copy-assets.json,确保打包时将src/lib中的文件复制到输出目录:
{ "includeExtensions": [".js", ".css"], "includeFiles": [ "src/lib/**/*" ] }
5. 在WebPart中加载脚本并手动挂载Angular应用
在你的WebPart类中,按顺序加载依赖脚本和app.js,然后在render方法中手动启动Angular(替代ng-app自动挂载):
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base'; import { SPComponentLoader } from '@microsoft/sp-loader'; export default class OldAngularAppWebPart extends BaseClientSideWebPart<any> { protected async onInit(): Promise<void> { // 1. 加载jQuery(按实际依赖顺序调整) await SPComponentLoader.loadScript('https://code.jquery.com/jquery-3.6.0.min.js', { globalExportsName: 'jQuery' }); // 2. 加载fullcalendar的JS和CSS await SPComponentLoader.loadScript(`${this.context.pageContext.web.serverRelativeUrl}/wp-content/webparts/your-webpart-name/lib/fullcalendar.min.js`); await SPComponentLoader.loadCss(`${this.context.pageContext.web.serverRelativeUrl}/wp-content/webparts/your-webpart-name/lib/fullcalendar.min.css`); // 3. 加载jquery-minicolors的JS和CSS await SPComponentLoader.loadScript(`${this.context.pageContext.web.serverRelativeUrl}/wp-content/webparts/your-webpart-name/lib/jquery.minicolors.min.js`); await SPComponentLoader.loadCss(`${this.context.pageContext.web.serverRelativeUrl}/wp-content/webparts/your-webpart-name/lib/jquery.minicolors.css`); // 4. 加载你的app.js await SPComponentLoader.loadScript(`${this.context.pageContext.web.serverRelativeUrl}/wp-content/webparts/your-webpart-name/lib/app.js`); } public render(): void { // 创建Angular挂载容器 this.domElement.innerHTML = `<div id="angular-app-root"></div>`; // 手动启动Angular应用 const container = document.getElementById('angular-app-root'); if (container && window.angular) { // 替换为你实际的Angular模块名 window.angular.bootstrap(container, ['oldAngularAppModule']); } } }
关键注意事项
- 脚本加载顺序必须严格:先加载基础依赖(如jQuery),再加载组件库,最后加载
app.js。 - 确认
app.js中Angular模块的实际名称,替换代码中的oldAngularAppModule。 - 若使用CDN加载依赖,直接替换对应的
loadScript/loadCss参数为CDN地址即可。
内容的提问来源于stack exchange,提问作者Adam
相关产品推荐
相关产品推荐

