用webpack4从零开始构建react开发环境

栏目: JavaScript · 发布时间: 6年前

内容简介:执行npm init,然后创建如下图所示的文件。在index.html里面添加

项目文件准备:

执行npm init,然后创建如下图所示的文件。

用webpack4从零开始构建react开发环境

在index.html里面添加

<!DOCTYPE html>
<html>
  <head>
    <title>The Minimal React Webpack Babel Setup</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="./bundle.js"></script>
  </body>
</html>

在webpack.config.js里面添加

module.exports = {
  entry: './src/index.js',
  output: {
    path: __dirname + '/dist',
    publicPath: '/',
    filename: 'bundle.js'
  },
  devServer: {
    contentBase: './dist'
  }
};

在package.json里面添加

"scripts": {
    "start": "webpack-dev-server --config ./webpack.config.js --mode development"
  },

这样,当执行npm start的时候,就会使用webpack-dev-server把index.js相关文件打包,生成bundle.js,这时候浏览器会打开一个窗口,执行index.html(contentBase里面定义了),又因为index.html里面引入了bundle.js,就可以把压缩后的js文件执行起来。当然引入bundle.js这一步可以由我们强大的html-webpack-plugin完成。

安装依赖

npm install --save-dev webpack webpack-dev-server webpack-cli
npm install --save-dev @babel/core @babel/preset-env
npm install --save-dev babel-loader
npm install --save-dev @babel/preset-react

配置babel

在根目录下新建.babelrc文件,然后添加

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ]
}

在webpack.config.js里面添加babel-loader配置

module.exports = {
  ...
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      }
    ]
  },
  resolve: {
    extensions: ['*', '.js', '.jsx']
  }
 ...
};

这个时候执行npm start,就可以在浏览器访问 http://localhost :8080看到Index.html里面的内容啦啦。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Speed Up Your Site

Speed Up Your Site

Andrew B. King / New Riders Press / 2003-01-14 / USD 39.99

There's a time bomb on the web: user patience. It starts ticking each time someone opens one of your pages. You only have a few seconds to get compelling content onto the screen. Fail, and you can kis......一起来看看 《Speed Up Your Site》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具