繁体   English   中英

使用Webpack 2使node_module成为全局的

[英]Making a node_module global using Webpack 2

我在角度项目中使用以下包:

https://github.com/pablojim/highcharts-ng

一个要求是它需要highcharts作为全局依赖,它告诉你在你的html中添加一个脚本标记:

<script src="http://code.highcharts.com/highcharts.src.js"></script>

而不是将上面的脚本标记添加到我的HTML中,我想通过Webpack使其全局化。

我已经通过npm安装了highcharts,并尝试使用此处描述的ProvidePlugin和noParse方法(无济于事): https ://webpack.js.org/guides/shimming/#scripts-loader

对于我使用的ProvidePlugin选项:

new webpack.ProvidePlugin({
  Highcharts: "highcharts",
})

对于noParse:

noParse: [
  /[\/\\]node_modules[\/\\]highcharts[\/\\]highcharts\.js$/,
],

两者都没有用,这意味着当highcharts-ng尝试工作时,它会出错,因为它无法创建new Highcharts

TypeError: Cannot read property 'Chart' of undefined

// from highcharts-ng which throws above error
chart = new Highcharts[chartType](mergedOptions, func);

这是我的角度模块

import angular from 'angular'
import highchartsNg from 'highcharts-ng'
import { ReportsData } from './reports.data'
import { reportsWidget } from './reports-widget/component'

export const ReportsModule = angular
  .module('reports', [
    highchartsNg,
  ])
  .factory('ReportsData', ReportsData)
  .component('reportsWidget', reportsWidget)
  .name

我的webpack配置:

var webpack = require('webpack')

module.exports = {
  context: __dirname + '/app/modules',
  entry: {
    vendor: ['angular', 'highcharts-ng'],
    modules: './modules.js',
  },
  output: {
    path: __dirname + '/.tmp/modules',
    filename: '[name].bundle.js',
  },
  plugins: [
    // info: https://webpack.js.org/guides/code-splitting-libraries/
    new webpack.optimize.CommonsChunkPlugin({
      name: ['vendor', 'manifest'],
    }),
  ],
  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          {
            loader: 'babel-loader',
            options: { presets: ['es2015'] },
          },
        ],
      },
    ],
  },
}

使用expose-loader和write require('expose-loader?Highcharts!highcharts'); 在第一次使用Highcharts全局变量之前的某个地方。 这将需要highcharts并将其公开为window.Highcharts在浏览器中。

在引擎盖下,webpack可以为您提供:

/* 0 */
/***/ function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {module.exports = global["Highcharts"] = __webpack_require__(1);
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2)))

/***/ }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM