Webpack-dev-server 为库配置

Webpack-dev-server configure for a library

我的 webpack 开发服务器有问题,因为我似乎无法测试我的库,因为该库在网络浏览器中似乎是空的。一个简单的例子:

我的src/index.js

function test() { console.log("test"); }
export { test }

我的package.json

{
    "name": "testpackage",
    "version": "0.0.1",
    "description": "",
    "module": "dist/index_bundle.js",
    "scripts": {
        "build": "webpack",
        "start": "webpack serve --open",
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "html-webpack-plugin": "^5.3.2",
        "webpack": "^5.48.0",
        "webpack-cli": "^4.7.2",
        "webpack-dev-server": "^3.11.2"
    },  
}

我的webpack.config.js

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

module.exports = {
    entry: path.resolve(__dirname, "src/index.js"),
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "index_bundle.js",
        library: "$",
        libraryTarget: "umd",
    },
    devtool: 'source-map',
    devServer: {
        contentBase: './dist',
        port: 9000
    },
      plugins: [
      new HtmlWebpackPlugin({
      title: 'Test',
    }),
  ],
    mode: "development",
}

如果我用 npm run start 启动开发服务器,就会出现空白页面。但是当试图通过控制台访问它时,对象 $ 似乎是空的。查看页面的源代码,构建脚本似乎已经生成并整齐地放在脚本标签中。

如果我构建包并使用指向 dist/ 文件夹中创建的文件的脚本标签创建 html 页面,包就可以正常工作。

我在这里错过了什么?

似乎是 webpack-dev-serverbug。更新到 "webpack-dev-server": "^4.0.0",它工作正常。

contentBase改为static选项,可以从migration guide

中找到

例如

src/index.js

function test() {
  console.log("test");
}
export { test };

webpack.config.js:

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

module.exports = {
  entry: path.resolve(__dirname, "src/index.js"),
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "index_bundle.js",
    library: {
      name: "$",
      type: "umd",
    },
  },
  devtool: "source-map",
  devServer: {
    static: "./dist",
    port: 9000,
  },
  plugins: [new HtmlWebpackPlugin({ title: "Test" })],
  mode: "development",
};

package.json:

{
  "name": "68712902",
  "main": "dist/index_bundle.js",
  "scripts": {
    "build": "webpack",
    "start": "webpack serve --open"
  },
  "devDependencies": {
    "html-webpack-plugin": "^5.3.2",
    "webpack": "^5.51.1",
    "webpack-cli": "^4.8.0",
    "webpack-dev-server": "^4.0.0"
  }
}

运行npm start后,在浏览器中查看库: