我正在試驗 Webpack 和 React,嘗試新的加載器以了解它們是如何作業的。這是我的webpack.config.js:
const webpack = require('webpack')
const path = require('path')
module.exports = {
entry: "./src/index.js",
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "babel-loader",
options: { presets: ["@babel/env"] }
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.txt$/,
use: 'raw-loader',
},
{
test: /\.json$/,
use: 'json-loader',
}
],
},
resolve: {
extensions: ["*", ".js", ".jsx"],
},
output: {
path: path.resolve(__dirname, "dist/"),
publicPath: "/dist/",
filename: "bundle.js",
},
plugins: [new webpack.HotModuleReplacementPlugin()],
devServer: {
contentBase: path.join(__dirname, "public/"),
port: 3000,
hotOnly: true,
publicPath: "http://localhost:3000/dist/",
}
}
如您所見,json-loader包含在“規則”部分中。
我已"json-loader": "^0.5.7"安裝在 package.json 的“依賴項”部分下,并運行yarn install以確保它包含在我的 node_modules 目錄中。
我的 /src 目錄中有一個簡單的“foo.json”檔案,如下所示:
{
"foo": "bar",
"bazz": {
"buzz": [1, 2, 3, 4, 5]
}
}
我正在將此 JSON 匯入到 React 組件中:
import React from "react";
import "./App.css";
import text from './foo.txt';
import myJson from './foo.json'
const App = () => {
const buzz = myJson.bazz.buzz;
return (
<div className="App">
<h1> Hello, World! </h1>
{
text.split("\n").map((item) => <p>{item}</p> )
}
<ul>
{ buzz.map((item) => <li>{item}</li> )}
</ul>
</div>
);
}
export default App;
但是,當我運行時yarn run build,出現以下錯誤:
ERROR in ./src/foo.json
Module parse failed: Unexpected token m in JSON at position 0 while parsing near 'module.exports = {"f...'
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token m in JSON at position 0 while parsing near 'module.exports = {"f...'
at JSON.parse (<anonymous>)
at parseJson (/Users/richiethomas/Desktop/Workspace/InvestmentTime/new-react-app/node_modules/json-parse-better-errors/index.js:7:17)
at JsonParser.parse (/Users/richiethomas/Desktop/Workspace/InvestmentTime/new-react-app/node_modules/webpack/lib/JsonParser.js:16:16)
at /Users/richiethomas/Desktop/Workspace/InvestmentTime/new-react-app/node_modules/webpack/lib/NormalModule.js:445:32
at /Users/richiethomas/Desktop/Workspace/InvestmentTime/new-react-app/node_modules/webpack/lib/NormalModule.js:327:12
at /Users/richiethomas/Desktop/Workspace/InvestmentTime/new-react-app/node_modules/loader-runner/lib/LoaderRunner.js:373:3
at iterateNormalLoaders (/Users/richiethomas/Desktop/Workspace/InvestmentTime/new-react-app/node_modules/loader-runner/lib/LoaderRunner.js:214:10)
at iterateNormalLoaders (/Users/richiethomas/Desktop/Workspace/InvestmentTime/new-react-app/node_modules/loader-runner/lib/LoaderRunner.js:221:10)
at /Users/richiethomas/Desktop/Workspace/InvestmentTime/new-react-app/node_modules/loader-runner/lib/LoaderRunner.js:236:3
at runSyncOrAsync (/Users/richiethomas/Desktop/Workspace/InvestmentTime/new-react-app/node_modules/loader-runner/lib/LoaderRunner.js:130:11)
at iterateNormalLoaders (/Users/richiethomas/Desktop/Workspace/InvestmentTime/new-react-app/node_modules/loader-runner/lib/LoaderRunner.js:232:2)
at Array.<anonymous> (/Users/richiethomas/Desktop/Workspace/InvestmentTime/new-react-app/node_modules/loader-runner/lib/LoaderRunner.js:205:4)
at Storage.finished (/Users/richiethomas/Desktop/Workspace/InvestmentTime/new-react-app/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:55:16)
at /Users/richiethomas/Desktop/Workspace/InvestmentTime/new-react-app/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:91:9
at /Users/richiethomas/Desktop/Workspace/InvestmentTime/new-react-app/node_modules/graceful-fs/graceful-fs.js:123:16
at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:63:3)
@ ./src/App.js 4:0-32 7:13-19
@ ./src/index.js
It says I need an appropriate loader to handle this type, but isn't that what json-loader is supposed to do? Do I have a setup or syntax error somewhere?
I have raw-loader installed and I'm able to import and render the text from foo.txt successfully, so I'm confused why json-loader isn't similarly straightforward for me.
Thanks.
EDIT:
I also get this same error when I use const myJson = require('./foo.json'); instead of import myJson from './foo.json'.
Also interestingly, when I remove json-loader from my Webpack config, both require and import work as expected.
So, my immediate problem of getting the JSON to load is solved, but I'd still like to know why json-loader wasn't working the way I expected it to.
EDIT #2:
From the docs, I do see that there is special require syntax for inline-importing a JSON file via json-loader:
const json = require('json-loader!./file.json');
I tried the following, but it also didn't work:
const myJson = require('json-loader!./foo.json');
uj5u.com熱心網友回復:
從發布的錯誤訊息
Module parse failed: Unexpected token m in JSON at position 0 while parsing near 'module.exports = {"f...'
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token m in JSON at position 0 while parsing near 'module.exports = {"f...'
看起來最重要的部分被截斷了一點。
請注意,根據 webpack 對已發布檔案的決議器的第一個標記是 CommonJS 匯出。
許多 webpack 加載器都是字串到字串的轉換。相繼。默認的 webpack JSON 處理是將檔案作為字串轉換為 CommonJS/ESM。json-loader可能期望原始 JSON,而是獲取相同的 CommonJS 模塊的字串形式。
https://webpack.js.org/migrate/4/#json-and-loaders建議洗掉 JSON 加載器,除非您對 JSON 檔案有特殊的檔案結尾。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/357622.html
