You need to enable JavaScript to run this app. 在Webpack配置中导入JSX文件时JSX内import语句报模块错误的咨询
优惠活动
大模型
产品
解决方案
定价
更多

在Webpack配置中导入JSX文件时JSX内import语句报模块错误的咨询

Webpack 配置导入 JSX 时报 Cannot use import statement outside a module

问题描述

在 Webpack 配置文件中引入 JSX 文件时,JSX 文件本身可被正常加载,但文件内部的模块导入逻辑会直接触发报错:Cannot use import statement outside a module。
已尝试的排查动作包括:

  • 调整 Babel 配置
  • 引入 @babel/register 依赖
  • 新增 .babelrc 配置文件
  • 修改导入语法形式
    上述操作均未解决问题。

现有项目配置

webpack.config.js 配置内容

const bodyParser = require('body-parser')
require('@babel/register')
const render = require('../src/static/render.jsx')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const path = require('path'); 
const PATHS = {
    app: path.join(__dirname, '../src/static'),
    build: path.join(__dirname, '../src/static_dist')
};
const basePath = path.resolve(__dirname, '../src/static/');

module.exports = {
    mode: 'development',
    devtool: 'cheap-module-eval-source-map', 
    output: {
        filename: '[name].js',
        path: PATHS.build,
        publicPath: '/static/'
    },
    devServer: {
        before: function(app) {
            app.use(bodyParser.json({ limit: '10mb' }))
            app.post('/render', function (req, res) {
                res.sendStatus(204);
                const initialState = {} //buildInitialState(req.body)  
                const result = render(url, initialState)
                res.json({
                    html: result.html,
                    finalState: result.finalState
                })
            });
        },

触发报错的 render.jsx 文件内容

require('@babel/register');

import React from 'react' // *此处为错误抛出位置*
import { Provider } from 'react-redux'
import { match, RouterContext } from 'react-router'
import ReactDOMServer from 'react-dom/server'
import configureStore from './store/configureStore';
import { createBrowserHistory } from "history";
import { routes } from "../routes.js";

import AdminNavbar from "./components/Navbars/AdminNavbar.jsx";
import Sidebar from "./components/Sidebar/Sidebar.jsx";

export default function render (url, initialState) {
 // 函数实现逻辑
}

内容的提问来源于stack exchange,提问作者ambe5960

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.29 15:57:03