需要 laravel 组合中的 npm 包?

Requiring a npm package in laravel mix?

我已经在网上看到这个问题被回答过几次了。但是,我只是没有让它工作。希望能帮到你。

我正在使用 Laravel 5.5 和 Laravel 混合。我不想手动将一些我需要的 js 文件加载到特定目录中,而是想通过 npm 安装软件包并在 laravel mix.

中要求它们

开箱即用 bootstrap。我将 3.3.7 版本换成了 4.0.0 alpha6。

npm install bootstrap-v4-dev -D

然后在resources/assets/js/bootstrap.js我把它改成这样

window._ = require('lodash');

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

try {
    window.$ = window.jQuery = require('jquery');

    require('bootstrap-v4-dev');
} catch (e) {}

并且有效。我可以 运行 npm run dev 就好了。现在,我想用另一个 npm 包做同样的事情。所以我 npm install now-ui-kit -D 我的 package.json 现在看起来像这样

{
  "private": true,
  "scripts": {
    "dev": "npm run development",
    "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch-poll": "npm run watch -- --watch-poll",
    "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
    "prod": "npm run production",
    "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
  },
  "devDependencies": {
    "axios": "^0.16.2",
    "bootstrap-v4-dev": "^4.0.0-alpha.6",
    "cross-env": "^5.0.1",
    "jquery": "^3.1.1",
    "laravel-mix": "^1.0",
    "lodash": "^4.17.4",
    "now-ui-kit": "^1.0.1",
    "popper.js": "^1.11.1",
    "vue": "^2.1.10"
  },
  "dependencies": {
    "now-ui-kit": "^1.0.1"
  }
}

然后在 bootstrap.js 文件中,我添加 require('now-ui-kit');,但是现在当我尝试编译时,出现以下错误:

ERROR in ./resources/assets/js/bootstrap.js
Module not found: Error: Can't resolve 'now-ui-kit' in '/home/vagrant/code/user/resources/assets/js'
 @ ./resources/assets/js/bootstrap.js 15:0-21
 @ ./resources/assets/js/app.js
 @ multi ./resources/assets/js/app.js

我也试过将 require('now-ui-kit'); 放在 app.js 甚至 webpack.mix.js..

没有任何效果,我真的不明白我做错了什么。有人可以帮忙吗?

按照以下步骤操作:

  • 安装 npm 包让安装 jQuery npm i jquery.
  • 创建一个 .js 文件说 resources/js/package.js
  • 现在打开webpack.mix.jswebpack.mix.js
  • 中添加package.js

mix.js([
      'resources/js/package.js',
      'resources/js/otherJsFile.js'
  ], 'js/app.js').extract([
    // Extract packages from node_modules to vendor.js
    'jquery'
])

resources/js/package.js中写下:

import $ from 'jquery';

最终在 .blade 文件上使用 js/vendor.jsjs/app.js

现在您可以jQuery在您的网站上从node_modules

导入