超级详细使用Webpack4.X 搭建H5开发环境

很久没弄博客了,这两天有点时间来搞一下最近在弄的webpack工具

webpack是什么东西我就不介绍了,因为我使用的webpack4以上版本,这个版本有一些较大的更新,可以自己去官网上找找看就知道了。

一、准备工作

node安装,这个百度、Google一下一大把,不做介绍

二、开始

  1. 构建自己的目录结构,下图是我自己弄的目录结构:


    超级详细使用Webpack4.X 搭建H5开发环境_第1张图片
    1.png
  2. 创建package.json文件,或者执行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,上面是我自己用到的一些库,如果有需要的朋友拷贝过去,然后执行npm install即可。

  1. 修改代码了
    3.1 先在index.html里面随便添加点测试代码:




  
  
  
  
  
  
  
  demo title




  

我是测试

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. 代码处理完了,准备需要调试了,但是我们调试的话就需要启动服务,接下来我们就需要配置webpack的服务了
    4.1 创建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 创建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,因为会导致css、js支援加载不到
  contentBase: __dirname + '/src/',
}).listen(80, '0.0.0.0', function (err) {
  if (err) {
      console.log(err);
  }
});

  1. 启动服务配置好了,在看看packag.json里面启动服务的命令:

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

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

  1. 在浏览器中输入:http://localhost/pages/index/index.html就可以看到效果了

  2. 如果想打包正式上线,执行命令: npm run build就行,注意把webpack.config.js里面的一些sourceMap、entry里面的热更新去掉,当然自己重新搞一个线上的webpack.pro.config.js也可以,把一些开发调试功能去掉就行了

OK,以上就是我看到webpack4有更新后,随便搞得一个H5与webpack结合开发的工具,有问题欢迎随时提出!下一章讲说一下怎么使用webpack执行本地接口proxy,解决本地开发接口调试跨域问题

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

下一章,如何接入webpack的proxy跨域代理,以及允许绑定本地host调试的:https://www.jianshu.com/p/b3e0cc3863e6

你可能感兴趣的:(超级详细使用Webpack4.X 搭建H5开发环境)