从零开始搭建webpack项目demo

1.创建一个文件夹d3util

2,运行命令npm init -y,会出现package.json 文件

3, 由于我想把它传到github上去,所以我又多运行了一个命令git init,将项目初始化成一个项目(当然这一步不是必须的)

目前的结果是d3util里存在package.json文件和.git文件夹

4,开始安装依赖

a,安装eslint以检查语法和语法规范

npm install eslint eslint-config-enough eslint-loader --save-dev

运行之后

安装的时候可能会出现以下提示

选择"yes", 意思是我们从npm拉取代码的时候,忽略node_modules目录,于是我们拉取的代码就不会包括node_modules目录,所以需要自己运行npm install安装需要的依赖,所安装的依赖是根据package-lock.json文件夹来的。

b,安装webpack, 核心

npm install webpack webpack-cli webpack-dev-server html-webpack-plugin html-loader css-loader style-loader file-loader xml-loader url-loader --save-dev

 c, 安装babel,为了让不支持es6的浏览器能照常运行,把我们写的es6的代码转成es5的。

npm install @babel/core @babel/preset-env babel-loader babel-eslint --save-dev

5,现在我们在项目下创建src文件夹(我们写代码的地方)和dist文件夹(代码打包的地方),在src文件夹下创建index.js,文件内容如下

var div = document.createElement('div')
div.innerHTML = '<b style="color: red">我是一个使用var来声明自己的div,因为我不知到自己现在是否支持es6所以不敢用let</b>'
document.body.appendChild(div)

然后在dist文件夹下创建index.html文件,内容如下

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8"/>
  </head>
  <body>
    <script src="bundle.js"></script>
  </body>
</html>

其中,bundle.js就是我们打包后生成的文件。

6,编写配置文件

在项目根目录下创建配置文件webpack.config.js,最简单的配置就是指定要打包的文件,和打包后生成的文件名及路径,配置如下:

const path = require('path')
module.exports = {
  entry: './src/index.js',  // 入口
  output: { // 输出
    filename: 'bundle.js', // 打包的文件名
    path: path.resolve(__dirname, 'dist') // 打包到哪里,“__dirname”是node.js中的一个全局变量,它指向当前执行脚本所在的目录
  }
}

此时项目的文件目录如下:

然后就可以开始打包了,运行以下命令:

npx webpack

 

这时dist文件夹下多了一个文件bundle.js,打开index.html看到以下结果:

这样一个最简单的webpack项目就搭建完成了。 

7.其他配置

(1)使用npm命令打包,我们可以在package.json里的script配置如下

"scripts": {
    "build": "webpack --config webpack.config.js"
  },

其中--config后面指定配置文件,默认的配置文件是webpack.config.js,所以,上面的配置也可以简化成

"scripts": {
    "build": "webpack"
  },

运行命令npm run build就可以打包了。

(2)为了方便调试,可以在webpack.config.js里配置devtool,如

devtool: 'eval-source-map', // 开发环境方便调试,不要在生产环境使用,否则打包出来的文件会很大

devtool其他配置请参考https://webpack.docschina.org/configuration/devtool/#devtool

(3)创建并启动本地服务器,我们在上面已经安装了webpack-dev-server,接下来在webpack.config.js配置devServer选项

devServer: {
    contentBase: path.resolve(__dirname, 'dist'),
    port: 8089
  }

然后在package.json里script配置如下:

 "scripts": {
    "build": "webpack --config webpack.config.js",
    "dev": "webpack-dev-server --open"
  },

运行命令npm run dev浏览器会自动打开窗口

到这里, webpack.config.js的内容如下:

const path = require('path')
module.exports = {
  devtool: 'eval-source-map', // 开发环境方便调试,不要在生产环境使用,否则打包出来的文件会很大
  entry: './src/index.js',  // 单入口
  // entry: { // 多入口,其中,app是自定义的属性
  //   app: './src/index.js'
  // },
  output: { // 输出
    filename: 'bundle.js', // 打包的文件名单入口
    // filename: '[name].bundle.js', 其中多入口时name是entry的属性,例如上面的app
    path: path.resolve(__dirname, 'dist') // 打包到哪里,“__dirname”是node.js中的一个全局变量,它指向当前执行脚本所在的目录
  },
  devServer: {
    // contentBase: path.resolve(__dirname, 'dist'),
    contentBase: './dist',
    port: 8089
  }
}

 package.json

{
  "name": "d3Util",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack",
    "dev": "webpack-dev-server --open"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.4.3",
    "@babel/preset-env": "^7.4.3",
    "babel-eslint": "^10.0.1",
    "babel-loader": "^8.0.5",
    "css-loader": "^2.1.1",
    "eslint": "^5.16.0",
    "eslint-config-enough": "^0.3.4",
    "eslint-loader": "^2.1.2",
    "file-loader": "^3.0.1",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^3.2.0",
    "style-loader": "^0.23.1",
    "url-loader": "^1.1.2",
    "webpack": "^4.30.0",
    "webpack-cli": "^3.3.1",
    "webpack-dev-server": "^3.3.1",
    "xml-loader": "^1.2.1"
  }
}

(4)loader

在webpack.config.js里的mudule里配置各种loader,比如file-loader(处理上传下载文件),css-loader和style-loader(处理css文件), babel-loader(处理将es6或以上的代码转为es5)

module: {
    rules: [{
      test: /\.css$/,
      use: [
        'style-loader',
        'css-loader'
      ]
    }, {
      test: /\.(png|jpe?g|gif|svg)$/,
      use: [
        'file-loader'
      ]
    }, {
      test: /\.(woff|woff2|eot|ttf|otf)$/,
      use: [
        'file-loader'
      ]
    }, {
      test: /\.(csv|tsv)$/,
      use: [
        'csv-loader',
      ]
    }, {
      test: /\.xml$/,
      use: [
        'xml-loader'
      ]
    }, {
      test: /\.js$/,
      exclude: /(node_modules|bower_components)/,
      use: {
        loader: 'babel-loader'
        // options: {
        //   presets: ['@babel/preset-env']
        // }
      }
    }]

其中,babel-loader的配置一般可以另外创建单独的配置文件.babelrc,目前的配置很简单,如下

 (5)plugins配置

打包时指定模板和清空上一次的打包的文件

我们之前打包时的index.html文件是自己在dist文件夹下手动创建的,现在我们将它删掉,然后在项目根目录下创建一个index.html,如下

<!DOCTYPE html>
<html>
  <head>
    <title>模板</title>
    <meta charset="utf-8"/>
  </head>
  <body>
  </body>
</html>

上面只是一个空的网页,没有引入任何js或css文件,接下来首先安装插件

npm install --save-dev html-webpack-plugin

然后在webpack.config.js里引入

const HtmlWebpackPlugin = require('html-webpack-plugin')

在webpack.config.js的plugins属性里配置

new HtmlWebpackPlugin({
      filename: 'index.html',
      template: `${__dirname}/index.html`
    })

运行命令npm run build就可以看到dist文件下生成了index.html

clean-webpack-plugin使用类似上面,先安装,然后引入,最后实例化。

(6)为不同的环境配置参数

因为项目分为开发环境和生产环境,因此我们要提取相同部分作为2种环境的共同配置,还要创建各自独特的配置文件,首先要安装webpack-merge插件

分别为

webpack.base.conf.js

const path = require("path")
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  entry: "./src/index.js", // 单入口
  // entry: { // 多入口,其中,app是自定义的属性
  //   app: './src/index.js'
  // },
  output: {
    // 输出
    filename: "bundle.js", // 打包的文件名单入口
    // filename: '[name].[chunkhash].js', // 其中多入口时name是entry的属性,例如上面的app,chunkhash是为了diff
    path: path.resolve(__dirname, "dist") // 打包到哪里,“__dirname”是node.js中的一个全局变量,它指向当前执行脚本所在的目录
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: "style-loader"
          },
          {
            loader: "css-loader"
            // options: {
            //   modules: true, // 指定启用css modules
            //   localIdentName: "[name]__[local]--[hash:base64:5]" // 指定css的类名格式
            // }
          },
          {
            loader: "postcss-loader"
          }
        ]
      },
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        use: ["file-loader"]
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        use: ["file-loader"]
      },
      {
        test: /\.(csv|tsv)$/,
        use: ["csv-loader"]
      },
      {
        test: /\.xml$/,
        use: ["xml-loader"]
      },
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/, // 排除node_modules/bower_components目录下的文件,include则是包含
        use: {
          loader: "babel-loader"
          // options: {
          //   presets: ['@babel/preset-env']
          // }
        }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html'
    }),
    new CleanWebpackPlugin() 
  ]
};

webpack.dev.conf.js

// const path = require('path')
const merge = require('webpack-merge')
const webpack = require("webpack")
const baseConfig = require('./webpack.base.conf')
module.exports = merge(baseConfig, {
  devtool: "eval-source-map", // 开发环境方便调试,不要在生产环境使用,否则打包出来的文件会很大
  mode: 'development',
  devServer: {
    // contentBase: path.resolve(__dirname, 'dist'),
    contentBase: "./dist",
    port: 8089,
    hot: true // 开启HMR
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin() // 热模块替换    
  ]
})

 

webpack.prod.conf.js

const merge = require('webpack-merge')
const webpack = require("webpack")
const baseConfig = require('./webpack.base.conf')
module.exports = merge(baseConfig, {
  mode: "production",
  plugins: [
    new webpack.BannerPlugin('版权所有,翻版必究')  
  ]
})

demo下载:https://github.com/fanqingyun/d3Util.git

参考链接:https://segmentfault.com/a/1190000007914129

中文文档: https://webpack.docschina.org/concepts/

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值