webpack 简易配置

安装react
npm install react --save-dev
npm install react-dom --save-dev


安装webpack
npm install webpack --save-dev


安装babel转码,可以使用jsx语法
npm install babel-core --save=dev
npm install babel-loader --save=dev
npm install babel-preset-es2016 --save=dev
npm install babel-preset-react --save=dev


目录结构


配置webpack.config.js
var path = require('path');
var webpack = require('webpack');

var config = {
	entry: [
		//'webpack/hot/dev-server',
		'webpack/hot/only-dev-server',
		'webpack-dev-server/client?http://localhost:8080',//资源服务器地址
		path.resolve(__dirname, 'app/js/main.js')		// 定义入口文件
	],
	output: {									 // 定义出口目录
		//publicPath: "http://127.0.0.1:9090/build/",
        path: path.resolve(__dirname, 'build/js'),
        filename: 'bundle.js'
    },
	module: {
		loaders: [
			{
				test: /.jsx?$/, // 匹配'js' or 'jsx' 后缀的文件类型
				loaders: 'babel-loader', // 使用'babel-loader'也是一样的
				exclude: /node_modules/,	//排除文件
				query:{
					 presets: ["es2016", "react"]
				}
			}
		]
	},
	plugins:[
		
	]
}

module.exports = config;



main.js引用jsx组件
import Hello from './modules/hello.jsx';


hello.jsx组件
import React from 'react';
import ReactDOM from 'react-dom';

class Hello extends React.Component{
	render(){
		return <h1>hello</h1>;
	}
}
ReactDOM.render(<Hello/>, document.getElementById("hello"));


index.html页面文件
<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello React</title>
  </head>
  <body>
    <div id="hello"></div>
    <!--webpack编译后自动生成-->
    <script src="bundle.js"></script>
  </body>
</html>


进行编译打包程序
webpack


安装webpack开发服务器。启动服务后,在浏览器输入http://localhost:8080可访问
npm install webpack-dev-server --save-dev


修改webpack.config.js文件,添加热启动插件。在修改脚本后自动编译并启动服务。
plugins:[
	new webpack.DefinePlugin({
			'process.env.NODE_ENV': '"development"'
		}),
		new webpack.HotModuleReplacementPlugin()
	]


修改package.json文件
{
  "name": "package.json",
  "version": "1.0.0",
  "description": "webpack-test",
  "scripts": {
    "dev": "webpack-dev-server --devtool eval --progress --colors --hot --content-base build"
  },
  "author": "wangzhenjia",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.25.0",
    "babel-loader": "^7.1.1",
    "babel-preset-es2016": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "webpack": "^3.5.4",
    "webpack-dev-server": "^2.7.1"
  }
}



运行npm run dev命令启动服务,在浏览器输入http://localhost:8080可访问
npm run dev


参考文章
  • https://www.twilio.com/blog/2015/08/setting-up-react-for-es6-with-webpack-and-babel-2.html
  • https://fakefish.github.io/react-webpack-cookbook/Getting-started.html

猜你喜欢

转载自jjumperwang.iteye.com/blog/2390542