[英]Module parse failed: Unexpected token (9:37) with babel-loader
I am serving the app through Express, which needs to use ES modules.我通过 Express 为应用程序提供服务,它需要使用 ES 模块。 Node does allow that, but I had to replace __dirname with another solution:
Node 确实允许这样做,但我不得不用另一个解决方案替换 __dirname :
server.mjs:服务器.mjs:
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
This resulted in error with Babel, which required me to add extra plugin ( https://babeljs.io/docs/en/next/babel-plugin-syntax-import-meta.html ).这导致 Babel 出错,这需要我添加额外的插件( https://babeljs.io/docs/en/next/babel-plugin-syntax-import-meta.html )。 I replaced original CRA with custom webpack and created .babelrc:
我用自定义 webpack 替换了原始 CRA 并创建了 .babelrc:
{
"presets": ["@babel/preset-env", "@babel/preset-react"],
"plugins": ["@babel/plugin-syntax-import-meta"]
}
webpack.config.js: webpack.config.js:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/index.js", // entry point to the application = top react component,
output: {
path: path.resolve(__dirname, "build"), // path where the transformed index.js will be stored
filename: "index_bundle.js", //name of the transformed file
},
module: {
rules: [
{
test: /\.(js|mjs|jsx)$/, use: {
loader: 'babel-loader',
}
}, // what files will be loaded by what procedure
{test: /\.css$/, use: ['style-loader', 'css-loader']},
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
},
],
},
]
},
mode: "development",
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.html" // will take the template file and transform it to include the rest
}),
]
};
I am still runing into an error when trying to build the app.尝试构建应用程序时,我仍然遇到错误。 It seems that all other files are built successfully, but server.mjs is still returning an error:
似乎其他所有文件都构建成功,但是 server.mjs 仍然返回错误:
ERROR in ./src/server/server.mjs 9:66
Module parse failed: Unexpected token (9:66)
File was processed with these loaders:
* ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| import getInitialPlayerStates from "../components/functions/initialStateFunctions.mjs";
|
> var __dirname = path.resolve(path.dirname(decodeURI(new URL(import.meta.url).pathname)));
|
| var port = process.env.PORT || 4001;
@ ./src/App.js 49:0-48 119:14-27
@ ./src/index.js
Other .mjs files are being build alright unless I include the line with import.meta in their code - than they fail too.其他 .mjs 文件正在构建中,除非我在它们的代码中包含带有 import.meta 的行 - 否则它们也会失败。
What is wrong?怎么了? How can I overcome this problem?
我怎样才能克服这个问题?
"es-dirname" library solves the problem without using "import.meta". “es-dirname”库无需使用“import.meta”即可解决问题。
https://www.npmjs.com/package/es-dirname https://www.npmjs.com/package/es-dirname
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.