在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
相关产品推荐
相关产品推荐

