Webpack-dev-server configure for a library

Viewed 472

I have a problem with the webpack dev server in that I cannot seem to test my library as the library seems to be empty in the webbrowser. A simple example:

my src/index.js

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

My 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"
    },  
}

My 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",
}

If I start the dev server with npm run start, the blank page comes up. But the object $ seems to be empty when trying to access it through the console. Looking at the source of the page, the build script seems to have been generated and put neatly in a script-tag.

If I build the package and make html page with script-tag that points to the created file in the dist/ folder, the package just works.

What am I missing here?

1 Answers

It seems a bug of webpack-dev-server. Updated to "webpack-dev-server": "^4.0.0", it works fine.

contentBase is changed to static option, you can find it from the migration guide

E.g.

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"
  }
}

After running npm start, check the library in browser:

enter image description here

Related