如何配置WebPack 5避免IIFE包裹JS,在.NET Core MVC视图直接调用函数
问题:WebPack 5打包后直接调用全局函数的配置方法
我在.NET Core MVC 7应用的构建流程中引入了WebPack 5,目标是能在视图中直接调用WebPack生成的JS文件内的函数。现有相关代码如下:
Index.cshtml
<div> @await Html.PartialAsync("SettingsTab") </div> @section Scripts { <script defer src="~/dist/settings.entry.js"></script> }
SettingsTab.cshtml
<div> <button type="button" onclick="saveProfileSettings()">Save Profile</button> </div>
打包前的settings.js
import ('../css/settings.css') function saveProfileSettings() { // do stuff }
未使用WebPack时可直接调用该函数,但打包后代码被WebPack包裹在IIFE中,无法直接调用。我已尝试配置library: ['WebPack', '[name]'],此时需通过WebPack.settings.saveProfileSettings()调用,但希望无需命名空间,直接以saveProfileSettings()方式调用,请问如何修改WebPack配置?
解决方案
方法1:手动将函数挂载到全局window对象(最直观)
无需修改WebPack配置,直接在settings.js末尾将需要全局调用的函数挂载到window:
import ('../css/settings.css') function saveProfileSettings() { // do stuff } // 暴露到全局作用域 window.saveProfileSettings = saveProfileSettings;
打包后,saveProfileSettings就会成为window对象的属性,视图中可以直接通过saveProfileSettings()调用。
方法2:修改WebPack配置暴露全局变量
如果希望通过WebPack配置实现,可调整webpack.config.js的output配置,将打包后的模块导出直接挂载到window:
output: { filename: "[name].entry.js", path: path.resolve('wwwroot', 'dist'), publicPath: "/dist/", // 将模块导出挂载到window,直接暴露全局函数 library: { name: 'window', type: 'assign' }, libraryExport: 'saveProfileSettings' // 指定要暴露的函数名 }
同时需要修改settings.js,将函数导出:
import ('../css/settings.css') export function saveProfileSettings() { // do stuff }
这种方式下,WebPack会自动把saveProfileSettings挂载到window对象,实现直接调用。
如果需要暴露多个函数,可导出一个包含所有函数的对象,再调整libraryExport为default:
// settings.js import ('../css/settings.css') export default { saveProfileSettings: function() { /* do stuff */ }, anotherFunction: function() { /* do other stuff */ } }
// webpack.config.js output: { filename: "[name].entry.js", path: path.resolve('wwwroot', 'dist'), publicPath: "/dist/", library: { name: 'window', type: 'assign' }, libraryExport: 'default' }
此时可通过saveProfileSettings()和anotherFunction()直接调用。
内容的提问来源于stack exchange,提问作者AlwaysNeedingHelp
相关产品推荐
相关产品推荐

