学习webpack,从0搭建react项目

从0搭建react项目

最近学习了webpack的基础知识,想要不通过脚手架就能自己搭好react项目,通过之前的学习,今天自己来动手实践一下,顺便复习一遍之前学习的知识,为后续的学习打好基础。

这里记录的是我今天的成果,可能webpack写的比较粗糙。

webpack.config.js

const path=require('path'); //使用__dirname变量,获取当前文件的绝对路径,避免在不同操作系统之间的路径问题
const HtmlWebpackPlugin = require('html-webpack-plugin');//使webpack自动按照模板将Html文件添加进打包目录中
const {CleanWebpackPlugin}=require('clean-webpack-plugin');



module.exports={
    mode:'development',//现在为开发环境
    entry:'./src/index.js',
    devtool:'cheap-module-eval-source-map',
    devServer:{
        contentBase:'./build',
        open:true,
        port:8080
    },
    module: {
        rules: [
            { test: /\.js$/, 
                exclude: /node_modules/,//不会去翻译node_modules中的文件
                loader: "babel-loader" ,
                options:{
                    "presets":[["@babel/preset-env",{
                        useBuiltIns:'usage'//按需加入es6新特性
                    }],
                    "@babel/preset-react"
                    ]
                }
            },{
                test:/\.less$/,
                use:[
                    {
                        loader:"style-loader"
                    }, {
                        loader: "css-loader" // translates CSS into CommonJS
                    }, {
                        loader: "less-loader" // compiles Less to CSS
                    }
                ]
            },{
                test:/\.jpg$/,
                use:{
                    loader:'url-loader',
                    options:{
                        name:'[name].[ext]',
                        outputPath:'images/',
                        limit:20480
                    }
                }
            }
        ]
      },
    plugins: [new HtmlWebpackPlugin({
		template:'public/index.html'//html模板
	}),new CleanWebpackPlugin()],//打包前,帮助将dist内的文件清除掉
    output:{
        path:path.resolve(__dirname,"build"),//打包文件导出
        filename:'[name].[hash].bundle.js',//文件名
    }
}

package.json

{
  "name": "mybolg",
  "version": "1.0.0",
  "description": "zhangmiao's blog",
  "private": true,
  "scripts": {
    "start": "webpack-dev-server"
  },
  "keywords": [],
  "author": "zhangmiao",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.9.6",
    "@babel/preset-env": "^7.9.6",
    "@babel/preset-react": "^7.9.4",
    "babel-loader": "^8.1.0",
    "clean-webpack-plugin": "^3.0.0",
    "css-loader": "^3.5.3",
    "file-loader": "^6.0.0",
    "html-webpack-plugin": "^4.3.0",
    "less": "^3.11.1",
    "less-loader": "^6.1.0",
    "style-loader": "^1.2.1",
    "url-loader": "^4.1.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.11.0"
  },
  "dependencies": {
    "@babel/polyfill": "^7.8.7",
    "react": "^16.13.1",
    "react-dom": "^16.13.1"
  }
}

posted @ 2020-05-14 17:21  ellenxx  阅读(567)  评论(0编辑  收藏  举报