【问题标题】:Making a node_module global using Webpack 2使用 Webpack 2 使 node_module 全局化
【发布时间】:2017-05-07 02:27:02
【问题描述】:

我在 Angular 项目中使用以下包:

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: [
  /[\/\\]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'] },
          },
        ],
      },
    ],
  },
}

【问题讨论】:

  • 我已将 highcharts 添加到我的供应商捆绑包中:供应商:['angular','highcharts','highcharts-ng'],还添加了:加载器:[{测试:/[\/\] node_modules[\/\]highcharts[\/\]highcharts\.js$/, loader: 'exports-loader?Highcharts', }, ], 这不是修改文件,我仍然有问题。以上正确吗?
  • 对不起,我的第一个链接指向了错误的插件 :(。我的意思是 expose-loader。这允许您定义全局(在窗口上)可用的包。不幸的是,我不在使用这个加载器迁移到 webpack 2 的路径上。

标签: javascript angularjs highcharts webpack webpack-2


【解决方案1】:

使用expose-loader 并在第一次使用Highcharts 全局变量之前的某处写require('expose-loader?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)))

/***/ }

【讨论】:

    猜你喜欢
    • 2018-08-26
    • 2018-06-05
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 2017-09-26
    相关资源
    最近更新 更多