简体   繁体   English

webpack5 output.library 无法导入

[英]webpack5 output.library can't import

problem问题

I use <script> to import index.bundle.js which bundled by webpack5 in a HTML.But I failed.我使用<script>在 HTML 中导入由 webpack5 捆绑的 index.bundle.js。但我失败了。

option file选项文件

//webpack.config.js
const path = require('path');

module.exports = {
    entry: {
        index: '/src/index.ts'
    },
    output: {
        path: path.join(__dirname, 'dist'),
        library: 'test',
        libraryTarget: 'umd',
    }
}

//index.ts
export function mount() {
    console.log("mount")
}
//html
 <script src="dist/index.js"></script>
    <script>
        console.log(window.mount());
    </script>

error错误

Uncaught TypeError: window.mount is not a function

code代码

I have checked the official documentation .But I can't find answer.我已经检查了官方文档。但我找不到答案。 my code is here我的代码在这里

use利用

yarn 
npm run build 

then open the index.html,you can find the error.然后打开index.html,就可以找到错误了。

Using the config you currently have (which is not putting them on the root window object), you can access your functions with window.test.mount() , because that's what you have in library in the webpack config.使用您当前拥有的配置(不是将它们放在根window对象上),您可以使用window.test.mount()访问您的函数,因为这就是您在 Z424516CA53B4AD4BEF37ED04F879 config.A8879 library中的内容

If you want to put these functions on the root window object, you'd need to do that in your code:如果要将这些函数放在根 window object 上,则需要在代码中执行此操作:

export function mount() {
    console.log("mount")
}
window.mount = mount

// etc.

You can see this by checking out dist/index.js (dropping it in the Prettier tool online can clean it up enough to be readable).您可以通过查看dist/index.js来查看这一点(将其放入Prettier 在线工具中可以将其清理得足够可读)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM