I have installed multiple JS libraries with npm and I trying to use them in Symfony views.
<script src="{{ asset('path/to/js.js') }}"></script>
Do I have to install node modules in web directory ? Is it a good practice ?
What's the best way to achieve that ?
I would suggest using Gulp to compile your assets into minified JS/CSS files. It can installed via npm, run from command line and good documentation exists including specifically how to gulp npm installed files.
Here's a sample of my Gulpfile so you can see how to gulp npm files:
var paths = {
admin: {
js: [
'node_modules/jquery/dist/jquery.min.js',
'node_modules/semantic-ui-css/semantic.min.js',
'vendor/sylius/sylius/src/Sylius/Bundle/AdminBundle/Resources/private/js/**',
'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/js/**',
'vendor/sylius/sylius/src/Sylius/Bundle/ShippingBundle/Resources/public/js/**',
'vendor/sylius/sylius/src/Sylius/Bundle/PromotionBundle/Resources/public/js/sylius-promotion.js',
'vendor/sylius/sylius/src/Sylius/Bundle/UserBundle/Resources/public/js/sylius-user.js'
],
sass: [
'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/sass/**',
],
css: [
'node_modules/semantic-ui-css/semantic.min.css'
],
img: [
'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/img/**',
]
},
shop: {
js: [
'node_modules/jquery/dist/jquery.min.js',
'node_modules/semantic-ui-css/semantic.min.js',
'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/js/**',
'vendor/sylius/sylius/src/Sylius/Bundle/ShopBundle/Resources/private/js/**'
],
sass: [
'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/sass/**',
'vendor/sylius/sylius/src/Sylius/Bundle/ShopBundle/Resources/private/scss/**',
],
css: [
'node_modules/semantic-ui-css/semantic.min.css',
'vendor/fortawesome/font-awesome/css/font-awesome.css'
],
fonts: [
'vendor/fortawesome/font-awesome/fonts/**.*'
],
img: [
'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/img/**',
],
app: [
'src/AppBundle/Resources/private/scss/**',
],
appJs: [
'src/AppBundle/Resources/private/js/**',
],
}
};
gulp.task('admin-js', function () {
return gulp.src(paths.admin.js)
.pipe(concat('app.js'))
.pipe(gulpif(env === 'prod', uglify))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(adminRootPath + 'js/'))
;
});