Webpack-如何将非模块脚本加载到全局范围窗户 [英] Webpack - How to load non module scripts into global scope | window
问题描述
因此,我需要从窗口范围(这是一系列窗口范围的函数)运行一些供应商文件,此外,我还希望将一些polyfill捆绑到供应商捆绑包中.
so i have a few vendor files that i need to run from window scoped (it's a bunch of window scoped functions) plus i have some polyfills that i would like to bundle into the vendor bundle as well.
所以我尝试了这样的事情:
So i tried something like this:
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: 'js/vendor.min.js',
minChunks: Infinity,
})
entry: {
'vendor' : ['./vendor.js', './vendor2.js', './polyfills.js']
}
现在,当我运行Webpack构建时,它会生成我的供应商捆绑包,但它们都包装在webpackJsonP包装器中,因此在窗口范围内无法访问这些功能.
Now when i run my webpack build it does generate my vendor bundle but it's all wrapped in a webpackJsonP wrapper so the functions are not accessible on the window scope.
我还考虑过使用诸如ProvidePlugin之类的方法,但是由于我没有像jQuery这样定义的名称(在该名称下所有内容都被映射),所以我根本无法使用它.
I've also looked at using something like the ProvidePlugin but i couldn't make that work at all since i don't have a defined name like jQuery where everything is mapped under.
在webpack中甚至有可能吗?
Is this even possible in webpack?
推荐答案
使用脚本加载器插件:
如果您希望整个脚本在全局名称空间中注册,则必须使用 script-loader .不建议这样做,因为它会破坏模块的含义;-) 但是,如果没有其他方法:
If you want the whole script to register in the global namespace you have to use script-loader. This is not recommend, as it breaks the sense of modules ;-) But if there is no other way:
npm install --save-dev script-loader
此加载器在全局上下文中评估代码,就像您将要评估的那样 将代码添加到脚本标签中.在这种模式下,每个普通库 应该管用.需求,模块等未定义.
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.
注意:该文件将作为字符串添加到捆绑软件中.没有最小化 通过webpack,因此请使用最小化版本.也没有开发工具 支持此加载程序添加的库.
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文件中导入内联:
Then in your entry.js file you could import it inline:
import "script-loader!./eluminate.js"
或通过配置:
module.exports = {
module: {
rules: [
{
test: /eluminate\.js$/,
use: [ 'script-loader' ]
}
]
}
}
以及您的entry.js
import './eluminate.js';
正如我所说,它污染了全局名称空间:
As I said, it pollutes the global namespace:
这篇关于Webpack-如何将非模块脚本加载到全局范围窗户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!