我在 widget.js 中有一个名为“Widget”的类。它有以下代码:
export class Widget {
constructor(elem,data) {
this.elem = elem;
this.data = data;
}
init(){
......
}
}
然后我有一个index.js文件,其中包含以下代码:
import { Widget as defaultExport } from './lib/widget';
export default defaultExport;
使用Webpack,此index.js 文件链接到HTML 文件index.html。现在,我的 HTML 页面中有一个脚本标记,它尝试导入 Widget 类并调用该类中的 init 函数。我一直在尝试做以下事情
<script>
$(document).ready(function() {
console.log("In document ready" );
let instance = new Widget(element,"data");
instance.init();
});
</script>
我的动机是通过index.js导入HTML文件中的Widget类,并调用init方法。当我尝试执行此操作时,我收到“未捕获的参考错误:未找到小部件”。我尝试使用“
new defaultExport
”而不是new Widget
,这也不起作用。我还尝试了 "import Widget from 'index.js'"
,这给了我“未捕获的语法错误:意外的标识符”。我尝试将脚本类型设置为“模块”,但它不执行 jquery 块(请参阅以下块):
<script type="module">
import Widget from './src/index'
$(document).ready(function() {
console.log("In document ready" );
let instance = new Widget(element,"data");
instance.init();
});
</script>
你能帮我解决这个问题吗
编辑:我注意到在开发人员控制台的元素部分中,index.js 文件的脚本导入标签被添加到 HTML 文件中的标签之后(请参见下文)。这可能是这个参考错误的原因吗?
<html>
<body>
<script>
..........
</script>
<script src = '/index.js'></script>
</body>
</html>
您需要使用output.library配置。
输出一个公开入口点导出的库。
例如
项目结构:
$ tree -L 2 -I node_modules
.
├── dist
│ ├── index.html
│ └── widget.js
├── package-lock.json
├── package.json
├── src
│ ├── index.html
│ ├── index.js
│ └── widget.js
└── webpack.config.js
2 directories, 8 files
src/index.js
:
import { Widget as defaultExport } from './widget';
export default defaultExport;
src/widget.js
:
export class Widget {
constructor(elem, data) {
this.elem = elem;
this.data = data;
}
init() {
console.log('Initialize widget success');
}
}
src/index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="widget"></div>
<script>
window.addEventListener('DOMContentLoaded', () => {
console.log("In document ready" );
const element = document.getElementById('widget');
let instance = new Widget(element, "data");
instance.init();
})
</script>
</body>
</html>
webpack.config.js
:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: 'widget.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
library: {
name: 'Widget',
type: 'window',
export: 'default',
},
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
minify: false,
}),
],
};
构建日志:
> webpack
asset index.html 573 bytes [compared for emit]
asset widget.js 338 bytes [emitted] [minimized] (name: main)
runtime modules 396 bytes 2 modules
orphan modules 151 bytes [orphan] 1 module
./src/index.js + 1 modules 234 bytes [built] [code generated]
webpack 5.88.2 compiled successfully in 193 ms
输出
dist/index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script defer src="widget.js"></script></head>
<body>
<div id="widget"></div>
<script>
window.addEventListener('DOMContentLoaded', () => {
console.log("In document ready" );
const element = document.getElementById('widget');
let instance = new Widget(element, "data");
instance.init();
})
</script>
</body>
</html>
dist/widget.js
:
(() => {
'use strict';
var e = {
d: (t, o) => {
for (var i in o) e.o(o, i) && !e.o(t, i) && Object.defineProperty(t, i, { enumerable: !0, get: o[i] });
},
o: (e, t) => Object.prototype.hasOwnProperty.call(e, t),
},
t = {};
e.d(t, { default: () => o });
const o = class {
constructor(e, t) {
(this.elem = e), (this.data = t);
}
init() {
console.log('Initialize widget success');
}
};
window.Widget = t.default;
})();
package.json
:
{
"version": "1.0.0",
"scripts": {
"build": "webpack",
"start": "http-server ./dist"
},
"devDependencies": {
"html-webpack-plugin": "^5.5.3",
"http-server": "^14.1.1",
"webpack": "^5.80.0",
"webpack-cli": "^5.0.2"
}
}
启动 HTTP 服务器来提供
dist/index.html
文件。浏览器控制台日志:
In document ready
Initialize widget success