اذهب إلى المحتوى

عبد النور محمد

الأعضاء
  • المساهمات

    95
  • تاريخ الانضمام

  • تاريخ آخر زيارة

أجوبة بواسطة عبد النور محمد

  1. أقوم أولاً بإحضار جميع المنشورات والمؤلفين من ContentfulAPI ، ثم أقوم بعمل تكرار لهم لإنشاء مسار صالح لتمريره إلى مصفوفة المسارات

    export const getStaticPaths = async () => {
    
      const posts = await DataController.getEntriesByContentType(
        "componentBlog",
      );
    
      const blogPosts = posts.items.map(item => {
        return {params: {blog_post: [item.fields.category.replace(/\s+/g, '-').replace(/'/g, '').toLowerCase(), item.fields.slug]}}
      })
    
      const authors = await DataController.getEntriesByContentType(
        "author",
      );
    
      const authorPaths = authors.items.map(item => {
        return {params: {blog_post: ['author', item.fields.slug]}}
      })
    
      return {
        
        paths: [
          blogPosts,
          authorPaths,
        ],
        fallback: false,
      }
    }

    وقد تلقيت هذا الخطأ عندما أحاول الوصول إلى رابط مدونة

    error - Error: Additional keys were returned from `getStaticPaths` in page "/blog/[...blog_post]". URL Parameters intended for this dynamic route must be nested under the `params` key, i.e.:
    
            return { params: { blog_post: ... } }
    
    Keys that need to be moved: 0, 1, 2, 3, 4, 5, 6, 7, 8.
    
        at C:\Workspace\phoenix-v2\next\new-phoenix\node_modules\next\dist\build\utils.js:518:23
        at Array.forEach (<anonymous>)
        at Object.buildStaticPaths (C:\Workspace\phoenix-v2\next\new-phoenix\node_modules\next\dist\build\utils.js:492:17)    at processTicksAndRejections (internal/process/task_queues.js:95:5) {
      type: 'Error',
      page: '/blog/[...blog_post]'

     

    • أعجبني 2
  2. لدي مشكلة في الحصول على البيانات وتعيينها في localStorage  فأنا أستخدم NextJs لذا لا يمكنني استخدام localStorage في البداية.

    أحاول حل المشكلة باستخدام useEffect لكن لدي حلقة لا نهائية  لا أعرف أفضل طريقة لحل المشكلة ، باستخدام useCallback أو useMemo أو useRef.

          const [ meetings, setMeetings] = useState([]) // meetings= [{meeting1},{meeting2}]
          
          useEffect(() => {
    
           if(localStorage.getItem('meetings') === undefined || 
             localStorage.getItem('meetings') === '' ||
             localStorage.getItem('meetings') === null
             ){
              localStorage.setItem('meetings', JSON.stringify([]))         
             }
    
    
           if( JSON.parse(localStorage.getItem('meetings')).length === 0){
                
                 const meetingsInLocalStorage  = JSON.parse(localStorage.getItem('meetings'))
                 setMeetings([...meetings, meetingsInLocalStorage])
    
           }
           },[meetings])

     

    • أعجبني 2
  3. أواجه الكثير من المشاكل في الحصول على أيقونات bootstrap للعمل معwebpack

    ERROR in ./node_modules/bootstrap-icons/font/bootstrap-icons.css 1:0
    Module parse failed: Unexpected character '@' (1: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
    > @font-face {
    |   font-family: "bootstrap-icons";
    |   src: url("./fonts/bootstrap-icons.woff2?856008caa5eb66df68595e734e59580d") format("woff2"),
     @ ./src/index.js 3:0-50

    webpack.config.js

        {
            test: /\.((png)|(eot)|(woff)|(woff2)|(ttf)|(svg)|(gif))(\?((v=\d+\.\d+\.\d+)|(\w*)))?$/,
            use: { loader: "file-loader?name=/[hash].[ext]" }
          },
          ...
    
          {
            test: /\.(sa|sc|c)ss$/,
            exclude: /node_modules/,
            use: [
              "style-loader",
              MiniCssExtractPlugin.loader,
              "css-loader",
              "postcss-loader",
              "sass-loader"
            ]
          }

    js 

    import "./scss/main.scss";
    import "bootstrap-icons/font/bootstrap-icons.css";
    webpack: "5.52.1",
    "bootstrap-icons": "^1.5.0",
    "file-loader": "^6.2.0",

     

  4. لقد قمت حرفياً بإنشاء مشروع  nextjs عبر   npx create-next-app ولم أغير شئ لكن ينفتح بخطأ مباشرة 

    (node:7636) [DEP_WEBPACK_MODULE_ISSUER] DeprecationWarning: Module.issuer: Use new ModuleGraph API
    (Use `node --trace-deprecation ...` to show where the warning was created)
    error - ./styles/globals.css
    Global CSS cannot be imported from files other than your Custom <App>. Due to the Global nature of stylesheets, and to avoid conflicts, Please move all first-party global CSS imports to pages/_app.js. Or convert the import to Component-Level CSS (CSS Modules).
    Read more: https://nextjs.org/docs/messages/css-global
    Location: pages\_app.js

     

    • أعجبني 1
  5. أحاول استظافة مشروع nextjs في vercel لكن لم ينجح الأمر و ظهر لي خطأ في ال build

    next-config.js

    module.exports = {
      typescript: {
      
        ignoreBuildErrors: true,
      },
    };
    10:23:27.575    Cloning github.com/lawderp/physical (Branch: main, Commit: 8f97554)
    10:23:28.589    Cloning completed: 1.014s
    10:23:28.614    Analyzing source code...
    10:23:29.739    Installing build runtime...
    10:23:31.612    Build runtime installed: 1.873s
    10:23:34.043    Looking up build cache...
    10:23:34.164    Build cache found. Downloading...
    10:23:35.100    Build cache downloaded [21.48 MB]: 936.007ms
    10:23:36.250    Installing dependencies...
    10:23:36.489    yarn install v1.22.11
    10:23:36.547    [1/4] Resolving packages...
    10:23:36.734    success Already up-to-date.
    10:23:36.743    Done in 0.26s.
    10:23:36.754    Detected Next.js version: 11.1.2
    10:23:36.755    Running "yarn run build"
    10:23:37.021    yarn run v1.22.11
    10:23:37.047    $ next build
    10:23:37.820    info  - Using webpack 5. Reason: Enabled by default https://nextjs.org/docs/messages/webpack5
    10:23:37.976    info  - Skipping validation of types...
    10:23:40.439    error Command failed with exit code 1.
    10:23:40.439    info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
    10:23:40.456    Error: Command "yarn run build" exited with 1

     

    • أعجبني 1
  6. يقوم برنامج تحميل الملفات بإنشاء صورتين منفصلتين في مجلد الإنشاء الخاص بي. أحدهما هو الاسم الصحيح ويتم حفظه في المسار الصحيح ، والآخر  يتم تخزينه في الإنشاء وليس البناء و هو 0 بايت هذا هو الملف الذي يتم ربطه في ملف index.html النهائي في مجلد البناء. لقد حددت كلاً من outputPath و publicPath. يبدو أن publicPath لا تفعل أي شيء في الواقع ، بغض النظر عما أضعه هناك. هل أنا أسيء فهم ما يفعله؟

    module.exports = {
        entry: {
            index: './app/main.js',
            vendor: './app/vendor.js'
        },
        output: {
            path: path.resolve(__dirname, './build'),
            filename: '[name].[contenthash].js',
        },
        module: {
            rules: [
                {
                    test: /\.js$/,
                    exclude: [/node_modules/, /api/, /tests/, /coverage/],
                    use: 'babel-loader'
                },
                {
                    test: /\.scss$/,
                    use: ['style-loader', 'css-loader', 'sass-loader']
                },
                {
                    test: /\.html$/,
                    use: 'html-loader'
                },
                {
                    test: /\.(svg|png|jpg|gif)$/,
                    use:{
                        loader: 'file-loader',
                        options: {
                            name: '[name].[hash].[ext]',
                            outputPath: 'images/',
                            publicPath: 'images/'
                        }
                    }
                },
            ]        
        },
        plugins: [
            new HtmlWebpackPlugin({ template: './app/index.html' }), 
            new CleanWebpackPlugin()
        ]
    };
    <img src="465107fe07e3ec18a463.png">

     

    • أعجبني 2
  7. لا يمكنني تشغيل خدمة webpack

    const webpack = require('webpack')
    const path = require('path')
    const HtmlWebpackPlugin = require('html-webpack-plugin')
    const { CleanWebpackPlugin } = require('clean-webpack-plugin')
    
    module.exports = {
        mode: 'development',
        devServer: {
            historyApiFallback: true,
            contentBase: path.resolve(__dirname, './dist'),
            open: true,
            compress: true,
            hot: true,
            port: 8080,
            allowedHosts: 'all',
        },
        entry: {
            main: path.resolve(__dirname, './src/index.js'), // точка входа приложения
        },
        output: {
            path: path.resolve(__dirname, './dist'), // точка выхода приложения, директория
            filename: '[name].bundle.js',
        },
        plugins: [
            new HtmlWebpackPlugin({
                title: 'webpack Boilerplate',
                template: path.resolve(__dirname, './src/template.html'), // шаблон
                filename: 'index.html', // название выходного файла
            }),
            new CleanWebpackPlugin(),
            new webpack.HotModuleReplacementPlugin(),
        ],
        module: {
            rules: [...],
        }
    }

    الخطأ

    skif@PC:~/WebstormProjects/webpack-tutorial$ yarn start
    yarn run v1.22.5
    $ webpack serve
    [webpack-cli] Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
     - options has an unknown property 'contentBase'. These properties are valid:
       object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, magicHtml?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, setupExitSignals?, static?, watchFiles?, webSocketServer? }
    error Command failed with exit code 2.
    info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
    skif@PC:~/WebstormProjects/webpack-tutorial$ 

     

  8. لقد اتبعت برنامجًا تعليميًا حول NextJS وحاولت الآن تعديله قليلاً. أردت تضمين ملف data.json في الصفحة. لكنني أتلقى دائمًا رسالة الخطأ 

    Unexpected token < in JSON at position 0

    أعلم أنه يجب علي تحويل ملف JSON إلى سلسلة نصية  كيف علي أن أفعل ذلك؟

      let res = await fetch(`${server}/data`);
      const articles = await res.json();
    
      return {
        props: {
          articles,
        },
      };
    }

     

    • أعجبني 1
  9. أحاول اكتشاف طريقة مناسبة لإجراء المصادقة و المصادقة الخاصة بي بسيطة أقوم بتخزين رمز JWT في session أرسله إلى خادم مختلف للموافقة عليه. إذا عدت إلى true فإننا نستمر  إذا عدت false  فإنه يمسح session ويذهب في الصفحة الرئيسية.

    function isAuthenticated(req, res, next) {
      //checks go here
    
      //if (req.user.authenticated)
       // return next();
    
     
      res.redirect('/');
    }
    
    server.get('/p/:id', isAuthenticated, (req, res) => {
      const actualPage = '/post'
      const queryParams = { id: req.params.id }
      app.render(req, res, actualPage, queryParams)
    })

    هذا يعمل على النحو المصمم. إذا قمت بتحديث الصفحة / p / 123 ، فستتم إعادة التوجيه إلى /. ومع ذلك ، إذا ذهبت إلى هناك عبر Link فلن يحدث ذلك  الذي أعتقد أنه لا يستخدم express في هذه المرحلة ولكن التوجيه المخصص ل next.

    هل هناك طريقة يمكنني من خلالها إجراء فحص لكل  انتقال ل Link  أتمكن من التأكد من تسجيل المستخدم للدخول؟

    • أعجبني 1
  10. أحاول تحويل صور jpeg الخاصة بي إلى تنسيق الويب باستخدام المكون الإضافي image-webpack-loader في Webpack .

    يعمل التكوين التالي على تصغير ملفاتي بنجاح ولكنه لا يحولها إلى صور webp.

    test: /\.(gif|png|jpe?g|svg)$/i,
    loader: 'image-webpack-loader',
    options: {
       disable: true, //bypassOnDebug
       convertPathData: false,
       mozjpeg: { //works
          progressive: true,
          quality: '80-90'
        },
       webp: {
          quality: 75,
          enabled: true
       }
     }

     

    • أعجبني 3
  11. أحاول تنفيذ دالة updateOne من Mongodb على NEXTJS. ولكن لا يتم تحديثه ، من console.log (req.body) يمكن الحصول على المعلومات.

    handler.patch(async (req, res) => {
      if (!req.user) {
        res.status(401).end();
        return;
      }
      const { name, bio } = req.body;
      await req.db.collection('users').updateOne(
        { _id: req.user._id },
        {
          $set: {
            ...(name && { name }),
            bio: bio || '',
          },
        },
      );
      res.json({ user: { name, bio } });
    });

    console.log(req.body)

    Content-Disposition: form-data; name="name"
    
    Firstname Lastname
    ------WebKitFormBoundaryPwuAfw4FvUzDe8uP
    Content-Disposition: form-data; name="bio"
    
    xx
    ------WebKitFormBoundaryPwuAfw4FvUzDe8uP--

     

    • أعجبني 1
  12. أنا أستخدم المسارات التالية لدي تسجيل دخول وعندما تحدث مشكلة  أرجع 401 ونص الرسالة التي أود عرضها للمستخدمين.

    Api: /api/v1/auth/signin.js

    export default async (req, res) => {
    const { name, password } = req.body;
    const url = process.env.SH_API_BASEURL + 'auth/signin';
    console.log(url);
    
    try {
        const resp = await axios.patch(url, { name, password });
        return res.status(200).send(resp.data);
    } catch (err) {
        const { response } = err;
        const status = response.status;
        const message = response.data.errors[0].message;
        console.log(`status: ${status}, message ${message}`);
        return res.status(status).send(message);
    }
    };

    Pages /pages/auth/signin.js

    const handleFormSubmit = async (formData, e) => {
        e.preventDefault();
        try {
            const res = await axios.post('/api/v1/auth/signin', formData);
            
    
            router.push('/secure/home');
        } catch (err) {
            console.log('pages auth in error');
            console.log(err);
            setSubmitError(true);
            console.log('sigin handle submit error');
            
        }
    };

    console.log(err) تعرض ه>ا الخطا

    Error: Request failed with status code 401
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:62)

    كيف يمكنني الوصول إلى statuscode ونص الخطأ في كود الصفحات؟

    • أعجبني 1
  13. الكثير من مطورين المدونات يستخدمون markdown في كتابة التدوينات لذا قررت تجربته وقد أنشات مكون بسيط و استخدمت react markdown للعرض لكن كنت أتسائل عن كيفية عرض الصورة داخل ال markdown بالمكون Image الخاص ب nextjs بدلا من معالجته مباشرة الى html 

    import React from 'react'
    import ReactDom from 'react-dom'
    import ReactMarkdown from 'react-markdown'
    import remarkGfm from 'remark-gfm'
    
    const markdown = `
    ---
    title: "test post"
    date: "June 24 2021"
    excerp: "this is the excerp"
    cover_image: "/images/posts/img1.jpeg"
    ---
    
    ## Heading Two
    
    - Item 1
    - Item 2
    - Item 3
    
    Hello world
    
    ![Image 1](/images/posts/img1.jpeg)`
    
    ReactDom.render(
      <ReactMarkdown children={markdown} remarkPlugins={[remarkGfm]} />,
      document.body
    )

     

    • أعجبني 1
  14. لدي الملف document.js_ 

    import Document, { Head, Main, NextScript } from "next/document";
    // Import styled components ServerStyleSheet
    import { ServerStyleSheet } from "styled-components";
    
    export default class MyDocument extends Document {
      static getInitialProps({ renderPage }) {
        // Step 1: Create an instance of ServerStyleSheet
        const sheet = new ServerStyleSheet();
    
        // Step 2: Retrieve styles from components in the page
        const page = renderPage(
          (App) => (props) => sheet.collectStyles(<App {...props} />)
        );
    
        // Step 3: Extract the styles as <style> tags
        const styleTags = sheet.getStyleElement();
    
        // Step 4: Pass styleTags as a prop
        return { ...page, styleTags };
      }
    
      render() {
        return (
          <html>
            <Head>
              <title>My app</title>
              {/* Step 5: Output the styles in the head  */}
              {this.props.styleTags}
            </Head>
            <body>
              <Main />
              <NextScript />
            </body>
          </html>
        );
      }
    }

    عندما أعمل build أحصل على هذا الخطأ رغم ان الملف في مجلد pages

    3:1  Error: next/document should not be imported outside of pages/_document.js. 
    See https://nextjs.org/docs/messages/no-document-import-in-page.  @next/next/no-document-import-in-page
    13:38  Error: Component definition is missing display name  react/display-name

     

    • أعجبني 1
  15. لدي مشروع هيكلته كالاتي 

    assets
    node_modules
    src
    package.json
    package-lock.json
    webpack.config.js

    وهذا اعدادات webpack

    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const CleanWebpackPlugin = require('clean-webpack-plugin');
    const webpack = require('webpack');
    
    module.exports = {
      entry: {
        app: './src/index.js'
      },
      devServer: {
        // contentBase: './dist',
        contentBase: __dirname + "/assets/",
        hot: true,
      },
      plugins: [
        new CleanWebpackPlugin(['dist']),
        new HtmlWebpackPlugin({
          title: 'Output Management'
        }),
        new webpack.NamedModulesPlugin(),
        new webpack.HotModuleReplacementPlugin()
      ],
      output: {
        path: __dirname + "/assets/",
        filename: 'bundle.js',
        chunkFilename: '[name].js'
      },
    };

    ولدي هذا الخطا داخل أدوات المطور

    Content not from webpack is served from C:\Users\PC-user\WebstormProjects\untitled/assets/
    

     

    • أعجبني 2
  16. لدي مشروع مكتمل والأن أريد التحويل من بيئة التطوير لبيئة ال production ليصبح الموقع اسرع كيف يمكنني ذلك

    const webpack = require('webpack');
    
    const config = {
      entry: ['babel-polyfill', './src/index.js'],
      output: {
        filename: 'bundle.js',
      },
      devServer: {
        inline: true,
        port: 8080,
        historyApiFallback: true,
      },
      plugins: [
        new webpack.DefinePlugin({
          'process.env': {
            API_KEY: 'API_KEY',
            GOOGLE_MAPS_KEY: 'GOOGLE_MAPS_KEY',
            GOOGLE_GEOLOCATION_KEY: 'GOOGLE_GEOLOCATION_KEY',
          },
        }),
      ],
      module: {
        loaders: [
          {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
              presets: ['es2015', 'react'],
            },
          },
          {
            test: /\.css$/,
            loader: 'style!css',
          },
        ],
      },
    };
    
    module.exports = config;

     

    • أعجبني 2
  17. هذا هو الموديل الخاص بي

    import mongoose from 'mongoose'
    
    const flashcardItemSchema = new mongoose.Schema({
        term: {
            type:String,
            required: true,
            min:1
        },
        description: {
            type:String,
            required:true,
            min:1
        }
    });
    const FlashcardItem = mongoose.model("flashcardItem", flashcardItemSchema);
    
    const flashcardSetSchema = new mongoose.Schema({
        title: {
            type: String,
            min: 1,
        },
        flashcards:[flashcardItemSchema],
    })
    
    const FlashcardSet = mongoose.model('flashcardSet', flashcardSetSchema )
    
    export {FlashcardItem, FlashcardSet}

    عند تشغيل المشروع أحصل على 

    cannot overwrite "mongoose" model once compiled

     

    • أعجبني 1
  18. لدي مشروع في material-ui و nextjs و  أحاول جعل شريط التنقل الخاص بي يعمل مع nextjs:

    import * as React from 'react';
    import AppBar from '@material-ui/core/AppBar';
    import Link from "next/link";
    import {Tab, Tabs} from "@material-ui/core";
    
    export default function NavBar() {
      return (
            <AppBar position="static">
              <Tabs>
                  <Tab label="Timer"><Link href="timer" /> </Tab>
                  <Tab label="Home" to="/" component={Link}  />
              </Tabs>
            </AppBar>
      );
    }

    لكن  عملية بناء المشروع تفشل ؟

    • أعجبني 2
  19. لدي مشروع Vanilla JS بسيط ، مرفق مع webpack.

    هذا هو ملف webpack.dev.js الخاص بي:

    const path = require('path');
    const webpack = require('webpack');
    
    module.exports = {
      mode: 'development',
      devtool: 'eval-source-map',
      output: {
        path: path.resolve('public'),
        filename: 'dist/bundle.js',
      },
      module: {
        rules: [
          {
            test: /\.css$/,
            use: [
              'style-loader',
              'css-loader',
            ],
          },
          {
            test: /\.svg$/,
            use: 'file-loader',
          },
        ],
      },
      plugins: [
        new webpack.EnvironmentPlugin(['CUSTOM_PATH']),
      ],
      devServer: {
        static: './public',
      },
    };

    هذا هو ملف .env الخاص بي:

    PATH=...

    عند تشغيل المشروع احصل على 

    Uncaught (in promise) ReferenceError: process is not defined

     

    • أعجبني 1
  20.  أحتاج إلى تحويل الملفين light-theme.less و dark-theme.less من ملفات less إلى css. لا أعرف كيفية القيام بذلك في حزمة webpack وتخزينها في المجلد العام من تطبيقي. كانت محاولتي:

    module.exports = {
      module: {
        rules: [
          {
            test: /\-theme.scss$/,
            use: [
              {
                loader: 'style-loader',
              },
              {
                loader: 'css-loader',
              },
              {
                loader: 'less-loader',
              },
            ],
          },
        ],
      },
    }

    ولكنها لم تنجح

    • أعجبني 1
  21. أنا أستخدم Material-UI مع Next.JS. أرغب في استخدام مكون Link الخاص ب material ui حتى أتمكن من الوصول إلى المتغير وعناصر واجهة برمجة التطبيقات الأخرى ذات الصلة بواجهة material ui. في الوقت نفسه ، أحتاج إلى استخدام مكون NextJS Link للربط بين الصفحات.

    إنني أتساءل ، كيف يمكنني استخدام الاثنين معًا حتى أتمكن من الحصول على مزايا الربط لمكون NextJS Link جنبًا إلى جنب مع مزايا التصميم لمكون رابط MaterialUI.

     

    • أعجبني 1
  22. أقوم باستخدام material ui مع nextjs ولدي هذه الصفحة

    export default function Index() {
      const [onScreen, theRef] = useOnScreen({
        rootMargin: "-300px",
        ssr: true
      });  
      const classes = useStyles();
      return (
        <Container maxWidth="sm">
          <DummyContainer />
          <div
            ref={theRef}
            style={{
              height: "100vh",
              padding: "20px",
              backgroundColor: "green",
              transition: "all .5s ease-in"
            }}
          >
            {onScreen && (
              <Box className={classes.rootBox} my={16}>
                <Typography variant="h2" gutterBottom>
                  Content Lazy using Intersection Observer
                </Typography>
                <Copyright />
              </Box>
            )}
          </div>
          <Box className={classes.rootBox} my={4}>
            <Typography variant="h2" gutterBottom>
              Content no lazy, why this Box loses margin?
            </Typography>
            <Typography gutterBottom>
              If you request this page with JavaScript disabled, you will notice
              that has been properly rendered in SSR
            </Typography>
          </Box>
        </Container>
      );
    }

    عند تحديث الصفحة يتشوه ال css الخاص بعناصر ال box فيما أخطأت؟

     

    • أعجبني 1
  23. لدي مشكلة في تكوين webpack الخاص بي. بعد تنفيذ html-webpack-plugin ، حصلت على خطأ  في  index.html الذي تم إنشاؤه.

      Error: Child compilation failed:
      Conflict: Multiple assets emit to the same filename index.html:
      Error: Conflict: Multiple assets emit to the same filename index.html
    
    

    هذه هي الاعدادات الخاصة بي 

    var webpack = require('webpack'),
        path = require('path');
    
    
    var CopyWebpackPlugin = require('copy-webpack-plugin'),
        ExtractTextWebpackPlugin = require('extract-text-webpack-plugin'),
        HtmlWebpackPlugin = require('html-webpack-plugin'),
    
    const sourcePath = path.resolve(__dirname, './src');
    const staticPath = path.resolve(__dirname, './static');
    
    module.exports = function (env) {
    
        const nodeEnv = env && env.prod ? 'production' : 'development';
        const isProd = nodeEnv === 'production';
    
        const postcssLoader = {
            loader: 'postcss-loader',
            options: {
                plugins: function () {
                    return [
                        require('autoprefixer')
                    ];
                }
            }
        }
    
        const plugins = [
            new webpack.optimize.CommonsChunkPlugin({
                name: 'vendor',
                minChunks: Infinity,
                filename: 'vendor.bundle.js'
            }),
            new webpack.EnvironmentPlugin({
                NODE_ENV: nodeEnv,
            }),
            new HtmlWebpackPlugin({
                template: 'index.html',
                minify: {
                    removeComments: true,
                    collapseWhitespace: true,
                    removeAttributeQuotes: true
                },
                chunksSortMode: 'dependency'
            })
        ];
    
        if(isProd) {
            plugins.push(
                new webpack.LoaderOptionsPlugin({
                    minimize: true,
                    debug: false
                }),
                new webpack.optimize.UglifyJsPlugin({
                    compress: {
                        warnings: false,
                        screw_ie8: true,
                        conditionals: true,
                        unused: true,
                        comparisons: true,
                        sequences: true,
                        dead_code: true,
                        evaluate: true,
                        if_return: true,
                        join_vars: true,
                    },
                    output: {
                        comments: false,
                    },
                })
            );
        } else {
            plugins.push(
                new webpack.HotModuleReplacementPlugin()
            );
        }
    
        return {
            devtool: isProd? 'source-map' : 'eval',
            context: sourcePath,
    
            entry: {
                app: './app/entry.ts',
                vendor: './app/vendor.ts'
            },
    
            output: {
                path: staticPath,
                filename: '[name].bundle.js',
            },
    
            module: {
                rules: [
                    {
                        test: /\.html$/,
                        exclude: /node_modules/,
                        use: {
                            loader: 'file-loader',
                            query: {
                                name: '[name].[ext]'
                            },
                        },
                    },
                    {
                        test: /\.css$/,
                        exclude: /node_modules/,
                        use: [
                            'style-loader',
                            'css-loader',
                            'postcss-loader'
                        ]
                    },
                    {
                        test: /\.scss$/,
                        exclude: /node_modules/,
                        use: [
                            'style-loader',
                            'css-loader',
                            'postcss-loader',
                            'sass-loader'
                        ]
                    },
                    {
                        test: /\.ts$/,
                        exclude: /node_modules/,
                        use: [
                            'ts-loader'
                        ],
                    },
                ],
            },
    
            resolve: {
                alias: {
                    Public: path.resolve(__dirname,'src/public'),
                    Style: path.resolve(__dirname,'src/styles')
                },
                extensions: ['.ts','.js', '.html'],
                modules: [
                    path.resolve(__dirname, 'node_modules'),
                    sourcePath
                ]
            },
    
            plugins,
    
            performance: isProd && {
                maxAssetSize: 100,
                maxEntrypointSize: 300,
                hints: 'warning'
            },
    
            stats: {
                colors: {
                    green: '\u001b[32m'
                }
            },
    
            devServer: {
                contentBase: './src',
                historyApiFallback: true,
                port: 3000,
                compress: isProd,
                inline: !isProd,
                hot: !isProd,
                stats: {
                    assets: true,
                    children: false,
                    chunks: false,
                    hash: false,
                    modules: false,
                    publicPath: false,
                    timings: true,
                    version: false,
                    warnings: true,
                    color: {
                        green: '\u001b[32m'
                    }
                },
            }
        };
    };

     

    • أعجبني 3
  24. أقوم بإنشاء تطبيق react باستخدام واجهة المستخدم materialui و nextjs. أنا أستخدم مكون <Autocomplete /> ، يتم توفيره بواسطة واجهة المستخدم materialui وتجاوز بعض أنماطه بأنماط خاصة بي مثل هذا:

    <Autocomplete
      classes={{
        root: `${styles[`search__autocomplete`]} ${
          styles[`search--${variant}__autocomplete`]
        }`,
        inputRoot: `${styles[`search__autocomplete-input`]} ${
          styles[`search--${variant}__autocomplete-input`]
        }`
      }} 
    />

    عند تحديث الصفحة ال css الخاص بالمكون للحظة ياتي مشوه ثم يرجع لحالته الطبيعية هل هناك حل للمشكلة 

    • أعجبني 2
×
×
  • أضف...