【问题标题】:Webpack-dev-server configure for a library为库配置 Webpack-dev-server
【发布时间】:2021-10-13 04:43:28
【问题描述】:

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

我的 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 启动开发服务器,就会出现空白页。但是对象$ 在尝试通过控制台访问它时似乎是空的。查看页面的源代码,构建脚本似乎已经生成并整齐地放在了 script-tag 中。

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

我在这里错过了什么?

【问题讨论】:

    标签: node.js webpack webpack-dev-server


    【解决方案1】:

    这似乎是webpack-dev-server 中的bug。更新到"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后,在浏览器中查看库:

    【讨论】:

    • 是的,这似乎是解决方案
    猜你喜欢
    • 2018-05-18
    • 1970-01-01
    • 2016-07-18
    • 2021-09-23
    • 2019-11-01
    • 2018-12-19
    • 1970-01-01
    • 2016-07-01
    • 2018-02-01
    相关资源
    最近更新 更多