我正在构建一个使用ES6模块并包含类的库。如果不是捆绑,我只是将package.json“main”指向源代码,一切都很好!我可以将库导入到应用程序中,它工作得很好。
一旦我使用WebPack捆绑应用程序并将“main”指向打包的bundle,什么都不起作用,我只能抓我头上剩下的一点头发。
以下是我得到的错误:
notablet__WEBPACK_IMPORTED_MODULE_3__.Notablet不是构造函数
这是我的package.json
{
"name": "notablet",
"version": "4.7.0",
"main": "lib/index.js",
"type": "module",
"scripts": {
"test": "npx mocha ./test/**/*.test.js",
"coverage": "c8 --reporter=text --all npm run test",
"build": "webpack --config webpack.config.js"
},
"license": "MIT",
"devDependencies": {
"c8": "^7.12.0",
"chai": "^4.3.6",
"clean-webpack-plugin": "^4.0.0",
"css-loader": "^6.7.1",
"jsdom": "^20.0.0",
"mocha": "^10.0.0",
"sinon": "^14.0.0",
"style-loader": "^3.3.1",
"webpack": "^5.73.0",
"webpack-cli": "^4.10.0"
}
}
下面是我的webpack.config.js:
import path from 'path';
import {fileURLToPath} from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const config = {
mode: 'development',
devtool: false,
entry: './src/Notablet.js',
output: {
path: path.resolve(__dirname, 'lib'),
filename: "index.js",
library: "notablet"
},
module: {
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
],
}
};
export default config;
注意.我确实把上面的“模式”从“开发”改成了“生产”,但是捆绑使用后得到了同样的错误。
以下是我的Notablet.js文件的相关部分:
import { Queue } from './Queue.js';
// Themes
import style from './style.css'; // assert { type: "css" };
import light from './theme/light.css';
import dark from './theme/dark.css';
import elegant from './theme/elegant.css';
import fantasy from './theme/fantasy.css';
import robot from './theme/robot.css';
export class Notablet {
constructor(conf = {}, queue = new Queue()) {
this.queue = queue;
var config = {
backgroundColor: 'black',
color: '#ffffff',
theme : 'light'
};
this.config = {...config, ...conf};
this.loadTheme();
}
/**
* Loads the theme identified in the configuration object along with the base stylesheet
*/
loadTheme() {
var theme = this.getTheme(this.config.theme)
var sheet = new CSSStyleSheet();
sheet.replace(theme);
var baseSheet = new CSSStyleSheet();
baseSheet.replace(style);
document.adoptedStyleSheets = [baseSheet, sheet];
}
getTheme(theme = 'light') {
var ret = light;
switch(theme) {
case "dark":
ret = dark;
break;
case "elegant":
ret = elegant;
break;
case "fantasy":
ret = fantasy;
break;
case "robot":
ret = robot;
break;
}
return ret;
}
}
当我调用let nt = new Notablet()
时,似乎在应用程序中抛出了错误
Notablet在ES6中似乎是一个有效的类,它有一个构造函数。我的假设是Webpack需要以某种方式配置为处理ES6模块,但我明白我只需要将我的package.json“type”更改为“module”。
任何帮助都非常感谢!
1条答案
按热度按时间djp7away1#
不知道这是否仍然相关,但这里是webpack的官方文档https://webpack.js.org/configuration/output/
TLDR:尝试将
libraryTarget: 'umd',
添加到输出选项中