Electron shows white screen when built - javascript

I'm learning electron and I've made an electron app that read and create files.
When I start the application with npm start or electron . it works as intended:
But when I use npm run build or build -w commands, the application built just shows a white screen
Is there something wrong with my code or something wrong with the commands I'm using?
This is my package.json
{
"name": "prova",
"version": "1.1.3",
"description": "Prova electron",
"main": "index.js",
"scripts": {
"start": "electron .",
"dist" : "build"
},
"author": "Randy",
"license": "ISC",
"devDependencies": {
"electron": "^2.0.2",
"electron-packager": "^12.1.0"
},
"build": {
"appId": "prova",
"win":{
"target" : "nsis",
"icon" : "icon.ico"
}
}
}
This is my main js page:
const {app, BrowserWindow} = require('electron')
const url = require('url')
function boot(){
win = new BrowserWindow()
win.loadURL(url.format({
pathname: 'index.html',
slashes: true
}))
}
app.on('ready', boot);
and there is my functions js page:
var app = require("electron").remote;
var dialog = app.dialog;
var fs = require("fs");
var i = 0;
var stringaLetta = "";
document.getElementById("bottone").onclick = function(){
dialog.showSaveDialog((fileName) => {
if(fileName === undefined){
alert("errore")
return
}
var content = document.getElementById("testo").value;
fs.writeFile(fileName, content, (err) => {
if (err == undefined) {
dialog.showMessageBox({
message: "the file has been saved",
buttons: ["OK"]
});
}
else dialog.showMessageBox({
message: err
})
})
})
}
document.getElementById("bottone2").onclick = function(){
dialog.showOpenDialog((fileNames) => {
if(fileNames === undefined){
dialog.showMessageBox({
message: "errore durante l'apertura",
buttons: ["OK"]
})
return
} else{
readFile(fileNames[0]);
}
})
}
function readFile(fP){
fs.readFile(fP, 'utf-8', (err, data) => {
if(err){
alert(err)
return
}
var textArea = document.getElementById("rtesto")
textArea.innerHTML = "";
i = 0;
do{
if(data.charAt(i) == "\n"){
stringaLetta += "<br\>";
}else{
stringaLetta += data.charAt(i);
}
i++;
}while(data.charAt(i) != "")
textArea.innerHTML = stringaLetta;
stringaLetta = " ";
})
}

I had a similar problem when I tried to build for windows.
While the win.loadURL(...) seems to work like that in development, maybe try to change it to this when building:
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}));
This makes sure it definitly gets the right path to your index.html file.
For the path.join(...) and url.format(...) to work you need to require them first:
const path = require('path');
const url = require('url');

i recently face white screen issue in my case little bit difference
i used vue framework with router(router must be hash)
1.for vue.js with vue router in electron
const router = new VueRouter({
mode: 'hash',
routes: [...]
})
2.for react.js with react router in electron
hashrouter
instead of
BrowserRouter
without any framework
check entry point url placed correctly
win.loadURL('app://./index.html')

In my case the build showed a white site as well. For those who are using React Router in their project this solution might be helpful.
My startUrl variable looks like this:
const startUrl = process.env.ELECTRON_START_URL || url.format(
{
pathname: path.join(__dirname, '/../build/index.html'),
protocol: 'file:',
slashes: true
});
For me the solution was to move from BrowserRouter to HashRouter in your App.js as mentioned in this thread
render()
{
return (
<Provider store = { store }>
<HashRouter>
<Switch>
<Route exact path='/' component={Home} />
<Route exact path='/Login' component={Login} />
</Switch>
</HashRouter>
</Provider>
);
}

I don't know about the build process especially, I had also the same problem on development, that electron shows nothing but a blank screen (probably because I clicked a link that was not available earlier).
After rebuilding and what else nothing was shown on the screen.
The final hack that worked for me was
clearning my Appdata from system.
In my case I had linux I cleared the app data by going to ~/.config/myApp
Windows: C:\Users\<user>\AppData\Roaming\<yourAppName>\Cache
OSX: /Users/<user>/Library/Application Support/<yourAppName>/Cache
Hope it will help someone in need.

Maybe you used a template of code that uses 2 cases,
one for development mode and one for production. At least that was my problem, so for dev mode I used to use a URL to localhost, and in production, it points to the build dir: like so:
const prodPath = format({
pathname: resolve('renderer/out/start/index.html'),
protocol: 'file:',
slashes: true
})

check how you set the title for the main window.
I tried to use 'process.env.npm_package_productName'
mainWindow.setTitle(process.env.npm_package_productName);
works fine locally, but fails when packed!

I had the same problem. I think it is a miss understanding, that the electron app will be bundled into a single .exe file.
I used the electron-react-boilerplate template from GitHub. If you
are going to package your application, all it does is generating
a directory with your bundled code (the electron-react-boilerplate template does that for you) and a bunch of other files with the generated .exe file in release/build/win-unpacked in the release/build folder.
What you have to do to get it to work:
Get the absolute path code wise of your index.html file in release/app/dist/renderer/index.html (CODEWISE) (Get this path in your main.ts/js)
Then use this file url in your mainWindow.loadUrl() function.
Then you will realize, that the whole release folder is actually your app to distribute to your clients.

Note: For launch the app with electron, follow these steps:(forgive my
English I am native french speaker)
First of all forget about the electron folder, do not touch it.
In your react/ion directory which is your root directory for the app,add the following in your package.json file: "homepage": "./"
Now from your react/ionic directory which is your root directory for the app, navigate to the "public" directory and update your index.html file replacing <base href="/" /> with: <base href="./" />
Now run the following command and that is it...
ionic build && npx cap copy
npx cap open electron

Related

Yarn Workspaces, workspace does not emit errors or warnings

I have followed the following post in order to create a monorepo using yarn workspaces and craco.
It works really well except one thing: the errors/warnings of the common (components )library are not emitted to the console.
The structure is very simple:
monorepo
|-packages
|-components
|-fe
Fe is the main webApp that uses the components library.
The FE emits all warnings correctly, components does not.
How to make the shared component emit warnings/errors?
Updated:
Steps to reproduce in this repo:
https://github.com/sofoklisM/my-monorepo.git
What you need to change is the context option of the underlying ESLint Webpack plugin that is used by Create React App.
In this case I changed the context of ESLint to the root of the monorepo (yarn workspace root).
Here is an updated craco.config.js that should do the trick:
// craco.config.js
const path = require("path");
const { getLoader, loaderByName } = require("#craco/craco");
const { getPlugin, pluginByName } = require("#craco/craco/lib/webpack-plugins")
const absolutePath = path.join(__dirname, "../components");
module.exports = {
webpack: {
alias: {},
plugins: [],
configure: (webpackConfig, { env, paths }) => {
const { isFound, match } = getLoader(
webpackConfig,
loaderByName("babel-loader")
);
if (isFound) {
const include = Array.isArray(match.loader.include)
? match.loader.include
: [match.loader.include];
match.loader.include = include.concat([absolutePath]);
}
// Change context of ESLint Webpack Plugin
const { match: eslintPlugin } = getPlugin(webpackConfig, pluginByName("ESLintWebpackPlugin"));
eslintPlugin.options['context'] = path.join(__dirname, "../..");
return webpackConfig;
}
}
};
I've also made an updated fork of your reproduction repo here: https://github.com/ofhouse/stackoverflow-65447779

Electron app opening multiple windows or processes in spectron test

My electron app works as expected but it keeps on opening new windows when I run spectron test that tests for number of windows opened.
Electron version - v8.0.2 , "spectron": "^10.0.1" . I am not sure how to check exact version of spectron.
I am just running a small demo, below I will give code snippet
Note: I am running the spectron test pointing to .exe file generated by electron-packager.
Does Anyone have an idea what is the issue if possible how to solve it?
main.js
const { app, BrowserWindow } = require('electron')
function createWindow () {
let win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
win.loadFile('index.html')
}
app.whenReady().then(createWindow)
index.js
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
test.js
const assert = require('assert');
const path = require('path');
const Application = require('spectron').Application;
const electronPath = require('electron');
const app = new Application({
path: 'C:/demoElectronApp/winx64/demoelectronapp-win32-x64/demoelectronapp.exe',
});
describe('client_settings_app', function () {
this.timeout(10000);
beforeEach(() => {
return app.start();
});
it('shows only one initial window', async () => {
const count = await app.client.getWindowCount();
return assert.equal(count, 1);
});
})
package.json
{
"name": "demoelectronapp",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"electronpackage": "electron-packager . --out winx64"
},
"author": "",
"license": "ISC",
"dependencies": {
"path": "^0.12.7"
},
"devDependencies": {
"electron": "^8.2.2",
"electron-packager": "^14.2.1",
"assert": "^2.0.0",
"mocha": "^7.1.1",
"spectron": "^10.0.1"
}
}
Okay, I was having the same issue. And solved by setting remote debugging port.
chromeDriverArgs: ['remote-debugging-port=9222']
Full test code:
const Application = require('spectron').Application
const assert = require('assert')
const electronPath = require('electron') // Require Electron from the binaries included in node_modules.
const path = require('path')
describe('Application launch', function () {
this.timeout(10000)
beforeEach(function () {
this.app = new Application({
// Your electron path can be any binary
// i.e for OSX an example path could be '/Applications/MyApp.app/Contents/MacOS/MyApp'
// But for the sake of the example we fetch it from our node_modules.
path: path.join(__dirname, '..', 'node_modules', '.bin', 'electron' + (process.platform === 'win32' ? '.cmd' : '')),
// Assuming you have the following directory structure
// |__ my project
// |__ ...
// |__ main.js
// |__ package.json
// |__ index.html
// |__ ...
// |__ test
// |__ spec.js <- You are here! ~ Well you should be.
// The following line tells spectron to look and use the main.js file
// and the package.json located 1 level above.
args: [path.join(__dirname, '..')],
env: {
ELECTRON_ENABLE_LOGGING: true,
ELECTRON_ENABLE_STACK_DUMPING: true,
NODE_ENV: 'test'
},
waitTimeout: 10e3,
requireName: 'electronRequire',
chromeDriverLogPath: '../chromedriverlog.txt',
chromeDriverArgs: ['remote-debugging-port=9222']
})
return this.app.start()
})
afterEach(function () {
if (this.app && this.app.isRunning()) {
return this.app.stop()
}
})
it('shows an initial window', function () {
return this.app.client.getWindowCount().then(function (count) {
assert.equal(count, 1)
// Please note that getWindowCount() will return 2 if `dev tools` are opened.
// assert.equal(count, 2)
})
})
})
I was having a similar issue, and changed the version of the packages I was working with.
This page has the version map:
https://github.com/electron-userland/spectron#version-map
It seems like this isn't your problem byt may help others.
I FINALLY found a way to fix this that worked for me. I found it in a comment by #wburgess-invision on this gitHub thread here: https://github.com/electron-userland/spectron/issues/60
Navigate to node_modules -> spectron -> lib -> launcher.js
after the line "const args = appArgs.concat(chromeArgs);" add a new line and copy and paste this: args.splice(args.indexOf('--enable-logging'), 1)
npm run build
To quote the thread: "I noticed that it was happening because of the --enable-logging parameter being passed in. So I made a modified version of launcher.js which purposely didn't include --enable-logging and it worked fine for us. I couldn't find where the spectron launcher was managing to pick up the --enable-logging flag from as I thought a better solution would have been just not providing it to launcher.js in the first place but I couldn't find out so I just went with the solution that worked for now. My assumption was that the --enable-logging flag was being picked up somewhere inside of webdriverio when the client is initialized and thus calls launcher.bat but I couldn't find out where."

Cypress - Getting error while executing 'cypress open'

I've a Testing framework with node, cypress, mocha, mochawesome and mochawesome-merge as below with this github repo:
and in my package.json I have two scripts as
`"scripts": {
"cy": "./node_modules/.bin/cypress open",
"cy_test": "node cypress.js"
},`
If I run npm run cy_test it works fine in headless state, but if I run npm run cy i get following error:
But If I remove cypress.js from my project then it works as expected.
cypress.js
const cypress = require('cypress')
const marge = require('mochawesome-report-generator')
const { merge } = require('mochawesome-merge')
const currRunTimestamp = getTimeStamp();
const mergedReport = {
reportDir: 'mochawesome-report',
}
const finalReport = {
reportDir: 'reports',
}
cypress.run({
reporter: 'mochawesome',
reporterOptions: {
reportDir: 'mochawesome-report',
overwrite: false,
html: true,
json: true
}
}).then(
() => {
generateReport()
},
error => {
generateReport()
console.error(error)
process.exit(1)
}
)
function generateReport(options) {
return merge(mergedReport).then(report => marge.create(report, finalReport))
}
I think this is a problem with npm on Windows that is messing with file names, because npm is trying to run the script as binary instead of getting it from ./node_modules/.bin.
So, I'll suggest, as first try, if you can, change the name of the cypress.js to something other than cypress. I think this can solve your problem.
If not, as a workaround remove .JS from PATHEXT environment variable and restart the processes that are running the script, including your IDE, if applicable.
Hope it works.

Specify code to run before any Jest setup happens

The tl;dr is:
1) How can I have Jest use the native require function to load all modules in my tests anywhere.
2) Where / how would I go about modifying (ie replacing with the esm loader) https://github.com/standard-things/esm the require function in one place, before any tests run, so all tests will use the modified require.
I'd like to use the esm-loader with my Jest test files. In order to do so, I need to patch the require function globally, before any test code runs, with something like
require = require("#std/esm")(module, { esm: "js", cjs: true });
How do I tell Jest to execute that code before anything else is touched or requested?
I tried pointing both setupTestFrameworkScriptFile and an setupFiles array entry to a file with that in it, but neither worked (though I did confirm that both ran).
Alternatively, I'm firing off these tests with an npm script
"scripts": {
"test": "jest"
}
Is there some CLI magic whereby I can just load a module and then run jest?
Edit - the testEnvironment and resolver options make me wonder if this is ever even using the actual Node require function to load modules, or instead using its own module loader. If so I wonder if this is even possible.
So this one was a bit tough to get working. The solution is quite simple but it took me a while to get it working. The problem is that whenever you use any module in jest
Setup Files
Setup Framework Files
Test Files
Module files
They are all loaded in below way
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){/*Module code inside*/
}});
If you have a look at node_modules/jest-runtime/build/index.js:495:510
const dirname = (_path || _load_path()).default.dirname(filename);
localModule.children = [];
localModule.parent = mockParentModule;
localModule.paths = this._resolver.getModulePaths(dirname);
localModule.require = this._createRequireImplementation(filename, options);
const transformedFile = this._scriptTransformer.transform(
filename,
{
collectCoverage: this._coverageOptions.collectCoverage,
collectCoverageFrom: this._coverageOptions.collectCoverageFrom,
collectCoverageOnlyFrom: this._coverageOptions.collectCoverageOnlyFrom,
isInternalModule,
mapCoverage: this._coverageOptions.mapCoverage },
this._cacheFS[filename]);
this._createRequireImplementation(filename, options); gives every module a custom require object. So you as such don't get the native require function at all, anywhere. Once jest has started every module loaded from then on will have jest's custom require function.
When we load a module, the requireModule methods from the jest-runtime gets called. Below is an excerpt from the same
moduleRegistry[modulePath] = localModule;
if ((_path || _load_path()).default.extname(modulePath) === '.json') {
localModule.exports = this._environment.global.JSON.parse(
(0, (_stripBom || _load_stripBom()).default)((_gracefulFs || _load_gracefulFs()).default.readFileSync(modulePath, 'utf8')));
} else if ((_path || _load_path()).default.extname(modulePath) === '.node') {
// $FlowFixMe
localModule.exports = require(modulePath);
} else {
this._execModule(localModule, options);
}
As you can see if the extension of the file is .node it loads the module directly, else it calls the _execModule. This function is the same code that I posted earlier which does the code transformation
const isInternalModule = !!(options && options.isInternalModule);
const filename = localModule.filename;
const lastExecutingModulePath = this._currentlyExecutingModulePath;
this._currentlyExecutingModulePath = filename;
const origCurrExecutingManualMock = this._isCurrentlyExecutingManualMock;
this._isCurrentlyExecutingManualMock = filename;
const dirname = (_path || _load_path()).default.dirname(filename);
localModule.children = [];
localModule.parent = mockParentModule;
localModule.paths = this._resolver.getModulePaths(dirname);
localModule.require = this._createRequireImplementation(filename, options);
Now when we want to modify require function for our test, we need _execModule to export our code directly. So the code should be similar to loading of a .node modules
} else if ((_path || _load_path()).default.extname(modulePath) === '.mjs') {
// $FlowFixMe
require = require("#std/esm")(localModule);
localModule.exports = require(modulePath);
} else {
But doing that would mean patching the code, which we want to avoid. So what we do instead is avoid using the jest command directly, and create our own jestload.js and running that. The code for loading jest is simple
#!/usr/bin/env node
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
cli = require('jest/bin/jest');
Now we want to modify the _execModule before the cli loads. So we add below code
const jestRuntime = require("jest-runtime");
oldexecModule = jestRuntime.prototype._execModule;
jestRuntime.prototype._execModule = function (localModule, options) {
if (localModule.id.indexOf(".mjs") > 0) {
localModule.exports = require("#std/esm")(localModule)(localModule.id);
return localModule;
}
return oldexecModule.apply(this, [localModule, options]);
};
cli = require('jest/bin/jest');
Now time for a test
//__test__/sum.test.js
sum = require('../sum.mjs').sum;
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
test('adds 2 + 3 to equal 5', () => {
expect(sum(3, 2)).toBe(5);
});
And a sum.mjs file
export function sum (x, y) { return x + y }
Now we run the test
The solution is available on below repo
https://github.com/tarunlalwani/jest-overriding-require-function-stackoverflow
You can clone and test the solution by running npm test.
setupFiles worked for me. Add this in package.json:
"jest": {
"setupFiles": ["./my_file.js"]
},
https://jestjs.io/docs/en/configuration.html#setupfiles-array
I tried using node -r #std/esm run.js where run.js is just a script that calls jest, but it does not work and crashes here : https://github.com/facebook/jest/blob/master/packages/jest-runtime/src/script_transformer.js#L305.
From what I understand from this line means that it is not possible because jest compiles the module using the native vm module. The above lines (290):
if (willTransform) {
const transformedSource = this.transformSource(
filename,
content,
instrument,
!!(options && options.mapCoverage));
wrappedCode = wrap(transformedSource.code);
sourceMapPath = transformedSource.sourceMapPath;
} else {
is the code called when you are specifying transforms in your jest config.
Conclusion : until esm are supported ( and they will be under the .mjs extension ) you cannot import es modules in jest without specifying a transform. You could try to monkey patch vm but I would really advise against this option.
Specifying a jest transform is really not that hard, and for es modules it's really as simple as using babel-jest with the right babel config :
Below a package.json with minimal settings
{
"dependencies": {
"babel-jest": "^21.2.0",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.0",
"jest": "^21.2.1"
},
"jest": {
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.js?(x)",
"<rootDir>/src/**/?(*.)(spec|test).js?(x)"
],
"transform": {
"^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest"
},
"testEnvironment": "node",
"testURL": "http://localhost",
"moduleFileExtensions": [
"js",
"json"
]
},
"babel": {
"plugins": ["babel-plugin-transform-es2015-modules-commonjs"]
}
}

How can I add Font Awesome to my Aurelia project using npm?

I have been following the Contact Manager tutorial and would like to add Font Awesome to the project. Here's what I have done so far:
npm install Font-Awesome --save
Added the following to aurelia.jsonunder the dependencies array of the vendor-bundle.js:
...
{
"name": "font-awesome",
"path": "../node_modules/font-awesome",
"resources": [
"css/font-awesome.min.css"
]
},
...
But when running au run --watch I get the error:
error
C:\Users\node_modules\font-awesome.js
Why is it looking for the .js file?
Don't add font-awesome resources to aurelia.json - you'd need font files too, which Aurelia don't process. Instead, take the following steps.
First, if you added anything for font-awesome already to your aurelia.json file, remove it again.
Add new file prepare-font-awesome.js in folder \aurelia_project\tasks and insert the below code. It copies font-awesome resource files to output folder (as configured aurelia.json config file; e.g. scripts):
import gulp from 'gulp';
import merge from 'merge-stream';
import changedInPlace from 'gulp-changed-in-place';
import project from '../aurelia.json';
export default function prepareFontAwesome() {
const source = 'node_modules/font-awesome';
const taskCss = gulp.src(`${source}/css/font-awesome.min.css`)
.pipe(changedInPlace({ firstPass: true }))
.pipe(gulp.dest(`${project.platform.output}/css`));
const taskFonts = gulp.src(`${source}/fonts/*`)
.pipe(changedInPlace({ firstPass: true }))
.pipe(gulp.dest(`${project.platform.output}/fonts`));
return merge(taskCss, taskFonts);
}
Open the build.js file in the \aurelia_project\tasks folder and insert the following two lines; this will import the new function and execute it:
import prepareFontAwesome from './prepare-font-awesome'; // Our custom task
export default gulp.series(
readProjectConfiguration,
gulp.parallel(
transpile,
processMarkup,
processCSS,
prepareFontAwesome // Our custom task
),
writeBundles
);
Finally, in the <head> section of your index.html file, just add the following line:
<link rel="stylesheet" href="scripts/css/font-awesome.min.css">
That's all; now you can use font-awesome icons in any Aurelia view modules (html files).
Note that this works for any complex third party library which requires resources which you have to manually include.
Simple default settings method
Here are the 4 simple steps I use to bring in Font-Awesome to an Aurelia project that uses the CLI.
1) npm install font-awesome --save
2) add copyFiles to build of aurelia.json
"build": {
"copyFiles": {
"node_modules/font-awesome/fonts/*": "/fonts/"
},
3) add bundling to dependencies array of aurelia.json
"dependencies": [
{
"name": "font-awesome",
"path": "../node_modules/font-awesome/css",
"main": "font-awesome.css"
},
4) include the import for the css file (mine lives in the app.html)
<require from="font-awesome.css"></require>
=========================================================================
Alternative
Specifying a custom font location
As I was serving my files from a different location I needed to be able to tweek the font location configured. As such, below are the steps involved if you need to do the same and specify where the fonts are stored. I am using .less
1, 2) As above.
3) Instead of adding to the bundling, you need to reference the font-awesome less file within your own less file (mine is called site.less) and then set the #fa-font-path to your custom location.
#import "../node_modules/font-awesome/less/font-awesome.less";
#fa-font-path: "fonts";
4) There is no 4, with this method as long as you have your own compiled equivalent site.css file referenced already (with the import) you don't need to add anything else.
Funny I was trying to get the same thing working this morning. This is all I had to do in my aurelia.json dependencies for it to work:
{
"name": "font-awesome",
"path": "../node_modules/font-awesome/",
"main": "",
"resources": [
"css/font-awesome.min.css"
]
},
Then in my html I had:
<require from="font-awesome/css/font-awesome.min.css"></require>
Not actually answering to your question of how to integrate Font Awesome in your application using NPM, but there is an alternative, clean way to get it in your application: using the CDN.
As mentioned in other answers, Aurlia currently doesn't support bundling resources other than js, css and html out-of-the-box using the CLI. There's a lot of discussion about this subject, and there are several, mostly hacky, workarounds, like some suggested here.
Rob Eisenberg says he's planning on getting it properly integrated in the Aurelia CLI, but he considers it low priority because there's a simple workaround. To quote him:
Of course there is interest in addressing this. However, it's lower priority than other things on the list for the CLI, in part because a simple link tag will fix the problem and is much easier than the work we would have to do to solve this inside the CLI.
Source: https://github.com/aurelia/cli/issues/248#issuecomment-254254995
Get your unique CDN link mailed here: http://fontawesome.io/get-started/
Include this link in the head of your index html file
Don't forget to remove everything you might have already added to try to get it working: the npm package (and its reference in your package.json), the reference in your aurelia.json file, any custom tasks you might have created, any <require> tags,...
importing css/fonts automagicly is now supported.
{
"name": "font-awesome",
"path": "../node_modules/font-awesome/css",
"main": "font-awesome.css"
}
<require from="font-awesome.css"></require>
Checkout this "Issue" https://github.com/aurelia/cli/issues/249
Happy codding
EDIT
I realized/read the comments this does not copy the font files.
Here is an updated build script (es6) that will copy any resources and add the folder to the git ignore. If you want the typescript version check here
https://github.com/aurelia/cli/issues/248#issuecomment-253837412
./aurelia_project/tasks/build.js
import gulp from 'gulp';
import transpile from './transpile';
import processMarkup from './process-markup';
import processCSS from './process-css';
import { build } from 'aurelia-cli';
import project from '../aurelia.json';
import fs from 'fs';
import readline from 'readline';
import os from 'os';
export default gulp.series(
copyAdditionalResources,
readProjectConfiguration,
gulp.parallel(
transpile,
processMarkup,
processCSS
),
writeBundles
);
function copyAdditionalResources(done){
readGitIgnore();
done();
}
function readGitIgnore() {
let lineReader = readline.createInterface({
input: fs.createReadStream('./.gitignore')
});
let gitignore = [];
lineReader.on('line', (line) => {
gitignore.push(line);
});
lineReader.on('close', (err) => {
copyFiles(gitignore);
})
}
function copyFiles(gitignore) {
let stream,
bundle = project.build.bundles.find(function (bundle) {
return bundle.name === "vendor-bundle.js";
});
// iterate over all dependencies specified in aurelia.json
for (let i = 0; i < bundle.dependencies.length; i++) {
let dependency = bundle.dependencies[i];
let collectedResources = [];
if (dependency.path && dependency.resources) {
// run over resources array of each dependency
for (let n = 0; n < dependency.resources.length; n++) {
let resource = dependency.resources[n];
let ext = resource.substr(resource.lastIndexOf('.') + 1);
// only copy resources that are not managed by aurelia-cli
if (ext !== 'js' && ext != 'css' && ext != 'html' && ext !== 'less' && ext != 'scss') {
collectedResources.push(resource);
dependency.resources.splice(n, 1);
n--;
}
}
if (collectedResources.length) {
if (gitignore.indexOf(dependency.name)< 0) {
console.log('Adding line to .gitignore:', dependency.name);
fs.appendFile('./.gitignore', os.EOL + dependency.name, (err) => { if (err) { console.log(err) } });
}
for (let m = 0; m < collectedResources.length; m++) {
let currentResource = collectedResources[m];
if (currentResource.charAt(0) != '/') {
currentResource = '/' + currentResource;
}
let path = dependency.path.replace("../", "./");
let sourceFile = path + currentResource;
let destPath = './' + dependency.name + currentResource.slice(0, currentResource.lastIndexOf('/'));
console.log('Copying resource', sourceFile, 'to', destPath);
// copy files
gulp.src(sourceFile)
.pipe(gulp.dest(destPath));
}
}
}
}
}
function readProjectConfiguration() {
return build.src(project);
}
function writeBundles() {
return build.dest();
}
I believe that bundles.dependencies section is for referencing JS libraries.
In your case, a bit of additional work will be needed. According to Aurelia CLI docs, you can create your own generators as well, which comes in handy for us.
Add some new paths to aurelia.json:
"paths": {
...
"fa": "node_modules\\font-awesome",
"faCssOutput": "src",
"faFontsOutput": "fonts"
...
}
Create a task for css bundling...
au generate task fa-css
Modified task file: aurelia_project\tasks\fa-css.js|ts
import * as gulp from 'gulp';
import * as changedInPlace from 'gulp-changed-in-place';
import * as project from '../aurelia.json';
import {build} from 'aurelia-cli';
export default function faCss() {
return gulp.src(`${project.paths.fa}\\css\\*.min.css`)
.pipe(changedInPlace({firstPass:true}))
/* this ensures that our 'require-from' path
will be simply './font-awesome.min.css' */
.pipe(gulp.dest(project.paths.faCssOutput))
.pipe(gulp.src(`${project.paths.faCssOutput}\\font-awesome.min.css`))
.pipe(build.bundle());
};
...and another for copying font files:
au generate task fa-fonts
Modified task file: aurelia_project\tasks\fa-fonts.js|ts
import * as gulp from 'gulp';
import * as project from '../aurelia.json';
export default function faFonts() {
return gulp.src(`${project.paths.fa}\\fonts\\*`)
.pipe(gulp.dest(project.paths.faFontsOutput));
}
Add these new tasks above to the build process in aurelia_project\tasks\build.js|ts:
export default gulp.series(
readProjectConfiguration,
gulp.parallel(
transpile,
processMarkup,
processCSS,
// custom tasks
faCss,
faFonts
),
writeBundles
);
After doing these steps, au build should embed font-awesome.min.css into scripts/app-bundle.js and copy necessary font files to ./fonts folder.
Last thing to do is to require font-awesome within our html.
<require from ="./font-awesome.min.css"></require>
You don't need more much this:
in aurelia.json
"dependencies": [
"jquery",
"text",
{
"name": "bootstrap",
"path": "../node_modules/bootstrap/dist/",
"main": "js/bootstrap.min",
"deps": ["jquery"],
"resources": [
"css/bootstrap.min.css"
]
},
{
"name": "font-awesome",
"path": "../node_modules/font-awesome/css",
"main": "",
"resources": [
"font-awesome.min.css"
]
}
]
}
],
"copyFiles": {
"node_modules/font-awesome/fonts/fontawesome-webfont.woff": "fonts/",
"node_modules/font-awesome/fonts/fontawesome-webfont.woff2": "fonts/",
"node_modules/font-awesome/fonts/FontAwesome.otf": "fonts/",
"node_modules/font-awesome/fonts/fontawesome-webfont.ttf": "fonts/",
"node_modules/font-awesome/fonts/fontawesome-webfont.svg": "fonts/"
}
See section Setup for copying files
i hope help you.
For those who wish to use the sass version of font-awesome
1) Install font-awesome
npm install font-awesome --save
2) Copy font-awesome's fonts to your project root directory
cp -r node_modules/font-awesome/fonts .
3) Include the font-awesome sass directory in the aurelia css processor task
# aurelia_project/tasks/process-css.js
export default function processCSS() {
return gulp.src(project.cssProcessor.source)
.pipe(sourcemaps.init())
.pipe(sass({
includePaths: [
'node_modules/font-awesome/scss'
]
}).on('error', sass.logError))
.pipe(build.bundle());
};
4) Import font-awesome in your app scss
# src/app.scss
#import 'font-awesome';
5) Require your app scss in your html
# src/app.html
<template>
<require from="./app.css"></require>
</template>

Categories

Resources