Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to correctly load .pcss - postcss files with webpack? #580

Closed
raphael10-collab opened this issue May 7, 2022 · 13 comments
Closed

How to correctly load .pcss - postcss files with webpack? #580

raphael10-collab opened this issue May 7, 2022 · 13 comments

Comments

@raphael10-collab
Copy link

raphael10-collab commented May 7, 2022

As described in this Stackoverflow post : https://stackoverflow.com/questions/72118482/how-to-correctly-load-pcss-postcss-files-with-webpack, I'm having problems of loading .pcss files with webpack

Packages installed :

"postcss": "^8.4.13",
"postcss-flexbugs-fixes": "^5.0.2",
"postcss-loader": "^6.2.1",
"extract-text-webpack-plugin": "^3.0.2"

 "webpack": "^5.23.0",
 "webpack-bundle-analyzer": "^4.4.0",
 "webpack-cli": "^4.5.0"

In webpack.config.js file :

        {
          test: /\.pcss$/,
          use: [
              //{
                  //loader: 'style-loader',
              //},
              //{
                  //loader: 'css-loader',
                  //options: {
                      //sourceMap: true,
                  //},
              //},
              { // https://github.com/webpack-contrib/postcss-loader#getting-started
                  loader: 'postcss-loader',
                  options: {
                      //config: {
                        //path: `${__dirname}/postcss.config.js`,
                      //},
                      postcssOptions: {
                        plugins: [
                          "postcss-preset-env",
                        ],
                      },
                      //sourceMap: true,
                  },
              },
          ],
        },

But it still says:

ERROR in ./src/assets/css/rssfeeds/app.pcss 9:0
Module parse failed: Unexpected token (9:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| html,
| body,
> #app {
|     min-height: 100vh;
| }

I tried also in this way in webpack.config.js :

const extractPCSS = new ExtractTextPlugin('../css/[name].css');

    {
      test: /\.pcss$/,

      // https://stackoverflow.com/questions/46865384/postcss-with-webpack?rq=1
      use: extractPCSS.extract([ 'css-loader', 'postcss-loader' ])
    }

But I still get this error:

ERROR in ./src/assets/css/rssfeeds/app.pcss 9:0
Module parse failed: Unexpected token (9:0)
You may need an appropriate loader to handle this file type, 
currently no loaders are configured to process this file

The postcss file is:

html,
body,
#app {
    min-height: 100vh;
}

div[role='menu'] {
    outline: none;
}

div[role='menuitem'] {
    outline: none;
}

input:focus {
    outline: none;
}

[role='button']:focus {
    outline: none;
}

[role='menuitemradio']:focus {
    outline: none;
}

.thin-scroll {
    @apply overflow-y-scroll;
}

.thin-scroll::-webkit-scrollbar {
    @apply bg-transparent w-2;
}

.thin-scroll::-webkit-scrollbar-thumb {
    @apply bg-gray-500 rounded-lg border-4 border-transparent bg-clip-content;
}

.rss-item {
    @apply leading-8 text-gray-300 flex items-center justify-between cursor-pointer px-3 py-2;
}

.rss-item.active {
    @apply bg-gray-600;
}

Other info:

node: v16.15.0
O.S.: Ubuntu 20.04 Desktop

How to solve the problem?

@alexander-akait
Copy link
Member

You have problems with configuration and no one loader was applied, please provide full configuration or reproducible test repo and I will show how to fix

@raphael10-collab
Copy link
Author

raphael10-collab commented May 7, 2022

Hi!

This is the complete webpack.config.js file :

const path = require('path');
const cwd = process.cwd();
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyPlugin = require("copy-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpack = require('webpack');
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')

const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractPCSS = new ExtractTextPlugin('../css/[name].css');


// https://hackernoon.com/how-to-run-machine-learning-models-in-the-browser-using-onnx?source=rss

// https://github.com/Leaflet/Leaflet/issues/4849

//const sqlite3 = require('sqlite3');

//const RedisGraph = require("redisgraph.js").Graph;
//const RedisGraph = require("redisgraph.js");


// https://github.com/Devtography/electron-react-typescript-webpack-boilerplate/blob/master/webpack.config.js

function srcPaths(src) {
  return path.join(__dirname, src);
}

// Creates Webpack Aliases using CWD path
//const createWebpackAliases = (als) => {
  //const result = {};
  //for (const name in als) {
    //result[name] = path.join(cwd, als[name]);
  //}
  //return result;
//};

//const aliases = createWebpackAliases({
  //'@src': 'src',
  //'@app': 'src/app',
  //'@app_A': 'src/app_A',
  //'@app_B': 'src/app_B',
  //'@app_C': 'src/app_C',
  //'@app_D': 'src/app_D',
  //'@app_E': 'src/app_E',
  //'@app_F': 'src/app_F',
  //'@app_G': 'src/app_G',
  //'@app_webpdf': 'src/app_webpdf',
  //'@app_trial': 'src/lib/pdfjs-dist/web',
  //'@about': 'src/sections/about',
  //'@account': 'src/sections/Account/account',
  //'@static': 'src/static',
  //'@pdfviewer': 'src/lib/pdfjs-dist/web/viewer',
//});

const isEnvProduction = process.env.NODE_ENV === 'production';
const isEnvDevelopment = process.env.NODE_ENV === 'development';

  // main process
var main_config = {
    mode: isEnvProduction ? 'production' : 'development',
    entry: './src/main/main.ts',
    target: 'electron-main',
    resolve: {
      extensions: ['.jsx', '.js', '.ts', '.tsx', '.css', '.pcss'],
    },
    // https://github.com/slackapi/node-slack-sdk/issues/746#issuecomment-778804407
    externals: [
      {
        'utf-8-validate': 'commonjs utf-8-validate',
        bufferutil: 'commonjs bufferutil',
        //ort: 'ort',
      },
      //{
        //'sqlite3': sqlite3,
      //},
    ],
    module: {
      rules: [
        {
          test: /\.ts$/,
          include: /src/,
          use: [{ loader: 'ts-loader' }]
        },
        {
          // css files
          test: /\.(sass|less|css)$/i,
          use: [
            {
              loader: 'style-loader'
            },
            {
              loader: 'css-loader'
            },
            {
              loader: 'less-loader',
            },
            {
              loader: 'postcss-loader', 
            }
          ],
        },

        {
          test: /\.s?css$/,
          use: [
            {
              loader: MiniCssExtractPlugin.loader,
              options: {
                sourceMap: true
              }
            },
            {
              loader: 'css-loader',
              options: {
                sourceMap: true
              }
            },
            {
              loader: 'sass-loader',
              options: {
                sourceMap: true
              }
            }
          ]
        },
       {
          test: /\.pcss$/,

          // https://stackoverflow.com/questions/46865384/postcss-with-webpack?rq=1
          use: extractPCSS.extract([ 'css-loader', 'postcss-loader' ])
          //use: [
              //{
                  //loader: 'style-loader',
              //},
              //{
                  //loader: 'css-loader',
                  //options: {
                      //sourceMap: true,
                  //},
              //},
              //{ // https://github.com/webpack-contrib/postcss-loader#getting-started
                  //loader: 'postcss-loader',
                  //options: {
                      //config: {
                        //path: `${__dirname}/postcss.config.js`,
                      //},
                      //postcssOptions: {
                        //plugins: [
                          //"postcss-preset-env",
                        //],
                      //},
                      //sourceMap: true,
                  //},
              //},
          //],
        },

        {
          test: /\.(png|jpe?g|svg|gif)$/i,
          use: [
            {
              loader: "file-loader",
              options: {
                name: "[path]/[name].[ext]",
              },
            },
          ],
        },
        {
          test: /\.geojson$/,
           use: [
             {
               loader: "json-loader",
             }
          ],
        }
      ]
    },
    output: {
      path: __dirname + '/dist',
      filename: 'main.js'
    },
    node: {
      __dirname: false,
      __filename: false
    },
    experiments: {
      asyncWebAssembly: true,
      syncWebAssembly: true,
      topLevelAwait: true
    }
};

  // renderer process
var renderer_config =  {
    mode: isEnvProduction ? 'production' : 'development',
    entry: {
      // https://stackoverflow.com/questions/53477466/react-referenceerror-regeneratorruntime-is-not-defined
      app: ['./src/app/index.tsx', 'react-app-polyfill/stable'],
      app_A: './src/app_A/index_A.tsx',
      app_B: './src/app_B/index_B.tsx',
      app_C: './src/app_C/index_C.tsx',
      app_D: './src/app_D/index_D.tsx',
      app_E: './src/app_E/index_E.tsx',
      app_F: './src/app_F/index_F.tsx',
      app_G: './src/app_G/index_G.tsx',
      app_H: './src/app_H/index_H.tsx',
      app_webpdf: './src/app_webpdf/index_webpdf.tsx',
      infoBasket: './src/app/sections/infobasket/Infobasket.tsx',
      style: './src/app/styles/index.css',
      style_A: './src/app_A/styles/index.css',
      style_B: './src/app_B/styles/index.css',
      style_C: './src/app_C/styles/index.css',
      style_D: './src/app_D/styles/index.css',
      style_E: './src/app_E/styles/index.css',
      style_F: './src/app_F/styles/index.css',
      style_G: './src/app_G/styles/index.css',
      style_H: './src/app_H/styles/index.css',
      //style_leaflet: path.resolve(__dirname, 'node_modules/leaflet/dist/leaflet.css'),
      style_webpdf: './src/app_webpdf/styles/index.css'
    },
    //target: 'electron-renderer',
    //target: 'web',
    target: ['web', 'es5'],
    //node: {global: true, fs: 'empty'},
    resolve: {
      extensions: ['.jsx', '.js', '.ts', '.tsx', '.css', '.pcss'],
      //alias: {
        // Custom Aliases
        //...aliases,
      //},
    },
    output: {
      path: __dirname + '/dist/',
        //filename: 'renderer.js'
      filename: '[name].js',
    },
    // https://github.com/slackapi/node-slack-sdk/issues/746#issuecomment-778804407
    externals: [
      {
        'utf-8-validate': 'commonjs utf-8-validate',
        bufferutil: 'commonjs bufferutil',
        //ort: 'ort',
      },
      //{
        //'sqlite3': sqlite3,
      //},
      //{
        //'RedisGraph': RedisGraph,
      //},
    ],
    module: {
      rules: [
        {
          test: /\.(js|ts)x?$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
          },
        },
        {
          // css files
          test: /\.css$/i,
          use: [
            {
              loader: 'style-loader'
            },
            {
              loader: 'css-loader'
            },
          ],
        },
        {
          // Font files
          test: /\.(woff|woff2|ttf|otf)$/,
          loader: 'file-loader',
          options: {
            name: '[hash].[ext]',
            outputPath: 'dist/assets/css/'
          }
        },
        {
          // image files
          test: /\.(jpe?g|png|gif|svg)$/i,
          loader: 'file-loader',
          options: {
            name: '/pics/[name].[ext]',
            outputPath: 'dist/assets/pics/'
          }
        },
        {
          // epub files
          test:/\.epub$/i,
          loader: 'file-loader',
          exclude: /node_modules/,
        }
      ],
    },
    node: {
      __dirname: false,
      __filename: false
    },
    experiments: {
      asyncWebAssembly: true,
      syncWebAssembly: true,
      topLevelAwait: true
    },
        // filename: This is the cornerstone parameter, which distingues different html templates
        // Because for each template, html-webpack-plugin produces, if not otherwise specified in filename,
        // an index.html file.
    plugins: [
      new NodePolyfillPlugin({
        excludeAliases: ['console'],
      }),
      new HtmlWebpackPlugin({
        filename: 'index.html',
        template: './src/app/index.html',
        inject:'body',
        chunks: ['app'],
      }),
      new HtmlWebpackPlugin({
        filename: 'index_A.html',
        template: './src/app_A/index_A.html',
        inject: 'body',
        chunks: ['app_A']
      }),
      new HtmlWebpackPlugin({
        filename: 'index_B.html',
        template: './src/app_B/index_B.html',
        inject: 'body',
        chunks: ['app_B']
      }),
      new HtmlWebpackPlugin({
        filename: 'index_C.html',
        template: './src/app_C/index_C.html',
        inject: 'body',
        chunks: ['app_C']
      }),
      new HtmlWebpackPlugin({
        filename: 'index_D.html',
        template: './src/app_D/index_D.html',
        inject: 'body',
        chunks: ['app_D']
      }),
      new HtmlWebpackPlugin({
        filename: 'index_E.html',
        template: './src/app_E/index_E.html',
        inject: 'body',
        chunks: ['app_E']
      }),
      new HtmlWebpackPlugin({
        filename: 'index_F.html',
        template: './src/app_F/index_F.html',
        inject: 'body',
        chunks: ['app_F']
      }),
      new HtmlWebpackPlugin({
        filename: 'index_G.html',
        template: './src/app_G/index_G.html',
        inject: 'body',
        chunks: ['app_G']
      }),
      new HtmlWebpackPlugin({
        filename: 'index_H.html',
        template: './src/app_H/index_H.html',
        inject: 'body',
        chunks: ['app_H']
      }),
      new HtmlWebpackPlugin({
        filename: 'index_I.html',
        template: './src/app_I/index_I.html',
        inject: 'body',
        chunks: ['app_I']
      }),
      new HtmlWebpackPlugin({
        filename: 'index_webpdf.html',
        template: './src/app_webpdf/index_webpdf.html',
        inject: 'body',
        chunks: ['app_webpdf']
      }),
      new HtmlWebpackPlugin({
        filename: 'viewer.html',
        template: './src/lib/pdfjs-dist/web/viewer.html',
        inject: 'body',
        chunks: ['app_viewer']
      }),
      new HtmlWebpackPlugin({
        filename: 'index_trial.html',
        template: './src/app_A/index_trial.html',
        inject: 'body',
        chunks: ['index_trial']
      }),
      new MiniCssExtractPlugin({
        filename: '[name].css',
        chunkFilename: '[id].css',
        linkType: 'text/css',
      }),
      new MiniCssExtractPlugin({
        filename: './src/lib/conversejs/converse.css'
      }),
      new CopyPlugin({
        patterns: [
          {
            from: path.resolve(__dirname, "./src/lib"),
            to: path.resolve(__dirname, "./dist/lib")
          },
          {
            from: path.resolve(__dirname, "./src/assets/css"),
            to: path.resolve(__dirname, "./dist/assets/css")
          },
          {
            from: path.resolve(__dirname, "./src/assets/pics"),
            to: path.resolve(__dirname, "./dist/assets/pics")
          },
          {
            from: path.resolve(__dirname, "./src/assets/geojson"),
            to: path.resolve(__dirname, "./dist/assets/geojson")
          },
          {
            from: path.resolve(__dirname, "./src/assets/svg"),
            to: path.resolve(__dirname, "./dist/assets/svg")
          },
          {
            from: path.resolve(__dirname, "./src/assets/epub"),
            to: path.resolve(__dirname, "./dist/assets/epub")
          },
          {
            from: path.resolve(__dirname, "./node_modules/onnxruntime-web/dist/*.wasm"),
            to: path.resolve(__dirname, "[name][ext]")
          },
          {
            from: path.resolve(__dirname, "./src/assets/onnx-models"),
            to: path.resolve(__dirname, "./dist/assets/onnx-models")
          }
        ],
        options: {
          concurrency: 100,
        },
      }),
    ]
}

//module.exports = [ main_config, renderer_config];
module.exports = [
  main_config,
  renderer_config,
];

This is tsconfig.json file:

{
  "compilerOptions": {
    "typeRoots": ["./node_modules/@types"],
    "target": "es2021",
    "module": "commonjs",
    "lib": ["es2021"],
    "outDir": "dist",
    //"jsx": "react",
    "jsx": "react-jsx",
    "baseUrl": "./src",
    "paths": {
      "@sections/*": ["app/sections/*"],
      "@app/*": ["app/*"]
    },
    "strict": true,
    "sourceMap": true,
    "skipLibCheck": true,
    "noImplicitAny": false,
    "noImplicitThis": false,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "allowJs": true
  },
  "include": ["src/**/*"],
  "exclude": [
    "src/index.js",
    "dist",
  ]
}

babel.config.json file :

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "usage",
        "corejs": 3
      }
    ],
    "@babel/preset-react",
    "@babel/preset-typescript"
  ],
  "plugins": [
    "@babel/plugin-syntax-top-level-await",
    "@babel/proposal-class-properties",
    "@babel/proposal-object-rest-spread",
    ["@babel/plugin-transform-modules-commonjs", {
      "allowTopLevelThis": true
    }],
  ]
}

Please tell me if something else is missing in order to understand how to fix the problem
Thank you for helping

@alexander-akait
Copy link
Member

Can you put this in github repo? It will be easier to investigate

@alexander-akait
Copy link
Member

Also ExtractTextPlugin is deprecated and will not work with webpack v5, file-loader and url-loader also deprecatedin favor https://webpack.js.org/guides/asset-modules/, please do these migrations (also please look at migratuon guide for webpack v5)

@raphael10-collab
Copy link
Author

raphael10-collab commented May 7, 2022

I've created this github repo: https://github.com/raphael10-collab/PostcssLoaderElectronPlaying

Steps to reproduce:

  1. git clone https://github.com/raphael10-collab/PostcssLoaderElectronPlaying.git
  2. cd PostcssLoaderElectronPlaying/
  3. yarn
  4. in one screen: yarn type-check
  5. in a second screen: yarn start

In the webpack.config.js I tried to migrate from file-loader and url-loader to AssetModules. What I've done should be OK, but forgive me if if not 100% OK

pcss is imported here: https://github.com/raphael10-collab/PostcssLoaderElectronPlaying/blob/master/src/app/components/App.tsx#L7

@alexander-akait
Copy link
Member

Hello, sorry for delay, you don't have css-loader, do you want just convert pcss to css and emit CSS files or you want to handle CSS files as module, i.e. resolve url(...)/@import? For

  1. You need to use (setup postcss-loader/less-loader/etc) and type, so webpack will emit them as assets
  2. You need to setup css-loader and style-loader/mini-css-extract-plugin

@raphael10-collab
Copy link
Author

raphael10-collab commented May 18, 2022

Hi @alexander-akait !

Starting from the first option: I want just convert pcss to css and emit CSS files: You need to use (setup postcss-loader/less-loader/etc) and type, so webpack will emit them as assets :

I installed:
postcss-loader : "postcss-loader": "^6.2.1",
postcss-preset-env: "postcss-preset-env": "^7.5.0",
and installed
@types/postcss-import : "@types/postcss-import": "^14.0.0" , if this is what you meant with type

In webpack.config.js

    {
      test: /\.pcss$/,
      use: [
          { // https://github.com/webpack-contrib/postcss-loader#getting-started
              loader: 'postcss-loader',
              options: {
                  postcssOptions: {
                    plugins: [
                      "postcss-preset-env",
                    ],
                  },
                  //sourceMap: true,
              },
          },
      ],
    },

I still get this error message:

(base) raphy@pc:~/PostcssLoaderElectronPlaying$ yarn start
yarn run v1.22.18
$ yarn run build && ELECTRON_DISABLE_SECURITY_WARNINGS=true electron ./dist/main/main.js
$ npx webpack --config ./webpack.config.js
asset main.js 5.84 KiB [compared for emit] (name: main)
./src/main/main.ts 3.13 KiB [built] [code generated]
external "path" 42 bytes [built] [code generated]
external "electron" 42 bytes [built] [code generated]
webpack 5.72.1 compiled successfully in 3429 ms

assets by path assets/css/ 25.8 KiB
  asset assets/css/global.css 19.8 KiB [compared for emit] [from: src/assets/css/global.css] [copied]
  asset assets/css/App.scss 5.26 KiB [compared for emit] [from: src/assets/css/App.scss] [copied]
  asset assets/css/postcss/app.pcss 721 bytes [compared for emit] [from: src/assets/css/postcss/app.pcss] [copied]
assets by path *.js 2.12 MiB
  asset app.js 2.05 MiB [compared for emit] (name: app)
  asset style.js 68.9 KiB [compared for emit] (name: style)
asset index.html 607 bytes [compared for emit]
runtime modules 2.77 KiB 13 modules
modules by path ./node_modules/core-js/ 506 KiB 482 modules
modules by path ./src/ 25.7 KiB 6 modules
modules by path ./node_modules/leaflet/dist/ 22 KiB 5 modules
modules by path ./node_modules/react-dom/ 1000 KiB 3 modules
modules by path ./node_modules/css-loader/dist/runtime/*.js 2.91 KiB 3 modules
modules by path ./node_modules/react/ 85.5 KiB
  ./node_modules/react/index.js 190 bytes [built] [code generated]
  ./node_modules/react/cjs/react.development.js 85.4 KiB [built] [code generated]
modules by path ./node_modules/scheduler/ 17.3 KiB
  ./node_modules/scheduler/index.js 198 bytes [built] [code generated]
  ./node_modules/scheduler/cjs/scheduler.development.js 17.1 KiB [built] [code generated]
./node_modules/react-app-polyfill/stable.js 433 bytes [built] [code generated]
./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js 6.67 KiB [built] [code generated]
./node_modules/regenerator-runtime/runtime.js 24.3 KiB [built] [code generated]

ERROR in ./src/assets/css/postcss/app.pcss 1:0
Module parse failed: Unexpected character '@' (1:0)
File was processed with these loaders:
 * ./node_modules/postcss-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
> @tailwind base;
| 
| @tailwind components;
 @ ./src/app/components/App.tsx 12:0-44
 @ ./src/app/index.tsx 7:34-61

webpack 5.72.1 compiled with 1 error in 4409 ms
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
(base) raphy@pc:~/PostcssLoaderElectronPlaying$ 

What am I missing? And what do I have to fix in webpack.config.js ?

@alexander-akait
Copy link
Member

Use:

const path = require('path');
const cwd = process.cwd();
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyPlugin = require("copy-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpack = require('webpack');


function srcPaths(src) {
  return path.join(__dirname, src);
}

const isEnvProduction = process.env.NODE_ENV === 'production';
const isEnvDevelopment = process.env.NODE_ENV === 'development';

  // main process
var main_config = {
    mode: isEnvProduction ? 'production' : 'development',
    entry: './src/main/main.ts',
    target: 'electron-main',
    resolve: {
      extensions: ['.jsx', '.js', 'ts'],
    },
    externals: [
      {
        'utf-8-validate': 'commonjs utf-8-validate',
        bufferutil: 'commonjs bufferutil',
      },
    ],
    module: {
      rules: [
        {
          test: /\.ts$/,
          include: /src/,
          use: [{ loader: 'ts-loader' }]
        },
        {
          test: /\.(sass|less|css)$/i,
          type: 'asset',
          generator: {
            outputPath: 'dist/assets/css/'
          },
        },
        {
          test: /\.s?css$/,
          type: 'asset',
          generator: {
            outputPath: 'dist/assets/css/'
          },
        },


        {
          test: /\.pcss$/,
          type: 'asset',
          use: [
              { // https://github.com/webpack-contrib/postcss-loader#getting-started
                  loader: 'postcss-loader',
                  options: {
                      postcssOptions: {
                        plugins: [
                          "postcss-preset-env",
                        ],
                      },
                      //sourceMap: true,
                  },
              },
          ],
        },


        {
          test: /\.(svg)$/i,
          type: 'asset',
          generator: {
            outputPath: 'dist/assets/svg/'
          },
        },
        {
          test: /\.(png|jpe?g|gif)$/i,
          type: 'asset',
          generator: {
            outputPath: 'dist/assets/pics/'
          },
        },

        {
          test: /\.geojson$/,
           use: [
             {
               loader: "json-loader",
             }
          ],
        }
      ]
    },
    output: {
      path: __dirname + '/dist',
      filename: 'main.js'
    },
    node: {
      __dirname: false,
      __filename: false
    },
};

  // renderer process
var renderer_config =  {
    mode: isEnvProduction ? 'production' : 'development',
    entry: {
      app: ['./src/app/index.tsx', 'react-app-polyfill/stable'],
      style: [
        './src/app/styles/index.css',
        path.resolve(__dirname, 'node_modules/leaflet/dist/leaflet.css')
      ]
    },
    //target: 'electron-renderer',
    //target: 'web',
    target: ['web', 'es5'],
    resolve: {
      extensions: ['.jsx', '.js', '.tsx', '.ts'],
    },
    output: {
      path: __dirname + '/dist/',
      	//filename: 'renderer.js'
      filename: '[name].js',
    },
    externals: [
      {
        'utf-8-validate': 'commonjs utf-8-validate',
        bufferutil: 'commonjs bufferutil',
      },
    ],
    module: {
      rules: [
        {
          test: /\.(js|ts)x?$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
          },
        },
        {
          // css files
          test: /\.css$/i,
          use: [
            {
              loader: 'style-loader'
            },
            {
              loader: 'css-loader'
            },
          ],
        },

        {
          test: /\.pcss$/,
          use: [
            {
              loader: 'style-loader'
            },
            {
              loader: 'css-loader'
            },
            { // https://github.com/webpack-contrib/postcss-loader#getting-started
                  loader: 'postcss-loader',
                  options: {
                      //config: {
                        //path: `${__dirname}/postcss.config.js`,
                      //},
                      postcssOptions: {
                        plugins: [
                          "postcss-preset-env",
                        ],
                      },
                      //sourceMap: true,
                  },
            },
          ],
        },

        {
          test: /\.(svg)$/i,
          type: 'asset',
          generator: {
            outputPath: 'dist/assets/svg/'
          },
        },
        {
          test: /\.(png|jpe?g|gif)$/i,
          type: 'asset',
          generator: {
            outputPath: 'dist/assets/pics/'
          },
        },
        {
          // Font files
          test: /\.(woff|woff2|ttf|otf)$/,
          type: 'asset',
          generator: {
            outputPath: 'dist/assets/css/'
          },
        },
      ],
    },
    node: {
      __dirname: false,
      __filename: false
    },
    plugins: [
      new HtmlWebpackPlugin({
        filename: 'index.html',
        template: './src/app/index.html',
        inject:'body',
        chunks: ['app'],
      }),
      new MiniCssExtractPlugin({
        filename: '[name].css',
        chunkFilename: '[id].css',
        linkType: 'text/css',
      }),
      new CopyPlugin({
        patterns: [
          {
            from: path.resolve(__dirname, "./src/assets/css"),
            to: path.resolve(__dirname, "./dist/assets/css")
          },
        ],
        options: {
          concurrency: 100,
        },
      }),
    ]
}

module.exports = [
  main_config,
  renderer_config,
];

@alexander-akait
Copy link
Member

Note I found MiniCssExtractPlugin, if you need to extract, you should not use style-loader and use mini-css-extract-plugin loader, here is recommended configuration https://github.com/webpack-contrib/mini-css-extract-plugin#recommended

@alexander-akait
Copy link
Member

alexander-akait commented May 18, 2022

Also copying assets without compiling them in in main_config is not valid, you will get pcss and sass files as is, without resolving @import and url(...), there are a lot of infromation in readme and examples, also electron has recomended webpack configuration, so I recommend to use it instead to write it from scratch

@alexander-akait
Copy link
Member

https://webpack.electron.build/configuration

@raphael10-collab
Copy link
Author

Thank you very much for your very kind help @alexander-akait

i'm going to dive now into https://webpack.electron.build/configuration , in order to understand how to transpose my configuration to a more standard one

@raphael10-collab
Copy link
Author

Unfortunately electron-webpack has issues as well: when upgrading to webpack 5 it breaks : electron-userland/electron-webpack-quick-start#119

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants