gpt4 book ai didi

javascript - 使用 Webpack 2 将 node_module 设为全局

转载 作者:行者123 更新时间:2023-11-28 05:12:14 25 4
gpt4 key购买 nike

我在一个 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:

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);

这是我的 Angular 模块

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并在第一次使用 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)))

/***/ }

关于javascript - 使用 Webpack 2 将 node_module 设为全局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41266591/

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