【问题标题】:Functions are not available in webpack bundle功能在 webpack 包中不可用
【发布时间】:2020-09-08 11:34:43
【问题描述】:

我正在处理Arrow 项目,我正处于使用Webpack 创建Bundle 文件的阶段。

我将modules 分组到一个文件夹中。对于每个文件夹,我都有index.js 导出所有模块。

另外,我有全局 index.js 可以像这样导入所有 index.js

import * as Has from "./scripts/array/has"
import * as  Math from "./scripts/array/math"
import * as  Arrow from "./scripts/array"
export { Has, Math, Arrow }

现在,我想从这个全局 index.js 创建我的包。

我的Webpack 配置如下:

const path = require("path")
const { CleanWebpackPlugin } = require("clean-webpack-plugin")

module.exports = {
    mode: "development",
    entry: {
        arrow: "./src/1.x.x/index",
    },
    plugins: [
        new CleanWebpackPlugin({ cleanStaleWebpackAssets: false }),
    ],
    devtool: 'inline-source-map',
    devServer: {
        contentBase: './build',
    },
    output: {
        filename: "[name]-alpha.js",
        path: path.resolve(__dirname, 'build'),
    },
    optimization: {
        splitChunks: {
            chunks: 'all',
        },
    },
}

问题是当我尝试从 build 导入我的函数时,这些函数没有出现在 Autocomplete 中,并且我收到了这些函数是 @987654332 的错误@!

我只有___esModule

import { __esModule } from "./arrow-alpha"

我想让开发者使用和导入像example这样的函数

import {omit} from "arrow" // arrow is the bundled file

const frameworks = ["react", "vue", "ember", "angular"];
const withoutAngular = omit(frameworks,"angular");

console.log(withoutAngular); // ["react", "vue", "ember"]

我在此步骤中阻止了几天,但我无法弄清楚问题所在。

【问题讨论】:

    标签: javascript webpack


    【解决方案1】:

    听起来您希望使用webpack 将代码导出为库。为此,您应该将库模块导出为umd,它可以用于后端/客户端,以便 IDE 也可以理解您导出的内容。只需在您的webpack.config.js 中添加以下配置:

    output: {
      libraryTarget: 'umd', // style for your library
      library: 'yourLibName', // if you keen to have a name for library
      // ...
    },
    

    注意:这仅在您将webpack 样式代码传递给cjs 时有效,否则它将转换为您无法相应导出的和声模块(如esm模块)

    为了确保babel 将您的esm 模块转换为commonjs,您必须将modules 设置为commonjs,如下所示:

    babel.config.js.babelrc

    [
      "@babel/preset-env",
      {
        "modules": "commonjs",
      }
    ]
    

    【讨论】:

    • 我仍然只收到__esModule
    • 您可以查看帖子中的链接。这是捆绑文件:bundle
    • 您似乎没有再次运行构建。您可以尝试重新构建吗?
    • 我生成了新包,请看一下。谢谢。
    • 啊,我明白了。看起来如果您将esm 输入到webpack,它会创建IDE 不理解的harmony 模块。但如果你先使用babel 转换cjs,然后传递给webpack,那么它应该可以工作。
    【解决方案2】:

    在配置下方添加。在将脚本添加到 index.html 页面时,将弹出您的最终捆绑包,以便作为 Window.Arrow 访问

    output: {
            filename: "[name]-alpha.js",
            path: path.resolve(__dirname, 'build'),
            library: 'Arrow',
            libraryTarget: 'var'
        },
    

    和你在 src 文件夹中的 index.js 页面是一样的

    module.exports = require('./scripts/array');
    

    【讨论】:

    猜你喜欢
    • 2017-07-01
    • 2017-07-25
    • 1970-01-01
    • 2018-12-15
    • 2019-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多