setup • Front end NodeJS stack in a new project - martindubenet/wed-dev-design GitHub Wiki
Requires NodeJS (and the included npm)
Compile SASS with npm
1.Note that this first method rely on
node-sass
which is built on top of the depricated LibSass. Therefor it would be wize to use the second method (#2a and #2b below)
Initiate npm using CLI
npm init
npm install node-sass clean-css-cli --save-dev
mkdir dist dist/css dist/img dist/img/logo dist/js src src/sass vendor && cd src/sass
touch theme.scss _theme-layout.scss _theme-mixins.scss _theme-variables.scss && cd ../../
Expected structure from the root of your project:
/dist/css/
/dist/img/logo/
/dist/js/
/src/sass/_theme-layout.scss
/src/sass/_theme-mixins.scss
/src/sass/_theme-variables.scss
/src/sass/theme.scss
/vendor/
/package.json
Copy/Paste the 4 following scripts within your existing "scripts":{}
block. If you already have content within your script just add a coma ,
at the end before pasting those lines under the existing ones.
/package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch-sass": "node-sass --watch --output-style expanded --source-map true --source-map-contents true src/sass/theme.scss dist/css/theme.css",
"_compile-sass": "node-sass --output-style expanded --source-map true --source-map-contents true src/sass/theme.scss dist/css/theme.css",
"_minify-css": "cleancss -O1 --format breaksWith=lf --source-map --source-map-inline-sources --output dist/css/theme.min.css dist/css/theme.css",
"commit-sass": "npm run _compile-sass && npm run _minify-css"
}
$ command |
description |
---|---|
npm run watch-sass | Everytime you save an edited .scss file, this script recompile all Sass files to (unminified) CSS. |
npm run commit-sass | Run this script BEFORE comitting your changes to git. This script is responsible for both compiling the SCSS into CSS output (_compile-sass ) AND minifying it for optimal use (_minify-css ). |
Press «
[Ctrl]+[Z]
» to exit the--watch
script in your Terminal.
Both node-sass and clean-css-cli parameters are available for Command Line Interface (CLI):
- https://github.com/sass/node-sass#command-line-interface
- https://github.com/jakubpawlowicz/clean-css-cli#cli-options
Import and Export ECMAScript (ES) Modules in Node.js using TypeScript with Babel Compilation
2a.Learn more about ES modules: A cartoon deep-dive
Set the « package.json »
Install Sass and Clean CSS packages
We will compile SASS .scss
files to .css
using DART Sass and ES Modules, for including Babel compiler in your project.
npm install node-sass clean-css-cli --save-dev
Set ES Modules
Edit your package.json
file to add the following line under the "name"
declaration to define that we use ES Modules in NodeJS:
"type": "module",
More packages
Some additional npm packages to carry out the compilation and type checking processes: Babel for generating clean, optimized and compiled JavaScript code, cross-env to have a single command without worrying about setting or using the environment variable properly for the Windows or Linux/MacOS platforms, rimraf the UNIX command rm -rf
for node and TypeScript adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host, on any OS.
npm install cross-env @babel/cli @babel/core @babel/preset-env @babel/preset-typescript rimraf typescript --save
Set the TypeScript compiler
At the root of the project, at the same level as your package.json
file, create a new file named tsconfig.json
.
touch tsconfig.json
Copy/Paste the following compiler options in that new file:
/tsconfig.json
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"isolatedModules": true,
"strict": true,
"module": "esnext",
"lib": ["ES2019"],
"noEmit": true,
"moduleResolution": "node",
"skipLibCheck": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules/**/*", "dist/**/*"]
}
Pay attention to the line
"include": ["src/**/*.ts"]
above where we set the sources reposity to be used as «src/
». To know more available configuration options for the TypeScript go to typescriptlang.org/tsconfig
Set Babel
touch .babelrc.json
Copy/Paste the following options for compiling your Sass and JS:
/.babelrc.json
{
"presets": [
["@babel/preset-env", { "modules": false, "targets": { "node": true } }],
["@babel/preset-typescript"]
],
"ignore": ["node_modules"],
"comments": false,
"minified": true
}
In the above example there are two extra babel settings included that instruct the Babel compiler to remove any comments in the source code and minify the JavaScript output.
The sources reposity
Create the repository where all the originals (uncompiled) files for developpers and create two empty files, one for exporting (helpers) and the other for importing (index) errors :
/src
Export and Import ES Modules from within the mkdir src && cd src
touch helpers.ts index.ts && cd ../
Copy/Paste the following basic function to catch and export any error.
/scr/helpers.ts
function log(value: string) {
console.log(value);
}
export { log };
Copy/Paste the following code to import and print the errors as logs in the file.
/scr/index.ts
import { log } from "./helpers.js";
function main() {
log("testing the modules");
}
main();
It is important to note that the file imported must end with a «
.js
» file extension rather than a «.ts
» file extension. This is because when the code is eventually compiled the ES Module code will then be a JavaScript file.
The distributed repository
/dist
Run ES Modules in NodeJS to compile in Open and edit the main package.json
file, look for the script {}
properties and replace the line "test": "echo \"Error: no test specified\" && exit 1"
by the block :
"test": "echo \"Error: no test specified\" && exit 1",
"compile": "cross-env-shell babel src -d dist --source-maps --extensions '.ts'",
"build": "npm run clean && npm run compile",
"typecheck": "tsc --p .",
"build-typecheck": "npm run typecheck && npm run build",
"jsstart": "npm run build-typecheck && node ./dist/index.js"
Since the JavaScript code is being output to a folder named /dist
the "main"
property value from within the package.json
file should be changedfrom "main": "index.js"
to :
"main": "./dist/index.js"
Use the Dart Sass JavaScript Implementation to Compile SASS with Node.js
2b.Compile with Dart Sass
In the same project root folder create a new file that will contain the entry point for the Node.js process that will carry out the SASS compilation.
touch index.js
Copy/Paste
/index.js
import sass from "sass";
import { promisify } from "util";
const sassRenderPromise = promisify(sass.render);
async function main() {
const styleResult = await sassRenderPromise({
file: `${process.cwd()}/styles.scss`,
});
console.log(styleResult.css.toString());
}
main();
This makes working with the asynchronous API of the sass npm package more manageable because it allows for the use of async/await syntax.
Now the main function contains the code to compile the styles.scss file into CSS. In order to run this code add the following line in the package.json
file, within the already existing script {…}
properties :
"csstart": "node index.js"
The commands
$ command |
description |
---|---|
npm run build | This will remove the old files from the /dist folder and compile the TypeScript source code with Babel, however no typechecking errors will be indicated and Babel may fail to compile the code if there are errors present.To resolve this an additional script "typecheck" is included that will pass the TypeScript source code through the TypeScript compiler, and if there are errors present, they will be output to the console. Since the tsconfig.json settings include the "noEmit" property the typecheck command won't output any JavaScript code. |
npm run build-typecheck | This will sequentially run the "typecheck" command and then if there are no errors present as a result of the TypeScript compilation with the TypeScript compiler, the "build" command will be executed, invoking the Babel compiler and generating JavaScript code that can be run by Node.js in ES Module format. |
npm run jsstart | Run the compiled JavaScript code |
npm run csstart | Process the Sass files to CSS |