用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里面的内容啦啦。


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

查看所有标签

猜你喜欢:

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

An Introduction to Probability Theory and Its Applications

An Introduction to Probability Theory and Its Applications

William Feller / Wiley / 1991-1-1 / USD 120.00

Major changes in this edition include the substitution of probabilistic arguments for combinatorial artifices, and the addition of new sections on branching processes, Markov chains, and the De Moivre......一起来看看 《An Introduction to Probability Theory and Its Applications》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

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

html转js在线工具