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

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

本文介绍了Webpack - 如何将非模块脚本加载到全局范围内 |窗户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一些供应商文件,我需要从窗口范围内运行(这是一堆窗口范围内的函数),另外我还有一些我想捆绑到供应商包中的 polyfill.

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

new webpack.optimize.CommonsChunkPlugin({name: '供应商',文件名:'js/vendor.min.js',minChunks:无穷大,})入口: {'供应商' : ['./vendor.js', './vendor2.js', './polyfills.js']}

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

我也考虑过使用 ProvidePlugin 之类的东西,但我根本无法使用它,因为我没有像 jQuery 这样的已定义名称,其中所有内容都映射到其中.

这甚至可以在 webpack 中实现吗?

解决方案

使用脚本加载器插件:

如果你想让整个脚本在全局命名空间中注册,你必须使用

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']
}

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.

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.

Is this even possible in webpack?

解决方案

Use the script-loader plugin:

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

Webpack docs

Then in your entry.js file you could import it inline:

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

or via config:

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

and in your entry.js

import './eluminate.js';

As I said, it pollutes the global namespace:

这篇关于Webpack - 如何将非模块脚本加载到全局范围内 |窗户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 04:59