1. 程式人生 > >使用webpack搭建一個react專案

使用webpack搭建一個react專案

npm init

package.json檔案配置

{
  "name": "serach-bar",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack-dev-server --progress --profile --colors --hot",
    "build": "webpack --progress --profile --colors",
    "test": "karma start"
  },
 //scripts這邊可以改一下,改start可以,在終端用npm start,上面有例子~這邊的dev要改的話在終端的命令是'npm run dev;
"author": "", "license": "ISC", "devDependencies": { "babel-core": "^6.22.1", "babel-loader": "^6.2.10", "babel-plugin-react-transform": "^2.0.2", "babel-preset-es2015": "^6.22.0", "babel-preset-react": "^6.22.0", "babel-preset-react-hmre": "^1.1.1", "bootstrap": "^4.0.0-alpha.2"
, "css-loader": "^0.26.1", "file-loader": "^0.10.0", "html-webpack-plugin": "^2.28.0", "jquery": "^3.1.1", "jshint": "^2.9.4", "jshint-loader": "^0.8.3", "json-loader": "^0.5.4", "node-sass": "^4.5.0", "react": "^15.4.2", "react-dom": "^15.4.2", "react-transform-catch-errors"
: "^1.0.2", "react-transform-hmr": "^1.0.4", "redbox-react": "^1.3.3", "sass-loader": "^4.1.1", "style-loader": "^0.13.1", "url-loader": "^0.5.7", "webpack": "^2.2.1", "webpack-dev-server": "^2.3.0" } }

配置的外掛不一定所有的都會用到

webpack.config.js檔案配置

var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ROOT_PATH = path.resolve(__dirname);
var APP_PATH = path.resolve(ROOT_PATH, 'app');
var BUILD_PATH = path.resolve(ROOT_PATH, 'build');

module.exports = {
    devtool: 'eval-source-map',
    entry: __dirname + '/app/index.js',
//webpack的入口檔案只有一個,所以寫的所有components甚至包括css/json什麼的,都要引用在這裡
output:{
    path: __dirname +'/public',
    filename: 'bundle.js',
},
//我這邊是新建了一個folder叫public,用來放index.html和bundle.js
devServer: {
    contentBase: "./public",//本地伺服器所載入的頁面所在的目錄
    historyApiFallback: true,//不跳轉
    inline: true//實時重新整理
},
plugins: [
    new HtmlWebpackPlugin({
        title: 'searchBar',    //配合html-webpack-plugin的配置
    })
],
module: {
    loaders: [
    {
        test: /\.(png|jpq)$/,
        loader: 'url? limit = 40000'
    },{
        test: /\.js$/,
        loader:'babel-loader',
        include: APP_PATH,
    }]
},
resolve:{
        extensions: ['','.js', '.jsx']
    },
};

.babelrc

{
    'presets':['react','es2015'],
    'env':{
    'development':{
    'presets':['react-hmre']
    }
    }
}