webpack 打包一個簡單react組件

安裝Webpack,並加載一個簡單的React組件html

 

全局的npm模塊安裝:react

npm install -g webpack

安裝jsx-loaderwebpack

npm install --save-dev jsx-loader

 

默認使用當前目錄的本身新建立的webpack.config.js做爲配置文件web

module.exports = {
    entry: [
      './assets/js/entry.js'
    ],
    output: {
        path: __dirname + '/assets/',
        publicPath: "/assets/",
        filename: 'bundle.js'
    },
    module: {
        loaders: [
          { test: /\.jsx?$/, loaders: ['jsx-loader?harmony'] }
        ]
    }
};

 

定義了一個簡單的React組件hello.js,使用ES6語法 npm

var React = require('react');
class Hello extends React.Component {
  render() {
    return (
      <h1>Hello {this.props.name}!</h1>
    );
  }
}
module.exports = Hello; 

 


建立entry.js入口文件,將一個Hello組件輸出到界面:服務器

var React = require('react');
var Hello = require('./Hello');
React.render(<Hello name="Nate" />, document.body);

 

 建立根目錄index.html文件webpack-dev-server

<html>
<head>
</head>
<body>
<script src="/assets/bundle.js"></script>
</body>
</html>

 

項目文件夾結構:ui

+ assets/
    - js/ Hello.js entry.js index.html webpack.config.js

 

 在當前目錄執行webpack命令以後,在assets目錄將生成bundle.js,打包了entry.js的內容this

webpack

 

經過npm安裝Webpack開發服務器並啓動它:spa

npm install webpack-dev-server -g
webpack-dev-server --progress --colors

 

好如今能夠經過http://localhost:8080/webpack-dev-server/index.html打開頁面,以下:

 

[轉載] http://www.cnblogs.com/fastmover/p/4867599.html

相關文章
相關標籤/搜索