没有webpackJsonp的独立自定义Webpack配置

时间:2019-11-20 13:10:36

标签: angular webpack

我们有一个标准的Angular 8应用程序,但是出于某些与业务相关的特定原因,我们需要公开一些javascript功能。为了使用一种构建并能够重复使用角度应用程序中的代码,我们使用了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的返回类型实际上是)。 / p>

(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,但实际上没有人提供解决方案(或者至少我无法提供解决方案)。

1 个答案:

答案 0 :(得分:1)

我认为您可以使用optimization.runtimeChunk webpack选项。

默认情况下,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;'
    })
  ]
};

以便您可以随心所欲地导出任何内容。