我们有一个标准的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
,因此整个文件的计算结果均为默认导出的函数。
答案 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;'
})
]
};
以便您可以随心所欲地导出任何内容。