webpack搭建一个js编译环境

前端工程化的出现, 迎来了前端开发的春天, 其中, webpack是春天里最美丽的一朵花, 我们接下来通过一段实例来一睹芬芳

  • 目录结构如下:
    |src -
        index.js
    |.babelrc
    |index.html
    |package.json
    |webpack.dev.config.js
  • 环境需要安装node
  • npm init 初始化一个项目
  • 包的安装
     npm install babel-core babel-polyfill babel-preset-es2015 babel-preset-latest 
     html-webpack-plugin webpack webpack-cli webpack-dev-server --save-dev
    
  • webpack.dev.config的配置
     path= require('path');
     HtmlWebpackPlugin = require('html-webpack-plugin')
    
    module.export={
       entry:'./src/index.js',
       output:{
             path: __dirname,
             filename:'./release/bundle.js'
        }
     },
     module:{
          rules:[
              {
                   test: /\.js?$/,
                   exclude: /(node_modules)/,
                   loader: babel-loader
              }
          ]
    },
    plugins:[
       new HtmlWebpackPlugin ({
             template:'./index.html'
      })
    ],
    devServer: {
         contentBase: path.join(__dirname, './release'), // 根目录
         open: true,  // 自动打开浏览器
         port: 9000,
     }
    
  • .babelrc编译es6
       {
        "presets": [
          "es2015",
          "latest"
        ],
        "plugins": []
     }
    
  • package.json配置
      "scripts": {
       "test": "echo \"Error: no test specified\" && exit 1",
     + "dev": "webpack-dev-server --config ./webpack.dev.config.js --mode development"
    }
    

至此, 配置完成,在index.html中加入html模板, 运行

  npm run dev

启动服务, OK!

你可能感兴趣的:(webpack搭建一个js编译环境)