超級詳細使用Webpack4.X 搭建H5開發(fā)環(huán)境

很久沒弄博客了,這兩天有點時間來搞一下最近在弄的webpack工具

webpack是什么東西我就不介紹了,因為我使用的webpack4以上版本,這個版本有一些較大的更新,可以自己去官網(wǎng)上找找看就知道了。

一、準備工作

node安裝,這個百度、Google一下一大把,不做介紹

二、開始

  1. 構(gòu)建自己的目錄結(jié)構(gòu),下圖是我自己弄的目錄結(jié)構(gòu):


    1.png
  2. 創(chuàng)建package.json文件,或者執(zhí)行npm init 來生成
    我的package.json文件如下:

{
    "name": "h5Base",
    "version": "1.0.0",
    "description": "h5Base",
    "main": "index.js",
    "scripts": {
        "service": "http-server -p 8002",
        "build": "webpack --config ./webpack.config.js --mode production --env.NODE_ENV=production",
        "dev": "node webpack.dev.service"
    },
    "author": "mjg",
    "license": "ISC",
    "devDependencies": {
        "babel-loader": "^7.1.4",
        "birdv3": "^0.3.33",
        "clean-webpack-plugin": "^0.1.19",
        "copy-webpack-plugin": "^4.5.1",
        "css-loader": "^0.28.11",
        "extract-text-webpack-plugin": "^4.0.0-beta.0",
        "file-loader": "^1.1.11",
        "html-loader": "^0.5.5",
        "html-webpack-plugin": "^3.2.0",
        "http-server": "^0.10.0",
        "mini-css-extract-plugin": "^0.2.0",
        "postcss-loader": "^2.1.3",
        "replace": "^0.3.0",
        "style-loader": "^0.20.3",
        "uglifyjs-webpack-plugin": "^1.2.4",
        "url-loader": "^1.0.1",
        "webpack": "^4.3.0",
        "webpack-cli": "^2.0.13",
        "webpack-dev-server": "^3.1.1",
        "webpack-merge": "^4.1.2"
    },
    "dependencies": {}
}

OK,上面是我自己用到的一些庫,如果有需要的朋友拷貝過去,然后執(zhí)行npm install即可。

  1. 修改代碼了
    3.1 先在index.html里面隨便添加點測試代碼:
<!doctype html>
<html lang="">

<head>
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="Cache-Control " content="no-cache,must-revalidate">
  <meta name="description" content="">
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
  <meta content="telephone=no" name="format-detection" />
  <meta name="x5-orientation" content="portrait">
  <title>demo title</title>

</head>

<body>
  <div class="root">
      <h1>我是測試</h1>
  </div>
</body>

</html>

3.2 修改index.js代碼:

import '../style/index.css'

console.log('====================================');
console.log(1);
console.log('====================================');

3.3 修改index.css代碼:

.root {
    background: red;
    width: 200px;
    height: 200px;
    margin: 0 auto;
}
  1. 代碼處理完了,準備需要調(diào)試了,但是我們調(diào)試的話就需要啟動服務(wù),接下來我們就需要配置webpack的服務(wù)了
    4.1 創(chuàng)建webpack.config.js

const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const srcDir = path.join(__dirname, './src');
const distDir = path.join(__dirname, './dist');

module.exports = {
  entry: {
      index: [
          'webpack/hot/dev-server',
          'webpack-dev-server/client?http://localhost:80',
          "./src/js/index.js"
      ]
  },
  output: {
      path: path.resolve(__dirname, 'dist'),
      // 給js css 圖片等在html引入中添加前綴
      publicPath: "../../",
      filename: 'js/[name].min.js',
  },

  devtool: 'source-map',

  module: {
      rules: [
          {
              test: /\.html$/,
              use: [
                  {
                      loader: "html-loader",
                      options: { minimize: true }
                  }
              ]
          },
          {
              test: /\.js$/,
              exclude: /node_modules/,
              use: {
                  loader: "babel-loader"
              }
          },
          {
              test: /\.css$/,
              exclude: /node_modules/,
              use: ExtractTextPlugin.extract({
                  fallback: "style-loader",
                  use: {
                      loader: 'css-loader'
                  },
              })
          },
          {
              test: /\.(gif|jpg|png|woff|svg|eot|ttf)\??.*$/,
              loader: 'url-loader?limit=8192&name=img/[name].[ext]'
          }
      ]
  },

  plugins: [
      new CleanWebpackPlugin(['dist']),

      new ExtractTextPlugin('style/[name].min.css'),
      new HtmlWebpackPlugin({
          hash: true,
          chunks: ['index'],
          template: "./src/pages/index/index.html",
          filename: "pages/index/index.html"
      }),
      
      new webpack.HotModuleReplacementPlugin(),
  ]
};

4.2 創(chuàng)建webpack.dev.service.js

var WebpackDevServer = require("webpack-dev-server");
var webpack = require("webpack");
var webpackConfig = require('./webpack.config.js');
var compiler = webpack(webpackConfig);
var server = new WebpackDevServer(compiler, {

  
  hot: true,
  historyApiFallback: true,
  // It suppress error shown in console, so it has to be set to false.
  quiet: false,
  // It suppress everything except error, so it has to be set to false as well
  // to see success build.
  noInfo: false,
  stats: {
      // Config for minimal console.log mess.
      assets: false,
      colors: true,
      version: false,
      hash: false,
      timings: false,
      chunks: false,
      chunkModules: false
  },
  
  // contentBase不要直接指向pages,因為會導(dǎo)致css、js支援加載不到
  contentBase: __dirname + '/src/',
}).listen(80, '0.0.0.0', function (err) {
  if (err) {
      console.log(err);
  }
});

  1. 啟動服務(wù)配置好了,在看看packag.json里面啟動服務(wù)的命令:

"dev": "node webpack.dev.service"

那么在命令終端中輸入: sudo npm run dev
ps:為什么加sudo?因為使用了80端口,所以加sudo,如果不使用80端口就不用加sudo

  1. 在瀏覽器中輸入:http://localhost/pages/index/index.html就可以看到效果了

  2. 如果想打包正式上線,執(zhí)行命令: npm run build就行,注意把webpack.config.js里面的一些sourceMap、entry里面的熱更新去掉,當然自己重新搞一個線上的webpack.pro.config.js也可以,把一些開發(fā)調(diào)試功能去掉就行了

OK,以上就是我看到webpack4有更新后,隨便搞得一個H5與webpack結(jié)合開發(fā)的工具,有問題歡迎隨時提出!下一章講說一下怎么使用webpack執(zhí)行本地接口proxy,解決本地開發(fā)接口調(diào)試跨域問題

附上github地址:https://github.com/majianguang/h5Base

下一章,如何接入webpack的proxy跨域代理,以及允許綁定本地host調(diào)試的:http://www.itdecent.cn/p/b3e0cc3863e6

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容