【问题标题】:Importing JSON in TypeScript does not import the contents but a URL在 TypeScript 中导入 JSON 不会导入内容而是导入 URL
【发布时间】:2022-01-16 12:30:47
【问题描述】:

我正在尝试在 TypeScript 中导入 JSON 文件的内容,但我得到的不是 JSON 的内容,而是它的 URL。

App.tsx

import * as videosInfo from './videos-info.json'

console.log("Print");
console.log(videosInfo);

控制台输出:

Print
http://localhost:3000/src/videos-info.json

在tsconfig.json 中,我使用"resolveJsonModule": true。 如何使用 JSON 的 contents 而不是它的路径?

编辑:这是我的webpack.config.js 供参考:

const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.tsx',
  module: {
    rules: [
      {
        test: /\.json/,
        type: 'asset/resource',
        generator: {
          filename: '[name][ext][query]'
        }
      },
      { 
        test: /\.css$/, 
        use: ['style-loader', 'css-loader']
      },
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    extensions: [ '.tsx', '.ts', '.js' ],
  },
  output: {
    filename: 'client.bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  plugins: [
    new HtmlWebPackPlugin({
      template: './public/index.html',
      filename: 'index.html'
    })
  ],
  devServer: {
    static: {
      directory: path.join(__dirname, 'dist')
    },
    compress: true,
    port: 3000
  }
};

【问题讨论】:

  • 您是否在使用某种捆绑程序或可能会产生干扰的东西?看起来它应该可以正常工作......
  • @T.J.Crowder 我添加了我的webpack.config.js 以供参考。我不知道是什么干扰...

标签: typescript webpack


【解决方案1】:

正如@T.J. Crowder 正确建议的那样,问题来自我对Webpack 5 中的asset/resource 加载程序的误解。根据documentation:

asset/resource 发出一个单独的文件并导出 URL。以前可以通过使用文件加载器来实现。

我的目标是在我执行npm run build 时将videos-info.json 从/src/ 复制到/dist 文件夹中,这样我就可以在某处静态托管它并设置一个AWS Lambda 以定期覆盖它。因此,我无法通过 Webpack 将 JSON 加载到 client.bundle.js 中,因为数据将被硬编码在包中。这篇关于 Webpack 如何静态构建资源的说明帮助我更好地理解了它:https://stackoverflow.com/a/44424933/9698467

因此我必须在 Webpack 5 中使用 asset/resource 加载器来生成一个 URL,然后我可以通过 React hook 将其加载到网页中,例如:

const videosFile = require('./videos-info.json');
// videosFile is a URL

React.useEffect(() => {
  const resp = await fetch(videosFile);
  const data = await resp.json() as VideoResult;
  const videos: VideoResultItem[] = data.items;
}, []);

【讨论】:

  • 别忘了查看resp.ok,更多信息请访问my blog。
猜你喜欢
  • 2019-06-26
  • 2018-07-17
  • 2020-06-25
  • 2022-12-14
  • 2018-10-04
  • 2013-04-05
  • 1970-01-01
  • 2016-10-17
相关资源
最近更新 更多