Webpack启动项目流程

2019-09-20 测试有效

以yarn为例:

  1. yarn init -y
  2. yarn add webpack webpack-cli webpack-dev-server -D
  3. yarn add css-loader style-loader sass-loader -D
  4. yarn add file-loader html-loader -D
  5. yarn add html-webpack-plugin clean-webpack-plugin -D
  6. yarn add node-sass -D

需要安装的包

模块:

  • webpack
  • webpack-cli
  • webpack-dev-server
  • node-sass

loader:

  • style-loader 用作fallback
  • css-loader
  • sass-loader
  • file-loader 解决js、css引入图片问题
  • html-loader 解决html引入图片问题

plugins:

  • html-webpack-plugin 将html也打包
  • clean-webpack-plugin

webpack.config.js

const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const {CleanWebpackPlugin} = require('clean-webpack-plugin')

module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    filename: '[hash:4]-bundle.js',
    path: path.join(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: ['style-loader', 'css-loader', 'sass-loader']
      },
      {
        test: /\.(jpg|png|gif|svg|webp)$/,
        use: ['file-loader']
      },
      {
        test: /\.(html|ejs)$/,
        use: ['html-loader']
      }
    ]
  },
  devServer: {
    contentBase: path.join(__dirname, 'dist'),
    port: 3000,
    historyApiFallback: true,
    overlay: true,
    hot: true
  },
  devtool: 'inline-source-map',
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'src', 'main.html')
    })
  ]
}

package.json

在package.json添加以下代码:

"scripts": {
    "build": "webpack",
    "build:prod": "webpack --production",
    "start": "webpack-dev-server"
  }

index.js

在入口文件index.js中import来引入样式、JS文件:

import './scss/main.scss'
import random from './js/random'

总结

本文内容是webpack目前版本(v4.40.2)下可用的、初级的配置,可应对简单的需求,另外也实现了样式的热加载。

你可能感兴趣的:(Webpack启动项目流程)