Skip to content

开发服务器&自动化

每次写完代码还要手动输入指令才能编译代码,太麻烦了,我们希望一切自动化

1. 下载包

npm i webpack-dev-server -D

2. 配置

  • webpack.config.js
js
const path = require('path')
const ESLintWebpackPlugin = require('eslint-webpack-plugin')
const HTMLWebpackPlugin = require('html-webpack-plugin')

mmodule.exports = {
  entry: '',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '/static/js/index.js'
    clear: true
  },
  module: {
    rules: [{
      test: /\.css$/,
      use: ['style-loader', 'css-loader']
    },{
      test: /\.less$/,
      use: ['style-loader', 'css-loader', 'less-loader']
    },{
      test: /\.s[ac]ss$/,
      use: ['style-loader', 'css-loader', 'sass-loader']
    },{
      test: /\.styl$/,
      use: ['style-loader', 'css-loader', 'stylus-loader']
    },{
      test: /\.(png|svg|webp|gif|jpe?g)$/,
      type: 'asset',
      parse: {
        dataUrlCondition: {
          maxSize: 10 * 1024
        }
      },
      generator: {
        filename: '/static/image/[hash:10][ext][query]'
      }
    },{
      test: /\.(ttf|woff2?|avi|mp3|mp4)$/,
      type: 'asset/resource',
      generator: {
        filename: '/static/media/[hash:10][ext][query]'
      }
    },{
        test: /\.js$/,
        excludes: 'node_module',
        loader: 'babel-loader'
    }]
  },
  plugins: [
    new ESLintWebpackPlugin({
      context: path.resolve(__dirname, 'src')
    }),
    new HTMLWebpackPlugin({
      // 模板:以public/index.html文件创建新的html文件
      // 新的html特点:1、结构和原来一致;2、自动引入打包输出的资源
      template: path.resolve(__dirname, 'public/index.html')
    })
  ],
  // * 开发服务器
  devServer: {
    host: 'localhost', // 启动服务器域名
    port: '8080', // 启动服务器端口号
    open: true // 自动打开浏览器
  },
  mode: 'development'
}

3. 启动指令

npx webpack serve

注意运行指令发生了变化

并且当你使用开发服务器时,所有代码都会在内存中编译打包,并不会输出到 dist 目录下。

开发时我们只关心代码能运行,有效果即可,至于代码被编译成什么样子,我们并不需要知道。

KESHAOYE-知识星球