gpt4 book ai didi

Webpack - 如何将非模块脚本加载到全局范围内 window

转载 作者:行者123 更新时间:2023-12-02 06:30:11 25 4
gpt4 key购买 nike

所以我有一些需要从窗口范围运行的 vendor 文件(这是一堆窗口范围的函数),另外我还有一些我想捆绑到 vendor 包中的填充文件。

所以我尝试了这样的事情:

new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: 'js/vendor.min.js',
minChunks: Infinity,
})

entry: {
'vendor' : ['./vendor.js', './vendor2.js', './polyfills.js']
}

现在,当我运行 webpack 构建时,它确实会生成我的 vendor 包,但它全部包装在 webpackJsonP 包装器中,因此在窗口范围内无法访问这些函数。

我也考虑过使用像 ProvidePlugin 这样的东西,但我根本无法让它工作,因为我没有像 jQuery 这样的定义名称,所有东西都映射在下面。

这在 webpack 中可能吗?

最佳答案

使用脚本加载器插件:

如果您希望整个脚本在全局命名空间中注册,则必须使用 script-loader 。不推荐这样做,因为它破坏了模块的意义;-)但如果没有其他办法的话:

npm install --save-dev script-loader

Webpack docs

This loader evaluates code in the global context, just like you would add the code into a script tag. In this mode every normal library should work. require, module, etc. are undefined.

Note: The file is added as string to the bundle. It is not minimized by webpack, so use a minimized version. There is also no dev tool support for libraries added by this loader.

然后在您的entry.js 文件中,您可以内联导入它:

import  "script-loader!./eluminate.js"

或通过配置:

module.exports = {
module: {
rules: [
{
test: /eluminate\.js$/,
use: [ 'script-loader' ]
}
]
}
}

在你的entry.js中

import './eluminate.js';

正如我所说,它污染了全局命名空间:

enter image description here

关于Webpack - 如何将非模块脚本加载到全局范围内 window ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48998102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com