2016-04-28 17 views
1

browserify-rails documentation指出「默認情況下,只有/ app和/ node_modules中的文件已被瀏覽」。但是,當我從npmjs安裝包並嘗試在application.js中引用它時,應用程序找不到它。有沒有辦法使用browserify-rails在我的Rails應用程序中要求node_modules?Rails - 使用browserify rails訪問application.js中的node_modules

# command line 
$ npm intl-tel-input --save 

# application.js.coffee 
#= require intlTelInput 

# throws error 
Error: Cannot find module 'intlTelInput' from '.../app/assets/javascripts' 

回答

2

當您使用#= require ...那麼它依然採用滑軌資產管道,並且將無法訪問NPM模塊。你應該做的,而不是爲使用

var intlTelInput = require("intlTelInput"); 

這browserify將解析,並從NPM模塊找到。如果你已經包含了ES6解析器(比如babelify),那麼你甚至可以這樣做:

import intlTelInput from "intlTelInput" 
+0

感謝您的快速響應!這讓我更近了一步,因爲它似乎加載文件,但它似乎並沒有將其添加爲jQuery擴展名:'$(...)。intlTelInput不是一個函數'聽起來像也許我需要處理一些另一種方式? – steel

+0

如果你想在你的browserify模塊中使用jQuery,那麼就需要用同樣的方法。確保你在'package.json'中添加了jQuery作爲依賴項,然後你可以在需要時添加'var $ = require('jQuery');'' – DanneManne