webpack搭建项目

1.初始化项目安装webpack相关工具

// 按指示初始化 NPM 设定 package.json
$ npm init
// --save-dev 是可以让你將安装套件的名称和版本咨询存放到 package.json,方便日后使用
$ npm install --save-dev babel-core babel-eslint babel-loader babel-preset-es2015 babel-preset-react html-webpack-plugin webpack webpack-dev-server
2.在根目录设置webpack.config.js
//使用 HtmlWebpackPlugin,將 bundle 好的插入到 body。${__dirname} 为 ES6 语法对应到 __dirname

const HtmlWebpackPlugin = require('html-webpack-plugin');
const HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
template: `${__dirname}/app/index.html`,
filename: 'index.html',
inject: 'body',
});
module.exports = {
// 应用开启后从 entry 进入,唯一入口文件
entry: [
'./app/index.js',
],
// output 导出文件名 以及 路径
output: {
path: `${__dirname}/dist`,
filename: 'index_bundle.js',
},
module: {
//通过使用不同的loader,webpack有能力调用外部的脚本或工具,实现对不同格式的文件的处理
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: { presets: ['es2015', 'react'],},
},
],
},
// devServer 則是 webpack-dev-server 設定
devServer: {
inline: true, //实时刷新
port: 8008,
},
// plugins 放置所使用的插件
plugins: [HTMLWebpackPluginConfig],
};


3.app下创建index.js
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = { };
}
render() {
return (
Hello World);
}
} ReactDOM.render(, document.getElementById('app'));
4.package.json下加启动配置
"scripts": {
"dev": "webpack-dev-server --devtool eval --progress --colors --content-base build"
}
5.启动
【webpack搭建项目】npm run dev

    推荐阅读