Giter VIP home page Giter VIP logo

electron-react-webpack-boilerplate's Introduction



Dependency Status devDependency Status MIT License Current release

Paypal Patreon buymeacoffee

Minimal Electron, React and Webpack boilerplate

Minimal Electron, React, PostCSS and Webpack boilerplate to help you get started with building your next app.

Table of contents

Install

Clone this repo

git clone https://github.com/alexdevero/electron-react-webpack-boilerplate.git

Install dependencies

npm install

or

yarn

Usage

Run the app

npm run start

or

yarn start

Build the app (automatic)

npm run package

or

yarn package

Build the app (manual)

npm run build

or

yarn build

Test the app (after npm run build || yarn run build)

npm run prod
yarn prod

Add Sass

Adding Sass to boilerplate requires updating webpack configs and adding necessary loaders.

  1. To webpack.build.config.js and webpack.dev.config.js add new object to rules:
{
  test: /\.scss$/,
  use: [
    { loader: 'style-loader' },
    { loader: 'css-loader' },
    { loader: 'sass-loader' }],
  include: defaultInclude
}
  1. Install additional loaders for sass, sass-loader and node-sass.

  2. Rename all CSS file to .scss.

Add TailwindCSS

If you don't want to do all these steps, you can clone This Repository and you are good to go.

Adding TainwindCSS to boilerplate requires adding all the dependencies listed on the tailwindcss website for create react app Official Guide. OR follow these steps

  1. install tailwindcss, postcss and autoprefixer.
npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
  1. Install craco.
npm install @craco/craco
  1. Open package.json file, find start and build scripts under scripts.

  2. Add && craco start at the end in start and build scripts. You also have to add build-css script to build the CSS styles using tailwindCSS. "build-css": "npx tailwindcss build -o src/styles/main.css",. You can choose output folder of your own choice. Here are the three scripts after changing/adding.

"start": "cross-env NODE_ENV=development webpack serve --hot --host 0.0.0.0 --config=./webpack.dev.config.js --mode development && craco start",
    "build": "cross-env NODE_ENV=production webpack --config webpack.build.config.js --mode production && craco build",
"build-css": "npx tailwindcss build  -o src/styles/main.css",
  1. Now, create craco.config.js file in your project at root of your project and add the following.
module.exports = {
  style: {
    postcss: {
      plugins: [
        require('tailwindcss'),
        require('autoprefixer'),
      ],
    },
  },
}
  1. Next, generate your tailwind.config.js file:
npx tailwindcss-cli@latest init

This will create a minimal tailwind.config.js file at the root of your project.

  1. (Optional) Configure Tailwind to remove unused styles in production In your tailwind.config.js file, configure the purge option with the paths to all of your components so Tailwind can tree-shake unused styles in production builds:
  // tailwind.config.js
  module.exports = {
   purge: [],
   purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
    darkMode: false, // or 'media' or 'class'
    theme: {
      extend: {},
    },
    variants: {
      extend: {},
    },
    plugins: [],
  }
  1. Add main.css file in app.js. Make sure you choose correct path for CSS file.
import '../styles/main.css' 
  1. You may have to run npm install tailwindcss@latest postcss@latest autoprefixer@latest if you face different version issues.
  2. You can also check JIT Mode In TailwindCSS if you want to use Just In Time Mode.

Change app title

This boilerplate uses HTML Webpack Plugin to generate the HTML file of the app. Changing app title is possible only through webpack configs, webpack.build.config.js and webpack.dev.config.js. App title can be changed by adding objects of options.

In webpack.build.config.js:

plugins: [
  new HtmlWebpackPlugin({title: 'New app title '}),// Add this (line 41)
  new MiniCssExtractPlugin({
    // Options similar to the same options in webpackOptions.output
    // both options are optional
    filename: 'bundle.css',
    chunkFilename: '[id].css'
  }),
  new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify('production')
  }),
  new BabiliPlugin()
],

In webpack.dev.config.js:

plugins: [
  new HtmlWebpackPlugin({title: 'New app title '}),// Add this (line 36)
  new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify('development')
  })
],

Contact and Support

I want your feedback! Here's a list of different ways to me and request help:

If you feel generous and want to show some extra appreciation:

Buy me a coffee

Code of Conduct

Contributor Code of Conduct. By participating in this project you agree to abide by its terms.

License

MIT © Alex Devero.

electron-react-webpack-boilerplate's People

Contributors

alexdevero avatar alphonsothegreat avatar dependabot[bot] avatar sanan4li avatar timburgess avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

electron-react-webpack-boilerplate's Issues

electron as a dev dependecy

Terminal gives the information that electron is not installed as a dev dependecy...So I changed from dependency to dev-dependency. In the future this can cause any problem? Because when I package the files, workes fine.

webpack-dev-server stops access to local files

Hey mate, thanks so much for the boilerplate, it's fantastic.

I had started a prototype of an Electron app before using your boilerplate, on the prototype I had a simple onDrop function that gave me a path in the event:
e.dataTransfer.files

This has a paths like so:

/Users/kylewetton/Desktop/some_image.jpg

Works well!

However, in your boilerplate because of the web-server, my function results in a path like this

http://localhost:8080/Users/kylewetton/Desktop/some_image.jpg

Am i able to reference local files while the server is running? I'm definitely in my 'stumble around until I find a solution' stage of Electron and Node in general so hopefully this is something that is easy to circumvent.

npm build give code ELIFECYCLE error

it works fine with npm start

 "scripts": {
    "prod": "cross-env NODE_ENV=production webpack --mode production --config webpack.build.config.js && electron --noDevServer .",
    "start": "cross-env NODE_ENV=development webpack-dev-server --hot --host 0.0.0.0 --config=./webpack.dev.config.js --mode development",
    "build": "cross-env NODE_ENV=production webpack --config webpack.build.config.js --mode production",
    "package": "npm run build",
    "postpackage": "electron-packager ./ --out=./builds"
  },
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "prod"
18 verbose node v10.16.3
19 verbose npm  v6.9.0
20 error code ELIFECYCLE
21 error errno 2
22 error [email protected] prod: `cross-env NODE_ENV=production webpack --mode production --config webpack.build.config.js && electron --noDevServer .`
22 error Exit status 2
23 error Failed at the [email protected] prod script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 2, true ]

Integrating Redux into the boilerplate

I have forked this repo so that I can use it as the base of my own project. I need Redux for state management so I decided to integrate it into the boilerplate. I decided to start off with a simple Counter app. Latest commits are here.

The app works perfectly fine in development environment. As soon as I run the script to package it for production, I get impossible to debug errors.

$ npm run package

> [email protected] package C:\Users\Phantomhive\Documents\Code\Node.js\electron-react-redux-webpack-boilerplate
> npm run build


> [email protected] build C:\Users\Phantomhive\Documents\Code\Node.js\electron-react-redux-webpack-boilerplate
> cross-env NODE_ENV=production webpack --config webpack.build.config.js --mode production

(node:5892) DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead
Hash: e6d8267a937c49e70318
Version: webpack 4.43.0
Time: 3351ms
Built at: 05/14/2020 4:39:27 PM
 2 assets
Entrypoint main = bundle.css main.js

ERROR in unknown: Unexpected token (729:15)
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] build: `cross-env NODE_ENV=production webpack --config webpack.build.config.js --mode production`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Phantomhive\AppData\Roaming\npm-cache\_logs\2020-05-14T10_39_27_934Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] package: `npm run build`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the [email protected] package script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Phantomhive\AppData\Roaming\npm-cache\_logs\2020-05-14T10_39_27_960Z-debug.log

2020-05-14T10_39_27_960Z-debug.log

0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'package' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'prepackage', 'package', 'postpackage' ]
5 info lifecycle [email protected]~prepackage: [email protected]
6 info lifecycle [email protected]~package: [email protected]
7 verbose lifecycle [email protected]~package: unsafe-perm in lifecycle true
8 verbose lifecycle [email protected]~package: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Users\Phantomhive\Documents\Code\Node.js\electron-react-redux-webpack-boilerplate\node_modules\.bin;C:\ProgramData\Anaconda3;C:\ProgramData\Anaconda3\Library\mingw-w64\bin;C:\ProgramData\Anaconda3\Library\usr\bin;C:\ProgramData\Anaconda3\Library\bin;C:\ProgramData\Anaconda3\Scripts;C:\ProgramData\Anaconda3\bin;C:\ProgramData\Anaconda3\condabin;C:\ProgramData\Anaconda3;C:\ProgramData\Anaconda3\Library\mingw-w64\bin;C:\ProgramData\Anaconda3\Library\usr\bin;C:\ProgramData\Anaconda3\Library\bin;C:\ProgramData\Anaconda3\Scripts;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Windows\System32\OpenSSH;C:\Program Files\dotnet;C:\MinGW\bin;C:\Program Files\CMake\bin;C:\Program Files\Java\jdk1.8.0_231\bin;C:\Program Files\nodejs;C:\Program Files\MongoDB\Server\4.2\bin;C:\Program Files\Microsoft SQL Server\130\Tools\Binn;C:\Users\Phantomhive\AppData\Local\Programs\MiKTeX 2.9\miktex\bin\x64;C:\xampp\php;C:\Program Files\MATLAB\R2018b\runtime\win64;C:\Program Files\MATLAB\R2018b\bin;C:\ProgramData\chocolatey\bin;C:\ProgramData\chocolatey\lib\mpv.install\tools;C:\Program Files\Git\cmd;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Git LFS;C:\Program Files (x86)\Yarn\bin;C:\Users\Phantomhive\AppData\Local\Microsoft\WindowsApps;C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\bin\Hostx64\x64;C:\Users\Phantomhive\AppData\Roaming\npm;C:\Users\Phantomhive\AppData\Local\Programs\MiKTeX 2.9\miktex\bin\x64;C:\Users\Phantomhive\AppData\Local\Programs\Microsoft VS Code\bin;C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.3.1\bin;.;C:\chromedriver_win32;C:\ffmpeg\bin;C:\Program Files\heroku\bin;C:\Users\Phantomhive\AppData\Local\Yarn\bin
9 verbose lifecycle [email protected]~package: CWD: C:\Users\Phantomhive\Documents\Code\Node.js\electron-react-redux-webpack-boilerplate
10 silly lifecycle [email protected]~package: Args: [ '/d /s /c', 'npm run build' ]
11 silly lifecycle [email protected]~package: Returned: code: 2  signal: null
12 info lifecycle [email protected]~package: Failed to exec package script
13 verbose stack Error: [email protected] package: `npm run build`
13 verbose stack Exit status 2
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:198:13)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:198:13)
13 verbose stack     at maybeClose (internal/child_process.js:982:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
14 verbose pkgid [email protected]
15 verbose cwd C:\Users\Phantomhive\Documents\Code\Node.js\electron-react-redux-webpack-boilerplate
16 verbose Windows_NT 10.0.17763
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "package"
18 verbose node v10.16.3
19 verbose npm  v6.9.0
20 error code ELIFECYCLE
21 error errno 2
22 error [email protected] package: `npm run build`
22 error Exit status 2
23 error Failed at the [email protected] package script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 2, true ]

Taking out Redux related code however makes the app package successfully.

Any suggestions would be appreciated.

Cannot use ES5 syntax

I would like to be able to write code with ECMAScript 2015 - ES6

This function markup below does not work in the current boilerplate, will not compile.

test = () => {

}

Only this would work:

function test(){

}

It can be fixed by installing a couple babel plugins. I ended up with the following babelrc

{
  "presets": ["@babel/preset-react"],
   "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-transform-arrow-functions"
  ]
}

Package/Build Error

Hello, when I run npm run package I am given the following error

> [email protected] package D:\Documents\cba2\electron-react-webpack-boilerplate
> npm run build


> [email protected] build D:\Documents\cba2\electron-react-webpack-boilerplate
> cross-env NODE_ENV=production webpack --config webpack.build.config.js --mode production

(node:21540) [DEP_WEBPACK_COMPILATION_OPTIMIZE_CHUNK_ASSETS] DeprecationWarning: optimizeChunkAssets is deprecated (use Compilation.hook.processAssets instead and use one of Compilation.PROCESS_ASSETS_STAGE_* as stage option)
(Use `node --trace-deprecation ...` to show where the warning was created)
(node:21540) [DEP_WEBPACK_DEPRECATION_ARRAY_TO_SET] DeprecationWarning: Compilation.chunks was changed from Array to Set (using Array method 'reduce' is deprecated)
(node:21540) [DEP_WEBPACK_DEPRECATION_ARRAY_TO_SET_LENGTH] DeprecationWarning: chunk.files was changed from Array to Set (using Array property 'length' is deprecated)
(node:21540) [DEP_WEBPACK_DEPRECATION_ARRAY_TO_SET_INDEXER] DeprecationWarning: chunk.files was changed from Array to Set (indexing Array is deprecated)
assets by status 219 KiB [cached] 2 assets
Entrypoint main = bundle.css main.js

ERROR in
unknown: Unexpected token, expected ( (13745:12)

webpack 5.18.0 compiled with 1 error in 4671 ms
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `cross-env NODE_ENV=production webpack --config webpack.build.config.js --mode production`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\alber\AppData\Roaming\npm-cache\_logs\2021-01-29T13_46_36_696Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] package: `npm run build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] package script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\alber\AppData\Roaming\npm-cache\_logs\2021-01-29T13_46_36_714Z-debug.log

I have researched and deleted my node_modules folder and yarn.lock and then reinstalled them but I still have the same error.
(works on brand new install of the boilerplate, just not working after I add my react project to it (also works fine with npm run start)

import css file from node_modules/ folder

Trying to use the openlayers module, when importing the ol.css file from node_modules/ol/ol.css I encounter this:

ERROR in ./node_modules/ol/ol.css 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
> .ol-box {
|   box-sizing: border-box;
|   border-radius: 2px;
 @ ./src/components/MainContainer.js 2:0-40
 @ ./src/components/App.js
 @ ./src/index.js

I'm not familiar with PostCSS or really webpack for that matter, so any idea why this is failing would be great, since I'm very tired from trying to get other boilerplates and tutorials working. Most are too bloated or too outdated, I very much like your boilerplate though. Thanks!

Make use of SASS

What must be done to make use of SASS?

I tried adding the two module rules to webpack.dev.config.js, but the first one (the non-global one) didn't do the trick (for this I installed style-loader, typings-for-css-modules-loader, postcss-loader, sass-loader, and autoprefixer):

        {
            test: /\.scss$/,
            exclude: /\.global.scss$/,
            use : [
                { loader: "style-loader" },
                { loader: "typings-for-css-modules-loader", options: { modules: true, namedExport: true, camelCase: true, localIdentName: "[local]" }},
                { loader: "postcss-loader", options: { plugins: function () { return [ require("autoprefixer") ]; }}},
                { loader: "sass-loader" }
            ]
        },
        {
            test: /\.scss$/,
            include: /\.global.scss$/,
            use : [
                { loader: "style-loader" },
                { loader: "css-loader" },
                { loader: "postcss-loader", options: { plugins: function () { return [ require("autoprefixer") ]; }}},
                { loader: "sass-loader" }
            ]
        },

Even though it should now create *.d.ts files for every *.scss file, when running yarn start it does not do it.

Is there another approach to make use of Sass here in the Electron React Webpack Boilerplate?

Error while building

everyThing seems ok while in developement but it crashes while building

---- using yarn

$ yarn build
yarn run v1.22.10
$ cross-env NODE_ENV=production webpack --config webpack.build.config.js --mode production
Hash: 644fc682e3e5f616b91a
Version: webpack 4.44.1
Time: 38070ms
Built at: 2020-10-09 18:15:06
6 assets
Entrypoint main = bundle.css main.js

ERROR in unknown: Unexpected token (149831:13)
error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

-------using npm

$npm run build

[email protected] build C:\Users\DESKTOP\Desktop\Applications\electronWebpack-main
cross-env NODE_ENV=production webpack --config webpack.build.config.js --mode production

Hash: 644fc682e3e5f616b91a
Version: webpack 4.44.1
Time: 47047ms
Built at: 2020-10-09 18:27:22
6 assets
Entrypoint main = bundle.css main.js

ERROR in unknown: Unexpected token (149831:13)
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] build: cross-env NODE_ENV=production webpack --config webpack.build.config.js --mode production
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\DESKTOP\AppData\Roaming\npm-cache_logs\2020-10-09T16_27_26_377Z-debug.log

Class Support?

Does this boiler plate support classes? I was trying to use state and was given an error.

unable to start the project

I cloned the repo and after the npm i I try starting it with npm start but I get the following error

ERROR in Error: The loader "C:\Users\caval\Documents\GitRepos\lol-electron-app\node_modules\html-webpack-plugin\lib\loader.js!C:\Users\caval\Documents\GitRepos\lol-electro n-app\node_modules\html-webpack-plugin\default_index.ejs" didn't return html.

Electron Latest

Hi
This bug: electron/electron#23662
force me to update the eletron to the latest. But right now after compilation I have blank page. Menu are loading but nothing else.

Electron 12.0.0

「wdm」: asset main.js 3.24 MiB [emitted] (name: main) 1 related asset
asset index.html 231 bytes [emitted]
930 modules
webpack 5.24.2 compiled successfully in 6386 ms
i 「wdm」: Compiled successfully.
(node:16412) ExtensionLoadWarning: Warnings loading extension at C:\Users\user\AppData\Roaming\project\extensions\fmkadmapgofadopljbjfkapdkoienihi:
Unrecognized manifest key 'browser_action'.
Unrecognized manifest key 'minimum_chrome_version'.
Unrecognized manifest key 'update_url'.
Cannot load extension with file or directory name metadata. Filenames starting with "" are reserved for use by the system.

(Use electron --trace-warnings ... to show where the warning was created)

Webpack prod error - cannot concat react, react-dom, etc.

I'm having trouble building this for prod. It works perfectly fine during dev.

Heres the error message:

> [email protected] build /opt/newtelco/billing-parser
> cross-env NODE_ENV=production webpack --verbose --progress --config webpack.build.config.js --mode production

Hash: 533302141eed02251f6e
Version: webpack 4.43.0
Time: 1413ms
Built at: 05/30/2020 4:15:36 AM
     Asset       Size  Chunks             Chunk Names
index.html  212 bytes          [emitted]
   main.js    150 KiB       0  [emitted]  main
Entrypoint main = main.js
chunk    {0} main.js (main) 202 KiB [entry] [rendered]
    > ./src main
 [11] ./src/index.js + 8 modules 67.7 KiB {0} [depth 0] [built]
      [no exports]
      ModuleConcatenation bailout: Cannot concat with ./node_modules/attr-accept/dist/index.js (<- Module is not an ECMAScript module)
      ModuleConcatenation bailout: Cannot concat with ./node_modules/prop-types/index.js (<- Module is not an ECMAScript module)
      ModuleConcatenation bailout: Cannot concat with ./node_modules/react-dom/index.js (<- Module is not an ECMAScript module)
      ModuleConcatenation bailout: Cannot concat with ./node_modules/react/index.js (<- Module is not an ECMAScript module)
      single entry ./src  main
      | ./src/index.js 465 bytes [depth 0] [built]
      |     [no exports]
      |     ModuleConcatenation bailout: Module is an entry point
      |     single entry ./src  main
      |     + 8 hidden modules
     + 11 hidden modules

LOG from webpack.buildChunkGraph.visitModules
<t> prepare: 0.380601ms
<t> visiting: 0.226386ms
Child HtmlWebpackCompiler:
     1 asset
    Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0
    chunk    {0} __child-HtmlWebpackPlugin_0 (HtmlWebpackPlugin_0) 429 bytes [entry] [rendered]
        > /opt/newtelco/billing-parser/node_modules/html-webpack-plugin/lib/loader.js!/opt/newtelco/billing-parser/node_modules/html-webpack-plugin/default_index.ejs HtmlWebpackPlugin_0
        1 module

    LOG from webpack.buildChunkGraph.visitModules
    <t> prepare: 0.342339ms
    <t> visiting: 0.164898ms

My webpack.build.conf.js

const webpack = require('webpack')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const BabiliPlugin = require('babili-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

// Any directories you will be adding code/files into, need to be added to this array so webpack will pick them up
const defaultInclude = path.resolve(__dirname, 'src')

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader'],
        include: defaultInclude,
      },
      {
        test: /\.jsx?$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              ['@babel/env', { modules: false }],
              ['@babel/react', { modules: false }],
            ],
          },
        },
        include: defaultInclude,
      },
      {
        test: /\.(jpe?g|png|gif)$/,
        use: [{ loader: 'file-loader?name=img/[name]__[hash:base64:5].[ext]' }],
        include: defaultInclude,
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        use: [
          { loader: 'file-loader?name=font/[name]__[hash:base64:5].[ext]' },
        ],
        include: defaultInclude,
      },
    ],
  },
  target: 'electron-renderer',
  plugins: [
    new HtmlWebpackPlugin({ title: 'Newtelco Billing Parser' }),
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: 'bundle.css',
      chunkFilename: '[id].css',
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production'),
    }),
    // new BabiliPlugin(),
  ],
  stats: {
    colors: true,
    children: false,
    chunks: false,
  },
}

My main.js

'use strict'

// Import parts of electron to use
const { app, BrowserWindow, Menu } = require('electron')
const path = require('path')
const url = require('url')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

// Keep a reference for dev mode
let dev = false

// Broken:
// if (process.defaultApp || /[\\/]electron-prebuilt[\\/]/.test(process.execPath) || /[\\/]electron[\\/]/.test(process.execPath)) {
//   dev = true
// }

if (
  process.env.NODE_ENV !== undefined &&
  process.env.NODE_ENV === 'development'
) {
  dev = true
} else {
  Menu.setApplicationMenu(null)
}

// Temporary fix broken high-dpi scale factor on Windows (125% scaling)
// info: https://github.com/electron/electron/issues/9691
if (process.platform === 'win32') {
  app.commandLine.appendSwitch('high-dpi-support', 'true')
  app.commandLine.appendSwitch('force-device-scale-factor', '1')
}

function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 500,
    height: 320,
    show: false,
    webPreferences: {
      nodeIntegration: true,
    },
    autoHideMenuBar: dev ? false : true,
  })

  // and load the index.html of the app.
  let indexPath

  if (dev && process.argv.indexOf('--noDevServer') === -1) {
    indexPath = url.format({
      protocol: 'http:',
      host: 'localhost:8080',
      pathname: 'index.html',
      slashes: true,
    })
  } else {
    indexPath = url.format({
      protocol: 'file:',
      pathname: path.join(__dirname, 'dist', 'index.html'),
      slashes: true,
    })
  }

  mainWindow.loadURL(indexPath)

  // Don't show until we are ready and loaded
  mainWindow.once('ready-to-show', () => {
    mainWindow.show()

    // Open the DevTools automatically if developing
    if (dev) {
      const {
        default: installExtension,
        REACT_DEVELOPER_TOOLS,
      } = require('electron-devtools-installer')

      installExtension(REACT_DEVELOPER_TOOLS).catch((err) =>
        console.log('Error loading React DevTools: ', err),
      )
      mainWindow.webContents.openDevTools()
    }
  })

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow()
  }
})

And my index.js

import React from 'react'
import { render } from 'react-dom'
import App from './components/App'

// Since we are using HtmlWebpackPlugin WITHOUT a template, we should create our own root node in the body element before rendering into it
let root = document.createElement('div')

root.id = 'root'
document.body.appendChild(root)

// Now we can render our application into it
render(<App />, document.getElementById('root'))

And for good measure, my webpack.dev.config.js

const webpack = require('webpack')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { spawn } = require('child_process')

// Any directories you will be adding code/files into, need to be added to this array so webpack will pick them up
const defaultInclude = path.resolve(__dirname, 'src')

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          { loader: 'style-loader' },
          { loader: 'css-loader' },
          { loader: 'postcss-loader' },
        ],
        include: defaultInclude,
      },
      {
        test: /\.jsx?$/,
        use: [{ loader: 'babel-loader' }],
        include: defaultInclude,
      },
      {
        test: /\.(jpe?g|png|gif)$/,
        use: [{ loader: 'file-loader?name=img/[name]__[hash:base64:5].[ext]' }],
        include: defaultInclude,
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        use: [
          { loader: 'file-loader?name=font/[name]__[hash:base64:5].[ext]' },
        ],
        include: defaultInclude,
      },
    ],
  },
  target: 'electron-renderer',
  plugins: [
    new HtmlWebpackPlugin({ title: 'Newtelco Billing Parser' }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development'),
    }),
  ],
  devtool: 'cheap-source-map',
  devServer: {
    contentBase: path.resolve(__dirname, 'dist'),
    stats: {
      colors: true,
      chunks: false,
      children: false,
    },
    before() {
      spawn('electron', ['.'], {
        shell: true,
        env: process.env,
        stdio: 'inherit',
      })
        .on('close', code => process.exit(0))
        .on('error', spawnError => console.error(spawnError))
    },
  },
}

As you can see, its mostly unchanged from this packages defaults.

I've done a bunch of googling and experimenting, but unfortunately im no webpack sensei haha. Any idea how I can get this to build?

Thanks!

Error building package

➜ npm run package

> [email protected] package /home/saleh/Projects/open_sources/locky/locky_desktop
> npm run build


> [email protected] build /home/saleh/Projects/open_sources/locky/locky_desktop
> cross-env NODE_ENV=production webpack --config webpack.build.config.js --mode production

Hash: 9f5a6cf59b0e19e4ddc5
Version: webpack 4.44.0
Time: 4591ms
Built at: 07/29/2020 8:57:26 PM
 2 assets
Entrypoint main = bundle.css main.js

ERROR in unknown: Unexpected token (22748:6)
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] build: `cross-env NODE_ENV=production webpack --config webpack.build.config.js --mode production`
npm ERR! Exit status 2
npm ERR! 
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/saleh/.npm/_logs/2020-07-29T16_27_26_936Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] package: `npm run build`
npm ERR! Exit status 2
npm ERR! 
npm ERR! Failed at the [email protected] package script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/saleh/.npm/_logs/2020-07-29T16_27_27_111Z-debug.log

HtmlWebpackPlugin option nodeModules working?

in the webpack dev config I found that the HtmlWebpackPlugin use one arg called nodeModules, but I can not find the explanation from HtmlWebpackPlugin docs, I even searched the HtmlWebpackPlugin source code but didn't find anything ? can anyone explain to me how this nodeModules option works ?

how to reference images?

I'm having an issue figuring out how to reference src image

<img src="img/logo.png" class="img-fluid" alt="Responsive image" />

I'm placing logo.png in src/assets/img, can't get it to work, any ideas?

Bootstrap

I'm trying to import bootstrap css
import 'bootstrap/dist/css/bootstrap.min.css';
and it gave me error. Can you have a look at it please ? I'm pretty new to frontend so I have no idea.
Thank you for the boilerplate btw. Looking for this for so long

Express, Sequelize and SQLite3

Hi @alexdevero,
Thank you so much for the boilerplate. Its AWESOME!!!

I started working on an Electron app with your boilerplate, and now, I need a database to store and retrieve data.
I have SQLite3 as my db, Sequelize as ORM and Express server for fetching the data via local API's

I am running the server separately as below, using concurrently library, but I am not sure if this solution is a good one.

"start:app": "cross-env NODE_ENV=development webpack serve --hot --host 0.0.0.0 --config=./webpack.dev.config.js",
"start:api": "node server.js",
"start": "concurrently \"npm run start:app\" \"npm run start:api\"",

Is there any better way to run the application using a single command?
Also, how can I use the same, when I build the project?

which is the renderer js file?

newbie question - I want to use IPC communication between main js and the react app/renderer.
is there a specific renderer file which is connected to the index.html file being created by webpack? can I make one somehow?
some pointers will be really apreciated

Change window title

Hello,
How can I change the title of the window? It seems that it always changes automatically to "Webpack App" regardless the title: option and the setTitle method.

BTW, great boilerplate!

Can not change main page font size

Hİ,
I can not change the main page inspector and menu panel font size.
At createWindow method , I added defaultFontSize under the WebReferences tag. But it was not changed anything.

Could you please help me?

image

tailwind css

I am trying to use tailwind css. I have followed the tailwind install guide over here.

I followed the "Add Tailwind as a PostCSS plugin" section and added. this to

postcss.config.js


module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }
}

now my config look like this

module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
    'postcss-import': {},
    'postcss-nested': {},
    'postcss-preset-env': {},
    'postcss-pxtorem': {
      rootValue: 16,
      unitPrecision: 5,
      propList: ['*'],
      selectorBlackList: ['html', 'body'],
      replace: true,
      mediaQuery: false,
      minPixelValue: 0,
    },
  },
};

I also added the directives to App.scss

/* Main CSS file */

@import '_example/_example.css';
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

but it is still not working. I did follow your "Add Sass" section btw

ASAR build

The project right now cannot be used to generate Electron ASAR distribution file.
If i'm using npm run build it's only generating main.js which is the entire project (it supposed to be bundle.js) for render process and there is no JS file for the main Electron process.

Any suggestions?

Thanks!

SCSS Images

Imagens into de SCSS files doesn't load...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.