我正在嘗試在 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 的內容而不是其路徑?
編輯:這是我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
}
};
uj5u.com熱心網友回復:
正如@T.J. Crowder正確地建議的那樣,問題來自我asset/resource對Webpack 5. 根據檔案:
資產/資源發出一個單獨的檔案并匯出 URL。以前可以通過使用檔案加載器來實作。
我的目標是在我這樣做時從檔案夾中復制,videos-info.json以便我可以將其靜態托管在某處并設定 AWS Lambda 以定期覆寫它。因此,我無法通過 Webpack加載 JSON,因為資料將被硬編碼在包中。這篇關于 Webpack 如何靜態構建資源的說明幫助我更好地理解了它:https ://stackoverflow.com/a/44424933/9698467/src//distnpm run buildclient.bundle.js
因此,我必須使用asset/resourceWebpack 5 中的加載器來生成一個 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;
}, []);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/416547.html
標籤:
