让节点了解' ES6导入(Babel)

时间:2016-11-03 21:16:13

标签: node.js express import ecmascript-6 babel

尝试运行我的快速服务器,它无法理解“导入”#39;关键词。我以为我已经安装了所有Babel依赖项,但显然不是......

命令:node server.js

控制台:SyntaxError: Unexpected token import

.babelrc - 我还需要添加其他内容吗?

{
  "presets": ["react", "es2015"]
}

的package.json

...

"dependencies": {
    "express": "^4.14.0",
    "react": "^15.3.2",
    "react-dom": "^15.3.2",
    "react-redux": "^4.4.5",
    "redux": "^3.6.0"
  },
  "devDependencies": {
    "babel-cli": "^6.18.0",
    "babel-core": "^6.18.2",
    "babel-loader": "^6.2.7",
    "babel-plugin-transform-react-jsx": "^6.8.0",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-react": "^6.16.0",
    "webpack": "^1.13.3"
  }

...

server.js

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'

const app = Express()
const port = 3000

// This is fired every time the server side receives a request
app.use(handleRender)

import { renderToString } from 'react-dom/server'

function handleRender(req, res) {
  // Create a new Redux store instance
  const store = createStore(counterApp)

  // Render the component to a string
  const html = renderToString(
    <Provider store={store}>
      <App />
    </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))
}

function renderFullPage(html, preloadedState) {
  return `
    <!doctype html>
    <html>
      <head>
        <title>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)

更新

现在已经完成以下任务:

命令:npm install babel-plugin-transform-es2015-modules-commonjs

.babelrc

{
  "presets": ["react", "es2015"],
  "plugins": ["transform-es2015-modules-commonjs"]
}

命令:babel server.js --out-file server-compiled.js

命令:node server-compiled.js

- &GT; server.js的汇编似乎有效。我仍然收到相同的错误消息,但这次是文件./containers/App.ks,它还包含一个ES6模块语句。

我在我的webpack.config.js文件中包含了所有babel插件和预设,所以我假设我的捆绑处理所有其他文件?

服务器-compiled.js

'use strict';

var path = require('path');
var Express = require('express');
var React = require('react');
var redux = require('redux').createStore;
var Provider = require('react-redux').Provider;
var counterApp = require('./reducers');
var App = require('./containers/App');

var app = Express();
var port = 3000;

// This is fired every time the server side receives a request
app.use(handleRender);

var renderToString = require('react-dom/server').renderToString;

function handleRender(req, res) {
  // Create a new Redux store instance
  var store = createStore(counterApp);

  // Render the component to a string
  var html = renderToString('\n    <Provider store={store}>\n      <App />\n    </Provider>\n    ');

  // Grab the initial state from our Redux store
  var preloadedState = store.getState();

  // Send the rendered page back to the client
  res.send(renderFullPage(html, preloadedState));
}

function renderFullPage(html, preloadedState) {
  return ' <!doctype html>\n    <html>\n      <head>\n        <title>Redux Universal Example</title>\n      </head>\n      <body>\n        <div id="root">' + html + '</div>\n        <script>\n          window.__PRELOADED_STATE__ = ' + JSON.stringify(preloadedState) + '\n        </script>\n        <script src="/static/bundle.js"></script>\n      </body>\n    </html>\n    ';
}

app.listen(port);

webpack.config.js

module.exports = {
    entry: "./client.js",
    output: {
        path: __dirname,
        filename: "bundle.js"
    },
    module: {
        loaders: [
            { test: /\.css$/, loader: "style!css" },
            {
               test: /\.js$/,
               exclude: /(node_modules|bower_components)/,
               loader: 'babel', // 'babel-loader' is also a valid name to reference
               query: {
                  presets: ['es2015', 'react'],
                  plugins: ['transform-es2015-modules-commonjs']
               }
            }
        ]

client.js (条目档案)

import React from 'react'
import { render } from 'react-dom'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import App from './containers/App'
import counterApp from './reducers'

// Grab the state from a global injected into server-generated HTML
const preloadedState = window.__PRELOADED_STATE__

// Create Redux store with initial state
const store = createStore(counterApp, preloadedState)

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

containers / App.js - 此文件仍会在控制台中显示错误

import React, { Component } from 'react'

export default class App extends Component {
   render() {
      return (
         <div>App Component Here</div>
      )
   }
}

2 个答案:

答案 0 :(得分:3)

安装Babel并创建.babelrc文件是不够的。您必须实际编译文件并使用node运行已编译的文件。

您可以使用以下命令编译文件:

babel server.js --out-file server-compiled.js

然后运行它:

node server-compiled.js

要编译整个目录,请使用以下命令:

babel src --out-dir lib

src替换为保存源文件的目录的名称,将lib替换为您希望输出编译文件的目录的名称。

另见Babel CLI docs

答案 1 :(得分:0)

我遇到了这个问题,并使用babel-node代替节点解决了问题。我正在使用Webstorm,通过查看node_packages(或者如果你在Windows ~\AppData\Roaming\npm\babel-node.cmd~/.node/bin/babel-node * nix / osx全局安装它来更改节点解释器很简单。在Windows中,使用*.cmd的重要方法。