簡體   English   中英

無法使用 webpack 和 babel 構建項目

[英]Not able to build project using webpack and babel

我正在使用webpackbabel從頭構建一個 React 應用程序。 我有所有的規則和 babel 配置。 我已經使用 webpack 的三個配置文件設置了我的應用程序:

  1. 開發配置
  2. 產品配置
  3. 兩個配置中的通用項目(規則、變量、別名等)。

當我嘗試使用webpack-dev-server在本地(開發)啟動我的應用程序時,我import merge from 'webpack-merge'遇到錯誤

使用的命令: webpack-dev-server --config webpack.config.dev.babel.js --open

SyntaxError: Cannot use import statement outside a module
    at Module._compile (internal/modules/cjs/loader.js:891:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)
    at Function.Module._load (internal/modules/cjs/loader.js:723:14)
    at Module.require (internal/modules/cjs/loader.js:848:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at WEBPACK_OPTIONS (C:\Users\hp-pc\node_modules\webpack-cli\bin\convert-argv.js:115:13)
    at requireConfig (C:\Users\hp-pc\node_modules\webpack-cli\bin\convert-argv.js:117:6)
    at C:\Users\hp-pc\node_modules\webpack-cli\bin\convert-argv.js:124:17
    at Array.forEach (<anonymous>)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

我無法弄清楚問題到底出在哪里

我嘗試過的可能修復:

  1. 刪除node_modules並進行全新安裝。
  2. 使用yarn-upgrade-all更新所有依賴項。
  3. 從頭開始使用 webpack 和 babel 設置一個反應項目。
  4. 所以回答。
  5. "type":"module"添加到package.json

到目前為止,這些都沒有對我有用。 誰能指導我如何解決這個問題?

以下是一些可能有助於進一步解決此問題的文件:

package.json

{
  "name": "weather-app",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "autoprefixer": "^10.2.5",
    "axios": "^0.21.1",
    "classnames": "^2.3.1",
    "copy-webpack-plugin": "^8.1.0",
    "dotenv": "^8.2.0",
    "git-revision-webpack-plugin": "^3.0.6",
    "html-webpack-plugin": "^5.3.1",
    "mini-css-extract-plugin": "^1.4.0",
    "moment": "^2.29.1",
    "prop-types": "^15.7.2",
    "react": "^17.0.2",
    "react-debounce-input": "^3.2.3",
    "react-dom": "^17.0.2",
    "react-redux": "^7.2.3",
    "react-router-dom": "^5.2.0",
    "redux": "^4.0.5",
    "redux-thunk": "^2.3.0",
    "sass-loader": "^11.0.1",
    "style-loader": "^2.0.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.13.14",
    "@babel/core": "^7.13.14",
    "@babel/node": "^7.13.13",
    "@babel/plugin-transform-modules-commonjs": "^7.13.8",
    "@babel/plugin-transform-regenerator": "^7.12.13",
    "@babel/plugin-transform-runtime": "^7.13.10",
    "@babel/preset-env": "^7.13.12",
    "@babel/preset-flow": "^7.13.13",
    "@babel/preset-react": "^7.13.13",
    "@babel/register": "^7.13.14",
    "babel-loader": "^8.2.2",
    "babel-plugin-react-display-name": "^2.0.0",
    "babel-plugin-webpack-alias": "^2.1.2",
    "babel-preset-react-hmre": "^1.1.1",
    "case-sensitive-paths-webpack-plugin": "^2.4.0",
    "chai": "^4.3.4",
    "chalk": "^4.1.0",
    "css-loader": "^5.2.0",
    "enzyme": "^3.11.0",
    "eslint": "^7.23.0",
    "eslint-config-airbnb": "^18.2.1",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-react": "^7.23.1",
    "node-sass": "^5.0.0",
    "terser-webpack-plugin": "^5.1.1",
    "webpack": "^5.30.0",
    "webpack-cli": "^4.6.0",
    "webpack-dev-server": "^3.11.2",
    "webpack-merge": "^5.7.3",
    "webpack-notifier": "^1.13.0"
  },
  "scripts": {
    "start:dev": "webpack-dev-server --config webpack.config.dev.babel.js --open",
    "start:mock": "nodemon mockAPI.js",
    "update:packages": "node wipe-dependencies.js && rm -rf node_modules && npm update --save-dev && npm update --save"
  },
  "lint-staged": {
    "*.js": [
      "eslint --fix",
      "git add"
    ]
  },
  "nyc": {
    "exclude": [
      "**/*.spec.js",
      "dist",
      "docs",
      "helpers",
      "node_modules",
      "styleguide",
      "webpack*"
    ],
    "extensions": [
      ".js",
      ".jsx"
    ]
  }
}

webpack.config.dev.babel.js


    /* eslint-disable import/no-extraneous-dependencies */
    import merge from 'webpack-merge';
    import Notifier from 'webpack-notifier';
    import CaseSensitivePathsPlugin from 'case-sensitive-paths-webpack-plugin';
    
    
    import common from './webpack.common';
    
    module.exports = merge(common, {
      mode: 'development',
      devtool: 'source-map',
      devServer: {
        contentBase: './app/src',
        historyApiFallback: true,
      },
      plugins: [
        new Notifier(),
        new CaseSensitivePathsPlugin(),
      ],
    });

webpack.common.js


    import path from 'path';
    import 'core-js/stable';
    import 'regenerator-runtime/runtime';
    import GitRevisionPlugin from 'git-revision-webpack-plugin';
    import HtmlWebpackPlugin from 'html-webpack-plugin';
    import MiniCssExtractPlugin from 'mini-css-extract-plugin';
    
    const gitRevisionPlugin = new GitRevisionPlugin();
    const buildDateTime = new Date().toISOString();
    
    const htmlConfig = {
        template: 'index.html',
        filename: 'index.html',
        inject: true,
        data: {
            __VERSION__: JSON.stringify(gitRevisionPlugin.version()),
            __COMMITHASH__: JSON.stringify(gitRevisionPlugin.commithash()),
            __BRANCH__: JSON.stringify(gitRevisionPlugin.branch()),
            __BUILDDATETIME__: buildDateTime,
        },
    };
    
    module.exports = {
        context: path.resolve(__dirname, './app/src'),
        entry: {
            app: ['./index.jsx'],
        },
        output: {
            path: path.resolve(__dirname, './app/dist'),
            publicPath: '/',
            filename: '[name].[chunkhash].js',
        },
        module: {
            rules: [
                {
                    test: /\.(woff|woff2|eot|ttf|otf)$/,
                    use: [
                        'file-loader?name=assets/fonts/[name].[ext]',
                    ],
                },
                {
                    test: /(\.js|\.jsx)$/,
                    loader: 'babel-loader',
                    exclude: [/node_modules/],
                    include: [path.resolve(__dirname, './node_modules/react-icons/fa'), path.resolve(__dirname, './node_modules/react-onclickoutside')],
                    query: {
                        presets: [['@babel/env',
                            {
                                useBuiltIns: 'usage',
                                corejs: 3,
                            },
                        ],
                            '@babel/react',
                            '@babel/flow'],
                        plugins: ['@babel/plugin-syntax-dynamic-import', '@babel/plugin-transform-regenerator', '@babel/plugin-proposal-class-properties', '@babel/plugin-transform-runtime', 'transform-class-properties'],
                    },
                },
                {
                    test: /\.(png|jpg|svg|ico)$/,
                    loader: 'file-loader',
                },
                {
                    test: /\.s?css$/,
                    use: [
                        'style-loader',
                        'css-loader',
                        'sass-loader'
                    ],
                },
            ],
        },
        plugins: [
            new MiniCssExtractPlugin({
                filename: '[name].[hash].css',
                chunkFilename: '[id].[hash].css',
            }),
            new HtmlWebpackPlugin(htmlConfig),
        ],
        resolve: {
            alias: {
                Actions: path.resolve(__dirname, 'app/src/actions'),
                Components: path.resolve(__dirname, 'app/src/components/'),
                Containers: path.resolve(__dirname, 'app/src/containers/'),
                Helpers: path.resolve(__dirname, 'helpers/'),
                Selectors: path.resolve(__dirname, 'app/src/selectors/'),
                Utils: path.resolve(__dirname, 'app/src/utils'),
                Assets: path.resolve(__dirname, 'app/src/assets'),
                Apis: path.resolve(__dirname, 'app/src/api'),
            },
            extensions: ['.js', '.jsx', '.json', '*'],
        },
    };

.babelrc

    {
      "presets": [
        "@babel/env",
        "@babel/preset-react",
        "@babel/preset-flow"
      ],
      "env": {
        "test": {
          "plugins": [
            "@babel/plugin-transform-regenerator",
            "@babel/plugin-syntax-dynamic-import",
            [
              "@babel/plugin-transform-runtime",
              {
                "regenerator": true
              }
            ],
            [
              "module-resolver",
              {
               
                "alias": {
                  "Actions": "./app/src/actions",
                  "Assets": "./app/src/assets",
                  "Components": "./dims-common-ui/components/",
                  "Containers": "./app/src/containers",
                  "Helpers": "./helpers",
                  "Selectors": "./app/src/selectors",
                  "Utils": "./app/src/utils",
                  "Apis": "./app/src/api"
                }
              }
            ],
            "@babel/plugin-proposal-class-properties"
          ]
        }
      }
    }

在 webpack-merge 自述文件中,沒有使用您使用的模式的示例。 你在哪里看到這個? 您是否嘗試過模仿文檔的模式? 我認為這意味着您在外部定義配置,然后運行返回合並的 function。 你試過這個嗎?

module.exports = env => {


switch(env) {
    case 'development':
      return merge(commonConfig, developmentConfig);
    case 'production':
      return merge(commonConfig, productionConfig);
    default:
      throw new Error('No matching configuration was found!');
  }
}

你需要告訴 babel 它需要轉換什么,你用@babel/register這樣做,所以在你的入口點你需要這樣的東西


module.exports ={
  entry: [
     "@babel/register",
     "path-to-where-your-entry-is-at"
  ]
}

因此,對我有用的解決方案是使用webpack 4而不是webpack因為在我的用例中webpack 5babel 7似乎存在一些問題。 感謝您的回答 Ernesto 和 IWI!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM