Is there an injector like grunt-wiredep that works

2019-03-11 23:23发布

问题:

Most packages nowadays are available in both NPM and Bower. I have to have NPM around, but I'd like cut Bower out of the loop on my project.

I'm currently relying on grunt-wiredep to create <script> includes in my index.html. This tool looks at all of the Bower configs to pull all the necessary js and css files into my index.html for me.

Is there a tool that will do the same for NPM dependencies?

回答1:

You would be able to do that using a module bundler like Browserify or Webpack.

For getting started with Browserify , you will need to first install it via NPM globally

npm install -g browserify

Then in your project , get the frontend library you want to include , like for example the angular library

npm install --save angular

Now you will need to use require() to make Browserify aware of the dependencies that it needs to fetch for the project to work (In case of Angular app, where you define the main module , add this first line)

var angular = require('angular');

angular
  .module('autocompleteDemo', [])
  .controller('DemoCtrl', DemoCtrl);

For setting up the grunt-browserify task , first install it in the project

npm install grunt-browserify --save-dev

and configure the task as follows

browserify: {
    main: {
        src: 'entry.js',
        dest: 'bundle.js'
    }
 }

Lastly in your index.html , you will need to add markup for the bundle.js script

<script src="bundle.js"></script>

Example code can be found at https://github.com/pra85/grunt-browserify-example