我正在嘗試在 React 專案中使用 AWS Amplify UI。但是,在將專案與 WebPack 捆綁后,我收到以下錯誤:(Uncaught SyntaxError: Invalid or unexpected token在 Chrome 中)& SyntaxError: Invalid character '\u00b0'(在 Safari 中)。該錯誤不會出現在 Firefox 中。
當我在使用webpack命令捆綁后加載捆綁的 HTML 檔案時會發生這種情況。但是,在使用 時webpack serve,我觀察到頁面在上述所有瀏覽器中都按預期呈現,沒有錯誤。
包.json
{
"devDependencies": {
"@babel/core": "^7.17.9",
"@babel/preset-env": "^7.16.11",
"@babel/preset-react": "^7.17.12",
"babel-jest": "^27.5.1",
"babel-loader": "^8.2.5",
"copy-webpack-plugin": "^10.2.4",
"css-loader": "^6.7.1",
"eslint": "^8.14.0",
"html-webpack-plugin": "^5.5.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^27.5.1",
"node-polyfill-webpack-plugin": "^1.1.4",
"pa11y": "^6.2.3",
"style-loader": "^3.3.1",
"terser-webpack-plugin": "^5.3.1",
"webpack": "^5.72.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.8.1"
},
"dependencies": {
"@aws-amplify/ui-react": "^3.0.1",
"@fontsource/poppins": "^4.5.8",
"aws-amplify": "^4.3.26",
"jquery": "^3.6.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");
module.exports = (env, argv) => {
let filename = "[name]-bundle.js";
if (argv.mode == "production") {
filename = "[name]-bundle-[contenthash].js";
}
let config = {
entry: {
app: './src/app.js'
},
output: {
filename,
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react']
}
}
},
{
test: /\.css$/,
use: [
{
loader: "style-loader"
},
{
loader: "css-loader",
options: {
importLoaders: 1,
sourceMap: true
}
}
]
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
filename: "index.html",
chunks: ["app"]
}),
new NodePolyfillPlugin()
],
devtool: 'inline-source-map',
devServer: {
static: './dist',
allowedHosts: "all"
}
};
return config;
};
應用程式.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Button } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';
import "@fontsource/poppins/index.css";
function App() {
return (
<div>
<p>Testing</p>
<Button variation="primary">Hello world</Button>
</div>
);
}
const domContainer = document.getElementById("container");
const root = ReactDOM.createRoot(domContainer);
root.render(<App />);
uj5u.com熱心網友回復:
這是一個字符編碼問題。
它與 WebPack DevServer 一起使用,因為charset=utf-8它會自動附加到Content-Type回應的標頭。
在 HTML 檔案的頭部設定字符編碼,如下所示,解決了這個問題。
<meta charset="utf-8" />
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/496208.html
