webpack使用攻略

安装相关包

tips:
网络不好,请使用淘宝镜像安装

1
npm install -g cnpm --registry=https://registry.npm.taobao.org

开始安装

webpack模块

1
npm install webpack webpack-cli webpack-dev-server --save-dev

JavaScript模块

tips:
这里由于版本兼容性问题,babel-loader我安装的版本是7.1.5

  • babel-core 和 babel-loader 充当的就是翻译官的角色,用来解析代码中的js代码
  • babel-preset-env 和 babel-preset-stage-0 是告诉翻译官,要把js解析成 es5 还是 es7
1
npm install babel-core babel-loader@7.1.5 babel-preset-env babel-preset-stage-0 --save-dev

css模块

tips: 要解析什么类型的css文件就安装对应的loader即可

  • css-loader 解析css代码
  • style-loader 将css解析的代码以style标签引入到页面中
  • less 和 less-loader 解析less
1
npm install style-loader css-loader less less-loader --save-dev

图片模块

tips: url-loader 依赖于 file-loader
所以两个都需要安装

1
npm install file-loader url-loader --save-dev

html模块

1
2
3
4
5
6
7
npm install html-webpack-plugin --save-dev
```

#### vue模块

> tips:
> 这里我是用vue写页面,所以安装vue相关依赖

npm install vue vue-cli vue-loader vue-template-compiler

1
2
3
4
5


### 配置文件

#### webpack.config.js

let path = require('path');
let HtmlWebpackPlugin = require('html-webpack-plugin');
let VueLoaderPlugin = require('vue-loader/lib/plugin');
module.exports = {
  mode: 'development',
  entry: './src/main.js',
  output: {
      filename: 'bundle.js',
      path: path.resolve('./dist')
  },
  module: {
      rules: [
          {test: /\.js$/, use: 'babel-loader', exclude: /node_module/},
          {test: /\.css$/, use: ['style-loader', 'css-loader']},
          {test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader']},
          {test: /\.(jpg|png|gif|jpeg)/, use: 'url-loader?limit=8192'},
          {test:/\.vue$/, use: 'vue-loader'}
      ]
  },
  plugins: [
      new HtmlWebpackPlugin({
          template: './src/index.html'
      }),
      new VueLoaderPlugin()
  ]
};
1
2

#### npm init 生成的package.json文件
{
  "name": "webpack-vue",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack",
    "dev": "webpack-dev-server"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.5",
    "babel-preset-env": "^1.7.0",
    "babel-preset-stage-0": "^6.24.1",
    "css-loader": "^1.0.0",
    "file-loader": "^2.0.0",
    "html-webpack-plugin": "^3.2.0",
    "less": "^3.8.1",
    "less-loader": "^4.1.0",
    "style-loader": "^0.23.0",
    "url-loader": "^1.1.1",
    "vue-loader": "^15.4.1",
    "vue-template-compiler": "^2.5.17",
    "webpack": "^4.17.2",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.7"
  }
}
1
2

#### js配置 .babelrc文件
{
  "presets": ["env", "stage-0"]
}

`