如何通过Webpack或Babel插件使TypeScript中import * as schema直接加载JSON对象
import * as schema直接获取JSON对象 Absolutely, you can fix this behavior using either Webpack configuration tweaks or a Babel plugin—let’s break down both options based on your current setup:
为什么当前会出现.default的情况
First, let’s clarify why you’re seeing this:
- Your Babel config has
@babel/preset-envset tomodules: 'commonjs', which converts ES module syntax (import/export) to CommonJS (require/module.exports). - Webpack 5+ (or earlier versions with
json-loader) defaults to exporting JSON files as ES modules, meaning the JSON content is exposed as thedefaultexport. - When Babel transforms
import * as schema from '../schema.json', it ends up asconst schema = require('../schema.json')—and since Webpack wrapped the JSON in an ES module,schemabecomes an object with a.defaultproperty pointing to your actual JSON data.
方法1:调整Webpack配置
You can tell Webpack to export JSON files directly as CommonJS modules (instead of ES modules), so require returns the raw JSON object directly. Add this to your Webpack config:
module.exports = { module: { rules: [ { test: /\.json$/, type: 'json', generator: { // Force JSON to export as CommonJS (matches Babel's module conversion) exports: 'commonjs' } } ] } };
With this, import * as schema from '../schema.json' will give you the raw JSON object directly—no need for .default.
方法2:使用Babel插件
If you prefer to handle this entirely in Babel, use the babel-plugin-transform-json-imports plugin to rewrite JSON import statements to bypass the .default wrapper.
步骤:
Install the plugin:
npm install babel-plugin-transform-json-imports --save-dev # or yarn add babel-plugin-transform-json-imports --devAdd it to your Babel config’s
pluginsarray (place it early in the list to ensure it runs before other transforms):{ "presets": [ "@babel/preset-typescript", "@babel/preset-react", ["@babel/preset-env", { "modules": "commonjs" }] ], "plugins": [ ["babel-plugin-transform-json-imports", { "include": "\\.json$", "allowNameSpaceImports": true }], "babel-plugin-dynamic-import-node", "@babel/plugin-transform-destructuring", ["@babel/plugin-transform-for-of", { "loose": true }], "@babel/plugin-transform-regenerator", "@babel/plugin-transform-runtime", ["@babel/plugin-proposal-decorators", { "legacy": true }], ["@babel/plugin-proposal-class-properties", { "loose": true }], "@babel/plugin-proposal-object-rest-spread", ["styled-components", { "ssr": true }] ] }
This plugin will automatically rewrite import * as schema from '../schema.json' to directly reference the JSON content, eliminating the need for .default.
验证
After setting up either option, you can test it with:
import * as schema from "../schema.json"; console.log(schema); // Should log your raw JSON object, not { default: ... }
内容的提问来源于stack exchange,提问作者hanego

