# 六.resolve 属性的配置

# 1.安装

package.json

{
  "name": "6.resolve",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server --open --mode development"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.4.0",
    "@babel/preset-env": "^7.4.2",
    "babel-loader": "^8.0.5",
    "css-loader": "^2.1.1",
    "html-webpack-plugin": "^3.2.0",
    "style-loader": "^0.23.1",
    "webpack": "^4.29.6",
    "webpack-cli": "^3.3.0",
    "webpack-dev-server": "^3.2.1"
  },
  "dependencies": {
    "bootstrap": "^4.3.1"
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# 2.文件

# 2.1src/index.js

import "bootstrap"
import "./style"
1
2

# 2.2 src/style.css

body {
  background: green;
}
1
2
3

# 2.3 index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>webpac-resolve</title>
  </head>

  <body>
    <button class="btn btn-danger">按钮</button>
  </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13

# 3.配置

webpack.config.js

const path = require("path")
let HtmlWebpackPlugin = require("html-webpack-plugin")

module.exports = {
  mode: "development",
  entry: {
    home: "./src/index.js",
  },
  resolve: {
    modules: [path.resolve("node_modules")],
    extensions: [".js", ".css", ".json", ".vue"],
    mainFields: ["style", "main"],
    // mainFiles: ["index.js"],
    // alias: {
    //   bootstrap: "bootstrap/dist/css/bootstrap.css"
    // }
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.js$/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env"],
          },
        },
      },
    ],
  },
  output: {
    filename: "[name].js",
    path: path.resolve(__dirname, "dist"),
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./index.html",
      filename: "index.html",
    }),
  ],
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

# 4.运行

npm run dev
1

页面按钮和背景都变颜色