Node.js 如何使用babel传输节点cli应用程序
我正在使用node编写mt first cli应用程序,并且在使用babel传输代码时遇到了一些问题。 基本上,应用程序应该启动一个express服务器,该服务器对react执行ssr(与next类似)。 在这个过程的某个地方,我使用jsx语法来呈现react组件,所以我需要用babel来传输我的代码。 我熟悉如何使用babel cli或webpack执行此操作, 但是,我仍然面临在cli应用程序中实现它的问题 在我的Node.js 如何使用babel传输节点cli应用程序,node.js,command-line-interface,babeljs,Node.js,Command Line Interface,Babeljs,我正在使用node编写mt first cli应用程序,并且在使用babel传输代码时遇到了一些问题。 基本上,应用程序应该启动一个express服务器,该服务器对react执行ssr(与next类似)。 在这个过程的某个地方,我使用jsx语法来呈现react组件,所以我需要用babel来传输我的代码。 我熟悉如何使用babel cli或webpack执行此操作, 但是,我仍然面临在cli应用程序中实现它的问题 在我的package.json文件中,我有: "bin": { "ssr
package.json
文件中,我有:
"bin": {
"ssr": "./cli/ssr.js"
},
和我的ssr.js文件:
#!/usr/bin/env node
const server = require('../server');
const routes = require('../../routes.js');
const createStore = require('redux').createStore;
const port = process.env.PORT || 3000;
const args = process.argv;
const defReducer = function(state={}, action){
return state;
}
const configureStore = createStore(defReducer);
const instance = server(routes, configureStore, {}, {});
instance.listen(port, ()=>{
console.log(`ssr server runs on localhost://${port}`);
});
而我的server.js文件只是一个普通的express服务器:
const express = require('express');
const cors = require('cors');
const renderer = require('./renderer');
module.exports = (Routes, createStore=()=>null, renderOpts={}, routerContext={})=>{
const app = express();
app.use(express.static('public'));
app.use(cors());
const port = process.env.PORT || 3000;
app.get('*.js', (req, res, next) => {
req.url = req.url + '.gz';
res.set('Content-Encoding', 'gzip');
next();
});
app.all('*', (req, res) => {
const store = createStore();
const promises = matchRoutes(Routes, req.path).map(( { route } ) => {
if (typeof route.path === 'undefined') { return null; }
let ctx = {store, module:route.module, req, res}
return route.loadData ? route.loadData(ctx) : null;
});
Promise.all(promises).then(() => {
const content = renderer(Routes, req, store, renderOpts, routerContext);
if (context.url) {
return res.redirect(301, context.url);
}
if (context.notFound) {
res.status(404);
}
res.send(content);
});
});
return app;
}
在server.js文件中,我调用渲染器
,它执行以下操作:
const content = renderToString(
<Provider store={store}>
<StaticRouter location={req.url} context={routerContext} basename= {opts.baseName || ''}>
<div>{renderRoutes(Routes)}</div>
</StaticRouter>
</Provider>
);
const content=renderToString(
{renderRoutes(Routes)}
);
这就是我得到语法错误的地方。。。
我还尝试使用webpack和babel预编译我的server.js文件
然后将bin命令链接到bundle.js输出,但它不起作用
我在屏幕上弹出了这个错误:
在cli应用程序中使用babel的正确方法是什么?我在这里遵循了几个步骤,您可以在这里找到这些步骤,然后单击“cli”。我能够按照这些步骤传输您的server.js JSX,并在一个新文件夹中添加了一些额外的内容。为了传输您的代码,我做了以下工作:
它成功地运行js并将其传输到lib文件夹中的一个新文件中。在一个全新的文件夹中试用它,让我知道goes如何为您工作我在这里遵循了一些步骤,您可以在这里找到这些步骤,然后单击“CLI”。我能够按照这些步骤传输您的server.js JSX,并在一个新文件夹中添加了一些额外的内容。为了传输您的代码,我做了以下工作:
它成功地运行js并将其传输到lib文件夹中的一个新文件中。在一个全新的文件夹中试用,让我知道如何为您工作我更改了我的.babelrc文件以使用您提供的预设,现在可以工作了…我更改了我的.babelrc文件以使用您提供的预设,现在可以工作了。。。