我有一个问题与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启动开发服务器,就会出现空白页面。但是当试图通过控制台访问对象$时,它似乎是空的。查看页面的源代码,构建脚本似乎已经生成并整齐地放在一个script-tag中。
如果我构建包并使用script-tag制作html页面,并指向dist/文件夹中创建的文件,包就能正常工作。
这里我漏掉了什么?
发布于 2021-08-25 05:52:27
它似乎是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后,在浏览器中检查库:

https://stackoverflow.com/questions/68712902
复制相似问题