從零開始學React(1)——配置webpack

webpack配置

基本配置

  1. 新建文件夾,起名react1
  2. 打開終端,打開至文件夾,輸入命令:npm init
  3. 一路回車,直至完成
  4. 創建webpack.config.js文件,並在其中書寫以下內容(摘自官網)
const path = require('path');

module.exports = {
 entry: './app/main.js',
 output: {
   filename: 'main.js',
   path: path.resolve(__dirname, 'dist')
 }
};

babel配置

  1. 前往https://github.com/babel/babel-loader
  2. 將以下內容(摘自官網)粘貼至output下方
module: {
  rules: [
    {
      test: /\.js$/,
      exclude: /(node_modules|bower_components)/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['es2015']
        }
      }
    }
  ]
}
  1. 因未安裝babel-loader,所以安裝babel-loader:npm i babel-loader -D
  2. 提示未安裝babel-core,所以安裝babel-core:npm i babel-core -D
  3. 運行webpack時報錯,提示未安裝preset,去安裝preset:npm i babel-preset-es2015 -D

配置React

  1. 安裝React npm包,npm i react -D
  2. 安裝React-dom包,npm i react-dom -D
  3. 因需要翻譯JSX語法,webpack的loader的preset中需添加react,上方代碼變更爲
module: {
 rules: [
   {
     test: /\.js$/,
     exclude: /(node_modules|bower_components)/,
     use: {
       loader: 'babel-loader',
       options: {
         presets: ['es2015','react']
       }
     }
   }
 ]
}
  1. 此時配置的react其實並未生效,因爲其並未被安裝,此時應運行命令:npm i babel-preset-react
  2. 記得要想查看效果需要編寫index.html文件並引入js文件呦。
  3. 此時已配置完成,但要想讓webpack持續監聽js變化自動打包,在modules的後面添加watch:true
    完整的webpack.config.js如下
const path = require('path');

module.exports = {
 entry: './app/main.js',
 output: {
   filename: 'main.js',
   path: path.resolve(__dirname, 'dist')
 },
 module: {
   rules: [
     {
       test: /\.js$/,
       exclude: /(node_modules|bower_components)/,
       use: {
         loader: 'babel-loader',
         options: {
           presets: ['es2015','react']
         }
       }
     }
   ]
 },
 watch: true
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章