maxkart
maxkart

Reputation: 667

Javascript project structure for dev and production using npm and grunt

I am trying to structure javascript files in a project. I have used NPM to manage the modules and planning to use Grunt to concatenate and compress the js and css files for deployment.

I am currently using the following structure

-[project root]   
-- [node modules] :packages such as requirejs, jquery, semantic-ui etc using npm  

--[war]  
---[Dev]   
----[css] multiple css files from modules (Question 2:?)  
----[js] multiple js files from modeuls (Question 2:?)

- Gruntfile.js :for concatenate and compress    
---[Production] -   
----[css]:This is where the compressed and concatenated css files are kept  
----[js] :This is where the compressed and concatenated js files are kept  

Question 1: Is the above approach to structure the project correct ? Any other recommendations which allows to manage the packages, dev and production files.

Question 2: Can NPM or another tool allows me to pick up the js and css files from the [node modules] folder and place them to (dev>>css or dev>>js) folder ? If am doing this manually how do I track the versions ? Seems like I am missing something here, there must be a better solution.

Suggestions/recommendations/comments are much appreciated.

Thanks

Upvotes: 0

Views: 192

Answers (1)

Pete TNT
Pete TNT

Reputation: 8403

The question is a bit too wide for SO format, but in general your structure is good. Instead of copying files from node_modules, you have your own JavaScript files under js and you import/require them to your own files.

//foo.js
//ES6 style imports
import {Foo as Bar} from "biz";

//Common JS style requires
var Bar = require("biz");

//AMD style requires
require(["biz"], function (Bar) {

If you want to use your node_modules in a browser, you'll want to bundle them using Browserify, Webpack, Rollup or similar. To automate this, you can easily use Grunt tasks such as grunt-browserify together with grunt-watch.

Same applies for your CSS files: You store your own files under css and if you need CSS files from node_modules you can import them to your own files: if you are using some preprocessor (such as SASS or LESS), the preprocessors usually inline your imports when building the .css-file. If you are just using plain .css files, see grunt-css-import for example.

Upvotes: 1

Related Questions