从零开始学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
};

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