使用 Webpack 管理 React 開發環境 === ## 目錄 [TOC] ## 安裝 Visual Studio Code https://code.visualstudio.com/ ## 安裝 Node.js https://nodejs.org/en/ 安裝 Webpack --- 1. 建立專案資料夾 2. 使用 VS Code 開啟專案資料夾 3. 初始化專案: npm init -y 5. 安裝 Webpack: npm install webpack webpack-cli --save-dev 6. 編輯 package.json, 加入以下設定 ```gherkin= ... "script": { ... "build": "webpack" } ... ``` 6. 專案資料夾新增 src 及 dist 資料夾, src 內為原始碼檔案, dist 則為 webpack 編譯結果 7. 使用 npm run build 測試初步結果 安裝 React --- 1. 安裝 React, React-dom: npm install react react-dom --save 2. 安裝 babel-core, babel-loader: npm install babel-core babel-loader --save-dev 3. 安裝 babel-preset-env, babel-preset-react: npm install babel-preset-env babel-preset-react --save-dev 4. 編輯 package.json, 加入以下設定 ```gherkin= ... "babel": { "presets": ["env", "react"] } ... ``` 5. 編輯 package.json, 修改 babel-loader 版本至 7.1.5 ```gherkin= "babel-loader": "^7.1.5" ``` 6. 安裝 babel-loader: npm install babel-loader --save-dev 7. 在專案資料夾新增 Webpack 設定檔([相關設定](https://webpack.js.org/guides/getting-started/#using-a-configuration)), webpack.config.js: ```gherkin= const path = require('path'); module.exports = { entry: './src/index.js', output: { filename: 'main.js', path: path.resolve(__dirname, 'dist'), }, module: { rules: [ { test: /\.js$/, use: [ 'babel-loader' ], }, ], } }; ``` 8. 完成 ###### tags: `React` `Webpack` `Babel`