我正在使用 php 将数据发布到 node.js 以在服务器端渲染 ReactJS 组件。
调试控制台显示,当变量 component
返回 undefined
时,会发生错误 Unexpected token ILLEGAL
。
React = require('react'),
ReactDOM = require('react-dom/server'),
require('babel-core/register');
app.post('/something', function (req, res) {
try {
var view = './src/ItemPage';
var component = require(view); <<<====== Error
var props = req.body || null;
res.status(200).send(
ReactDOM.renderToString(
React.createElement(component, props)
)
);
} catch (err) {
res.status(500).send(err.message);
}
});
问题是由于从 Grommet UI 库导入 css 脚本以便将 css 包含在 bundle.js
中造成的。如果我删除该样式导入行,则脚本运行正常。为什么以下类在 Node 中返回未定义?有语法错误吗?它在 webpack 中编译得很好。
ItemPage 类:
import React from 'react';
import Tabs from 'grommet/components/Tabs';
import Tab from 'grommet/components/Tab';
import 'grommet/grommet.min.css'; <<=== Error !!!!
export default class ItemPage extends React.Component {
render(){ return <Tabs>
<Tab title="First Title">
<h3>First Tab</h3>
<p>Contents of the first tab !</p>
</Tab>
<Tab title="Second Title">
<h3>Second Tab</h3>
<p>Contents of the second tab</p>
</Tab>
<Tab title="Third Title">
<h3>Third Tab!</h3>
<p>Contents of the third tab</p>
</Tab>
</Tabs>
}
}
module.exports = ItemPage;
最佳答案
如果您希望能够将样式表与其他模块模块化,您应该将 css-laoder
与 webpack 结合使用。
安装它:
npm install style-loader css-loader --save-dev
并配置它:
{
// ...
module: {
loaders: [
{ test: /\.css$/, loader: "style-loader!css-loader" }
]
}
}
这将使得需要 css 成为可能。
关于javascript - 在reactjs es6文件中导入css脚本时出现意外的 token 非法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38323044/