The question: Why won't import
parse my JSON string provided as a webpack externals
member?
I have a group of React apps that need to share a JSON configuration file, which I want webpack (v4) to inline into each app during the build. Based on answers like this and similar examples like the "Using Webpack" section in this article, it looks like this should work, but the JSON string imports as a string value, it is not parsed into an object.
JSON:
{ "api": "https://localhost:5050/api" }
Webpack (modifying a config produced by another package):
config.externals.push({
'AppConfig': JSON.stringify(require(path.resolve(configPath, "app-config.json")))
});
Module:
import Config from 'AppConfig';
I'm using a component to read the OpenAPI schema:
<ApiService schema={Config.api}> ...
The error shows the JSON is not parsed, it is imported as a string literal:
GET https://localhost:9000/%7B%22api%22:%22https://localhost:5050/api%22%7D net::ERR_ABORTED 404
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The webpack config works, obviously. And I know the configuration itself is good, if I change the import
to reference the JSON file directly, it works as expected. But that requires using lots of ../../../
relative path garbage I'm trying to avoid. I am also not interested in the export default
approach in a .js file that I've seen people use for similar questions.
Am I missing a webpack or Babel plug-in somewhere, perhaps?