Reputation: 71
Upfront, I want to admit this is my first dive into webpack in any depth, and I could be missing something obvious.
I am developing a node JS
script that runs as a sort of agent to provide features and data to an HTML5/JS client app in my target environment. Part of the API is supplied in the node_modules on the target environment at runtime, rather than at build time. In my code, I provide it with const phoenix = require('@phoenix/apis/dist/index');
Running webpack, everything is bundled fine, but when I try to run the script I run into:
Invalid or unexpected token at Object.@phoenix/apis/dist/index (/home/path/node_modules/AgendaWeb_0.0.1/main.js:2312:1)
This makes sense because webpack is turning that require into this:
eval("module.exports = @phoenix/apis/dist/index;\n\n//# sourceURL=webpack:///external_%22@phoenix/apis/dist/index%22?");
And @phoenix
would not be a valid module/object name to work with.
I basically need webpack to just leave the require alone (I don't know if that even makes sense in the context of bundling) so the node instance can bring in the module in the environment its running in.
Here is my webpack config:
module.exports = {
entry: {
main: './src/agendaAgent'
},
output: {
path: path.resolve(__dirname, './prod/')
},
externals: /@phoenix/,
target: 'node',
plugins: [
new CleanWebpackPlugin(),
new CopyPlugin([{from:'./manifest.json', to:'./'}]),
new webpack.DefinePlugin({ 'global.GENTLY': false })
]
};
I would expect there's a way to include an external module which would be referenced at Runtime (in the node_modules/@phoenix
directory - that's the way it currently works, outside of webpacked code)
So far I've tried using externals (as above), and tried to use resolve.alias to give it a direct path to the libraries (this is not a good solution as the module is not part of the development environment - I haven't gotten this working either). I also tried to use the IgnorePlugin, but if I'm understanding it correctly, it only prevents generating the matched module.
Any help or guidance is appreciated.
Upvotes: 4
Views: 1304
Reputation: 71
After struggling with this for quite some time, I stumbled into the answer. It's not spelled out clearly, but the following configuration change allowed webpack to bundle everything properly:
output: {
path: path.resolve(__dirname, './prod/'),
libraryTarget: 'umd'
}
The relevant change is the libraryTarget: 'umd'
, which makes webpack bundle your module in commonJS, AMD, and Global. The critical point here is that webpack is not trying to expose the module as a property of an object. There are likely other libraryTarget
values which would result in a successful output, but for the time being this is working for me.
Upvotes: 2