问题描述
我正在尝试将JSX文件导入到我的webpack配置中。似乎文件已导入,但我无法将模块导入该文件。我不断收到错误消息,说Cannot use import statement outside a module
这是我的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' <-- error happens here
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) {
... a function ...
}
我觉得我已经尝试了一切!修补babel,添加@ babel / register,添加.babelrc,更改其导入方式等。
解决方法
您可能需要告知Webpack resolve
该特定扩展名。
以下是resolve
上的文档:Resolve
代码:
module.exports = {
//...
resolve: {
extensions: ['.js','.jsx']
}
};
我还注意到您尚未指定entry
。如果上述解决方案不起作用,请尝试指定以下内容:
module.exports = {
//...
entry: './src/Render.jsx'
};
文档:Entry Point
您可能必须两者都做。