12. 路径处理 环境分离

108 阅读1分钟

output.publicPath

作用: 指定打包后的 index.html 文件引用的一个基本路径
打包之后的文件路径的组成 域名 + output.publicPath + bundle.js
默认值:空字符串,所以打包后引入 js 文件时,路径是 bundle.js。

  output: {
    filename: "bundle.js",
    // 必须是一个绝对路径
    path: path.resolve(__dirname, "./build"),
    publicPath: ""
  }
<!-- 引入的js路径 http://localhost:8080/bundle.js -->
<script defer src="bundle.js"></script>
  output: {
    filename: "bundle.js",
    // 必须是一个绝对路径
    path: path.resolve(__dirname, "./build"),
    publicPath: "./"
  }
<script defer="defer" src="./bundle.js"></script>

devServer.publicPath

devServer 中的 publicPath 属性,指定本地服务所在的文件夹。 默认值是 /,直接访问端口即可访问其中的资源 http://localhost:8080 ,如果将其设置为了 /abc,那么我们需要通过 http://localhost:8080/abc 才能访问到对应的打包后的资源。

环境分离

webpack.common.js

const path = require("path");
module.exports = {
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "./dist"),
  },
};

开发环境配置 webpack.dev.js

const { merge } = require("webpack-merge");
const commonConfig = require("./webpack.common.js");
const config = {
  mode: "development",
  devServer:{

  }
};
module.exports = {
  ...merge(commonConfig, config),
};

生产环境配置 webpack.prod.js

const { merge } = require("webpack-merge");
const commonConfig = require("./webpack.common.js");
const config = {
  mode: "production",
};
module.exports = {
  ...merge(commonConfig, config),
};

package.json

  "scripts": {
    "build": "npx webpack --config ./webpack.prod.js",
    "serve": "webpack serve --config ./webpack.dev.js"
  }