首页 > 解决方案 > 在 Laravel 应用程序中使用 NPM 包时遇到问题

问题描述

我已经使用 Laravel 多年了,但直到现在我才在我的 Laravel 应用程序中使用过 NPM 包。我使用 Laravel Valet 作为我的开发环境。

我正在尝试使用一个与remove.bg js 包接口的简单包,但经过数小时尝试不同的事情后,我无法让它工作。

这是我所做的:

  1. 通过npm install remove.bg.
  2. 该软件包抱怨它找不到它所依赖的模块(unirest、http 等),所以我通过安装它们npm install甚至添加了这些后备,因为它抱怨 Webpack 5 和 polyfill:

我的 webpack.mix.js 文件:

mix.webpackConfig({
    resolve: {
        fallback: {
            fs: require.resolve('browserify-fs'),
            crypto: require.resolve('crypto-browserify'),
            stream: require.resolve('stream'),
            http: require.resolve('stream-http'),
            https: require.resolve('https-browserify'),
            path: require.resolve('path-browserify'),
            zlib: require.resolve('browserify-zlib'),
        },
    },
});
  1. 在我的resources/js/bootstrap.js我补充说:
import { RemoveBgResult, RemoveBgError, removeBackgroundFromImageBase64 } from 'remove.bg';
window.Removebg = require('remove.bg');
  1. 运行npm run dev没有错误。
  2. 包含<script src="{{ mix('/js/app.js') }}"></script>在我的刀片模板中。

但是,当我查看我的页面时,我在控制台中收到以下错误:

app.js:137237 Uncaught TypeError: Cannot read properties of undefined (reading 'prototype')
    at Object.inherits (app.js:137237)
    at Object../node_modules/browserify-zlib/lib/index.js (app.js:28688)
    at __webpack_require__ (app.js:139212)
    at Object../node_modules/unirest/index.js (app.js:131192)
    at __webpack_require__ (app.js:139212)
    at Object../node_modules/remove.bg/dist/index.js (app.js:108502)
    at __webpack_require__ (app.js:139212)
    at Module../resources/js/bootstrap.js (app.js:16242)
    at __webpack_require__ (app.js:139212)
    at Object../resources/js/app.js (app.js:16230)

我难住了。我在这里做错了什么?

标签: laravelnpmwebpacklaravel-mix

解决方案


您可能会错过 webpack.mix.js 文件

添加这一行

mix.js('resources/js/app.js', 'public/js');

推荐阅读