2017-06-25 18 views
2

我對Webpack很新,​​我只是試圖在這裏得到一個簡單的項目。我收到以下錯誤:如何獲取Webpack以轉儲ES6代碼?

ERROR in ./index.js 
Module parse failed: /Users/jay/Documents/personal_projects/open_phil_grants_visualizer/index.js Unexpected token (6:16) 
You may need an appropriate loader to handle this file type. 
| import App from './app'; 
| 
| ReactDOM.render(<App />, document.getElementById('content')); 
| 
@ multi (webpack)-dev-server/client?http://localhost:8080 ./index.js 

這裏是我的webpack.config.js

module.exports = { 
    entry: './index.js', 
    output: { 
     path: __dirname, 
     filename: 'bundle.js' 
    }, 
    devtool: 'source-map' 
}; 

的依賴在我package.json

"dependencies": { 
    "d3": "^4.9.1", 
    "lodash": "^4.17.4", 
    "react": "^15.6.1", 
    "react-d3-basic": "^1.6.11", 
    "react-dom": "^15.6.1" 
}, 
"devDependencies": { 
    "babel-cli": "^6.24.1", 
    "babel-preset-es2015": "^6.24.1", 
    "webpack-dev-server": "^2.4.5" 
} 

這是我index.js

import React from 'react'; 
import ReactDOM from 'react-dom'; 

import App from './app'; 

ReactDOM.render(<App />, document.getElementById('content')); 

這裏是app.js

import React from 'react'; 

class App extends React.Component { 
    render() { 
    return(
     <h2> 
     Hello from the App component! 
     </h2> 
    ) 
    } 
} 

export default App; 

我怎樣才能得到這個東西去?

回答

6

您將需要設置加載器規則,以實際處理文件並將其轉換爲瀏覽器兼容的ES5。 Webpack不會自動將您的ES2015和JSX代碼轉換爲網頁兼容,您必須告訴它將loader應用於某些文件,以便將它們轉換爲網絡兼容代碼,如錯誤狀態所示。既然你不這樣做,錯誤就會發生。

假設你有版本的WebPack 2+,在配置使用rules屬性:

module.exports = { 
    entry: './index.js', 
    output: { 
    path: __dirname, 
    filename: 'bundle.js' 
    }, 
    devtool: 'source-map', 
    module: { 
    rules: [ 
     { 
     test: /\.jsx?/, 
     include: 'YOUR_APP_SRC_DIR', 
     use: { 
      loader: 'babel-loader', 
      options: { 
      presets: ['es2015', 'react'] 
      } 
     } 
     } 
    ] 
    } 
}; 

這添加一條規則,使用正則表達式中test的配置的WebPack選擇在.js.jsx結尾的文件。然後它使用babel-loader與預設es2015react使用Babel並將您的JSX和ES2015代碼轉換爲ES5代碼。你還需要安裝以下軟件包:

  • babel-core
  • babel-loader
  • babel-preset-react

而且你可以擺脫:

  • babel-cli

更多信息在Webpack documentation for modules