jquery 使用Webpack时未捕获的引用错误(HTML Webpack插件)

5lhxktic  于 2023-08-04  发布在  jQuery
关注(0)|答案(1)|浏览(119)

我在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'",它给了我“Uncaught SyntaxError:意外的标识符“”。我尝试将脚本类型设置为“module”,它不执行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>


你能帮我解决这个问题吗
编辑:我注意到在开发者控制台的Elements部分,index.js文件的脚本导入标签被添加到HTML文件中的标签之后(请参见下文)。这可能是这个引用错误的原因吗?

<html>
<body>
<script>
..........
</script>
<script src = '/index.js'></script>
</body>
</html>

6jygbczu

6jygbczu1#

您需要使用输出.库配置。
输出一个库,公开入口点的导出。
例如:
项目结构:

$ 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

相关问题