We have a standard Angular 8 app, but for some specific business-related reasons we need to have some on-the-side javascript functions exposed. In order to use one build and to be able to reuse code from the angular application, we use a custom webpack config like this:
"customWebpackConfig": {
"path": "./webpack.exposed.js",
"replaceDuplicatePlugins": true,
"mergeStrategies": {
"module.rules": "append"
}
}
The contents of the webpack.exposed.js
:
module.exports = {
entry: {
'for-others': './src/for-others/for-others.ts',
},
output: {
filename: '[name].js',
}
};
The for-others
file contains just one exported function: export default () => {'config1': 1, 'config2': 2};
This works quite well and produces a separate for-others.js
file. The problem is that this file doesn't just expose the function somehow, but adds something to a global webpackJsonp
array. This means that other "external systems" can't use our config, as when this push
is evaluated, we as a result we get a number (what the return type of push
actually is).
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["for-others"],{
},[["./src/for-others/for-others.ts","runtime","vendor"]]]);
We've handled this requirement in another project where separate webpack builds are used. There the generated file is just:
/******/ (function(modules) { // webpackBootstrap
/******/ ...
/******/ })({<code>})
There we use a wrapper plugin that just adds (() => {\nreturn
before this code and\n})().default
after it, so the whole file evaluates to the default-ly exported function.
I've seen these questions already, but none actually provides a solution (or at least i can't get a solution out).
I think you can make use of optimization.runtimeChunk webpack option.
By default Angular CLI sets it to 'single' which is basically alias for:
optimization: {
runtimeChunk: {
name: 'runtime'
}
}
So I would try something like:
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'
},
}
};
This should remove webpackJsonp
part. Then as you have already mentioned, you can use a wrapper plugin:
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;'
})
]
};
so that you can export whatever and wherever you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With