The Issue
Consider the following JS
file:
./src/test.js
import { Something } from 'some-package';
import SomeImage from 'static/assets/images/some-image.png';
export const test = [
{
foo: 'bar',
messages: [ 'Hello World' ],
handler: Something,
image: SomeImage
}
];
During the Webpack compilation, I would like to read the above file, and output something along the lines of the following:
./dist/test.json
[
{
"foo": "bar",
"messages": [ "Hello World" ],
"handler": {},
"image": "https://example.com/assets/images/some-image.some-hash.png"
}
]
What I have tried
I have researched and tried many different things;
- Writing a custom webpack plugin - this was the closest I got. However, it failed when importing the
.src/test.js
file into the plugin becauseSomeImage
was obviously still an image and not a URL. Maybe this is along the right path?
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".png" for static/assets/images/some-image.png
Utilizing
transform
in thewebpack-copy-plugin
- this does not work because I still have to import the/src/test.js
into the webpack build configuration in order to pass the properties totransform
- therefore it fails with the same error as aboveReading from the bundled output of a second entry file - this was a long shot but my idea was the following:
- Add a new file,
test-export.js
like so:
import { test } from './test.js';
export default test;
- Add a second file entry to the initial Webpack compilation:
export default {
entry: { app: [ './src/app.js' ], test: [ './src/test.js' ] },
...config
}
Write another webpack plugin that runs after the build is complete and imports the compiled/bundled file
./dist/js/test.bundle.js
The plugin will read the above file and emit a new JSON file to
./dist/test.json
I tested this method by adding the new entry (step 1) and then trying to call:
import { test } from './dist/js/test.bundle.js'
and also:
const { test } = require('./dist/js/test.bundle.js')
Both of these methods returned undefined
, and when I just tried to import the default
, I got a Webpack wrapper (expected), and I decided this path was too dirty to continue.
Conclusion
On the face of it, this seems like a really simple task but as far as my knowledge extends with Webpack, I cannot see a simple way to do this or if it is even possible.
Can anyone point me in the right direction as to how I can achieve the above? I don't require the code to be written for me, I simply need guidance as to whether it is possible, and if so, what steps I should take.