react腳手架搭建javascript
因爲公司項目一直用的webpack3點幾,因此我webpack會用4.0如下,若是用的weback4.0(webpack和webpack-cli沒有集成到一塊兒會有差別)html
1先建一個文件夾如:react-cli-basic
2 npm init 建立page.json文件
java
回車就好node
文件夾就多了一個page.jsonreact
3 react必須裝的插件
react react-dom babelify babel-preset-es2015 babel-preset-react 安裝 ,建立一個index.html 建立一個文件夾src子文件index.js 要跑這個服務,那就必需要裝webpack (建議版本webpack@3.6.0) 建立配置文件webpack.config.js 文件目錄以下webpack
//webpack.config.js基本配置 var webpack = require('webpack'); var path = require('path'); module.exports={ context: path.join(__dirname), entry: "./src/index.js", //入口文件 module: { rules: [ { test: /\.js?$/, exclude: /(node_modules)/, loader: 'babel-loader', query: { presets: ['react', 'es2015'] } } ] }, output: { path: __dirname, filename: "./dist/bundle.js" //生成的文件輸出到dist裏面 } }
而後直接跑指令webpack 若是出現webpack不是內部指令說明webpack沒全局安裝,環境變量裏面讀不到(若是你node安裝環境變量已經配置好了,直接npm install wenpack -g)便可web
若是報這個錯,安裝一下babel-loader(npm install babel-loader --save)npm
若是繼續報上面錯誤繼續安裝 babel-core(npm install babel-core --save),json
還報錯的話,報錯建議安裝7.幾版本,把以前安裝的babel-loader先卸載(npm uninstall babel-loader --save),再次安裝(npm uninstall babel-loader@瀏覽器
到這步你的項目就能夠跑起來了
展現下index.js 和index.html裏面文件//index.js const React =require('react'); const ReactDOM = require('react-dom'); ReactDOM.render( <h1>hello world</h1>, document.getElementById('example') ) index.html <div id="example"></div> <script src="./dist/bundle.js" charset="utf-8"></script> 這個路徑就是你webpack以後生成的文件路徑
而後直接index.html右鍵瀏覽器打開就能夠看到以下
你在次修改文件你會發現不會熱更新,這時候你就要安裝webpack-dev-server(npm install webpack-dev-server@2.9.1--save)
而後你就能夠直接訪問localhost:8084 來訪問你的服務
貼一份package.json配置
{ "name": "react-cli-basic", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "babel-core": "^6.26.3", "babel-loader": "^7.1.1", "babel-preset-es2015": "^6.24.1", "babel-preset-react": "^6.24.1", "babelify": "^10.0.0", "react": "^16.9.0", "react-dom": "^16.9.0", "webpack": "^3.6.0", "webpack-dev-server": "^2.9.1" } }
引入路由
react-router(npm install react-router --save)
若是若有的版本是2-3瀏覽器會報一個
react Cannot read property 'func' of undefined
這種錯,你能夠把react和react-dom的版本降到15.X就能夠了下一篇介紹引入路由以後wabpack的變化