gulp+webpack-dev-server 輕量伺服開發(fā)環(huán)境

1.在package.json中添加腳本或者命令行直接執(zhí)行任務(wù)
2.新版本的gulp必須要從gulpfile.js或者gulpfile.js文件夾下面的index.js中導(dǎo)出任務(wù),才能被gulp --task審查到



舊版棄用task暴露任務(wù)

parallel為并發(fā),series為順序執(zhí)行

const gulp = require('gulp');
const { runDev } = require('./dev');

exports.runDev = gulp.series(
  runDev
);

基本任務(wù)配置

const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const WebpackDevServer = require('webpack-dev-server');
const path = require('path');
const HtmlWebpackPlugin = require("html-webpack-plugin");

async function runDev() {
  const mode = { mode: 'development' };
  const exclude = [
    /node_modules/
  ];
  // webpack配置
  const cfg = {
    //腳本入口
    entry: {
      index: path.join(__dirname, '../src/index.tsx'),
    },
     //腳本出口
    output: {
      path: path.join(__dirname, "../dist/"),
      filename: '[name].js'
    },
    resolve: {
      modules: [path.join(__dirname, "../src"), "node_modules"],
      extensions: [".js", ".jsx", ".ts", ".tsx", ".css", ".less"]
    },
    module: {
      rules: [{
        test: /(\.js)|(\.ts)|(\.tsx)$/,
        exclude,
        loader: "ts-loader",
        options: {
          transpileOnly: true
        }
      },
      {
        test: /\.css$/,
        exclude,
        use: ["style-loader", "css-loader", "postcss-loader"]
      },
      ]
    },
     // 至關(guān)重要
    plugins: [
      new HtmlWebpackPlugin({
        hash: true,
        inject: true,
        chunks: ["index"],
        template: path.join(__dirname, '../src/index.html'),
        filename: "index.html"
      }),
    ],
  };
  const webpackConfig = webpackMerge(cfg, mode);
  const compiler = webpack(webpackConfig);
  // dev server配置
  const defaultServer = {
    // 伺服的directory
    contentBase: path.join(__dirname, '../dist'),
    compress: true,
    open: true,
    // index:作為string來索引頁面
    index: 'index.html',
  };
  console.log('Dev Server page is ' + path.join(__dirname, '../src/index.html'))

  const serverPort = 9998;
  new WebpackDevServer(compiler, defaultServer).listen(serverPort, 'localhost', () => {
    console.log('dev server listening on port' + serverPort);
  });
}

module.exports = {
  runDev
}

HtmlWebpackPlugin簡化了HTML文件的創(chuàng)建,以便為你的webpack包提供服務(wù)。這對于在文件名中包含每次會隨著編譯而發(fā)生變化哈希的 webpack bundle 尤其有用。
注意:你啟動webpack-dev-server后,你在目標(biāo)文件夾中是看不到編譯后的文件的,實時編譯后的文件都保存到了內(nèi)存當(dāng)中。因此很多同學(xué)使用webpack-dev-server進行開發(fā)的時候都看不到編譯后的文件

最后編輯于
?著作權(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ù)。

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