通过Webpack外部从JSON字符串文字导入ES6 [英] ES6 import from a JSON string literal via webpack externals
问题描述
问题:为什么 import
不能解析作为webpack externals
成员提供的JSON字符串?
The question: Why won't import
parse my JSON string provided as a webpack externals
member?
我有一组React应用程序,它们需要共享一个JSON配置文件,我希望Webpack(v4)在构建期间内联到每个应用程序中.基于诸如此之类的答案以及类似使用Webpack"文章,这看起来应该可以工作,但是JSON字符串会作为字符串值导入,不会解析为对象.
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(修改另一个软件包产生的配置):
Webpack (modifying a config produced by another package):
config.externals.push({
'AppConfig': JSON.stringify(require(path.resolve(configPath, "app-config.json")))
});
模块:
import Config from 'AppConfig';
我正在使用组件来读取OpenAPI架构:
I'm using a component to read the OpenAPI schema:
<ApiService schema={Config.api}> ...
错误显示未解析JSON,它作为字符串文字导入:
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
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
显然,webpack配置有效.而且我知道配置本身很好,如果我更改 import
以直接引用JSON文件,则它可以按预期工作.但这需要使用大量我试图避免的 ../../../
相对路径垃圾.我也对人们看到的用于类似问题的.js文件中的 export default
方法不感兴趣.
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.
也许我在某个地方缺少Webpack或Babel插件吗?
Am I missing a webpack or Babel plug-in somewhere, perhaps?
推荐答案
The solution is to use an alias
with a relative path. The extra path
steps are because this is in a utility module.exports
that modifies an existing webpack configuration object. The npm_config_top_dir
environment variable is specific to our monorepo setup (Lerna runs these scripts and the shared config file is in that root directory).
const pathToCallerSourceCode = path.resolve(process.cwd(), "./src");
const appConfigFullPathname = path.resolve(process.env.npm_config_top_dir, "app-config.json");
const appConfigRelativePathname = path.relative(pathToCallerSourceCode, appConfigFullPathname);
Object.assign(config.resolve, { alias: { AppConfig: appConfigRelativePathname }});
这篇关于通过Webpack外部从JSON字符串文字导入ES6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!