Webpack新手,尝试运行我自己的服务器(node server.js
),但收到此消息:
$ node server.js
/path/to/server.js:3
import path from 'path'
^^^^^^
SyntaxError: Unexpected token import
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:513:28)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.runMain (module.js:575:10)
at run (bootstrap_node.js:352:7)
at startup (bootstrap_node.js:144:9)
at bootstrap_node.js:467:3
我的server.js:
require("babel-register");
import path from 'path'
import Express from 'express'
import React from 'react'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import counterApp from './reducers'
import App from './containers/App'
import { renderToString } from 'react-dom/server'
const app = Express()
const port = 3000
// This is fired every time a request is made
app.use(handleRender)
function handleRender(req, res) {
// Create a new Redux store instance
const store = createStore(counterApp) // this is taken from './reducers'
// Render the component to a string
const html = renderToString(
<Provider store={store}> // Needs an import?
<App /> // this is defined in './containers/...'
</Provider>
)
// Grab the initial state from our Redux store
const preloadedState = store.getState()
// Send the rendered page back to the client
res.send(renderFullPage(html, preloadedState))
}
// Yet to be defined...
function renderFullPage(html, preloadedState) {
return
<!doctype html>
<html>
<head>
<title>Paulos3000 Redux Universal Example</title>
</head>
<body>
<div id='root'>${html}</div>
<script>
window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState)}
</script>
<script src='/static/bundle.js'></script>
</body>
</html>
}
app.listen(port)
有人能看到我的代码有问题吗?如果您需要我提供更多信息(不确定要包含哪些内容,因为我不知道问题的根源),请告诉我。
更新:
SyntaxError: /path/to/server.js: Unexpected token (25:6)
23 |
24 | const html = renderToString(
> 25 | <Provider>
| ^
26 | <App />
27 | </Provider>
28 | )
答案 0 :(得分:2)
根据您的节点版本,它不支持import
语法。
尝试通过require()
使用导入:
const path = require('path').default
答案 1 :(得分:1)
babel-register
不适用于您在其中使用的文件,仅适用于您随后require()
的文件。
例如:
// bootstrap.js
require("babel-register");
require("./server");
// server.js
import path from 'path'
import Express from 'express'
import React from 'react'
...
使用以下命令启动服务器:
$ node bootstrap.js
这假设您已经拥有有效的Babel设置。如果您不想,请在与.babelrc
相同的目录中创建名为server.js
的文件,其中包含以下内容:
{
"presets": ["es2015", "react"]
}
并安装预设模块:
$ npm i babel-preset-es2015 babel-preset-react