angular - 没有 webpackJsonp 的独立自定义 webpack 配置

标签 angular webpack

我们有一个标准的 Angular 8 应用程序,但由于某些特定的业务相关原因,我们需要公开一些旁侧 javascript 函数。为了使用一个构建并能够重用来自 angular 应用程序的代码,我们使用了 custom webpack config像这样:

"customWebpackConfig": {
  "path": "./webpack.exposed.js",
  "replaceDuplicatePlugins": true,
  "mergeStrategies": {
    "module.rules": "append"
  }
}
webpack.exposed.js的内容:
module.exports = {
  entry: {
    'for-others': './src/for-others/for-others.ts',
  },
  output: {
    filename: '[name].js',
  }
};
for-others文件只包含一个导出函数:export default () => {'config1': 1, 'config2': 2};
这很有效并产生一个单独的 for-others.js文件。问题是这个文件不仅以某种方式公开了函数,而且还向全局 webpackJsonp 添加了一些东西。大批。这意味着其他“外部系统”不能使用我们的配置,就像这个 push被评估后,我们得到一个数字(push 的返回类型实际上是什么)。
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["for-others"],{
},[["./src/for-others/for-others.ts","runtime","vendor"]]]);

我们已经在另一个使用单独 webpack 构建的项目中处理了这个需求。生成的文件只是:
/******/ (function(modules) { // webpackBootstrap
/******/ ...
/******/ })({<code>})

我们使用了一个包装插件,它只是添加了 (() => {\nreturn在此代码和 \n})().default 之前在它之后,所以整个文件评估为默认导出的函数。

我见过these questions already ,但实际上没有提供解决方案(或者至少我无法找到解决方案)。

最佳答案

我想你可以利用 optimization.runtimeChunk网络包选项。

默认情况下,Angular CLI 将其设置为 'single'这基本上是别名:

optimization: {
  runtimeChunk: {
    name: 'runtime'
  }
}

所以我会尝试类似的事情:
module.exports = {
  entry: {
    'for-others': './src/for-others/for-others.ts',
  },
  output: {
    filename: '[name].js',
  },
  optimization: {
    runtimeChunk: {
      name: entryPoint => entryPoint.name === 'for-others' ? 'for-others' : 'runtime'
    },
  }
};

这应该删除 webpackJsonp部分。然后正如您已经提到的,您可以使用包装插件:
const WrapperPlugin = require('wrapper-webpack-plugin');

module.exports = {
  entry: {
    'for-others': './src/for-others/for-others.ts',
  },
  output: {
    filename: '[name].js',
  },
  optimization: {
    runtimeChunk: {
      name: entryPoint => entryPoint.name === 'for-others' ? 'for-others' : 'runtime'
    },
  },
  plugins: [
    new WrapperPlugin({
      test: /for-others\.js$/,
      header: '(() => {\nreturn ',
      footer: '\n})().default;'
    })
  ]
};

这样您就可以随心所欲地导出任何内容。

关于angular - 没有 webpackJsonp 的独立自定义 webpack 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58955158/

相关文章:

angular - 何时向 Angular 2 模块级别和 App 组件级别注入(inject)服务

webpack - dotnet 发布在预发布完成之前运行

Angular 6 子路由不起作用

angular - Angular html中的箭头函数

angular - angular 2 backgrounImage 中的样式绑定(bind)抛出错误

angular - Uncaught ReferenceError : require is not defined at

node.js - Express 抛出 404 url​​ 中是否有点 - Vue、webpack

javascript - 内联 Webpack JS 文件不起作用

javascript - Kendo UI 和 Vue.js

Angular2/网络包 : how to load fonts that are imported inside css files?