【问题标题】:Not able to build project using webpack and babel无法使用 webpack 和 babel 构建项目
【发布时间】:2021-06-30 17:13:54
【问题描述】:

我正在使用 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. Setting a react project with webpack and babel from scratch.
  4. SO Answer.
  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"
          ]
        }
      }
    }

【问题讨论】:

    标签: javascript reactjs webpack babeljs webpack-dev-server


    【解决方案1】:

    在 webpack-merge 自述文件中,没有使用您使用的模式的示例。你在哪里看到这个?您是否尝试过模仿文档的模式?我认为这意味着你在外部定义你的配置,然后运行一个返回合并的函数。你试过吗?

    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!');
      }
    }
    

    【讨论】:

    • 我会试试这个。我有两个不同的脚本用于开发和生产。在开发脚本中,我传递了开发配置文件,并将其传递给生产配置文件。我没有设置 env 变量,而是考虑使用不同的 webpack 配置文件并使用 webpack-dev-server--config 选项提供名称。脚本运行时,我将公共部分拉出,然后直接将它们合并到各自的环境配置中。这不是正确/推荐的方法吗?
    【解决方案2】:

    你需要告诉 babel 它需要转换什么,你用@babel/register 这样做,所以在你的入口点你需要这样的东西

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

    【讨论】:

      【解决方案3】:

      因此,对我有用的解决方案是使用webpack 4 而不是webpack,因为在我的用例中webpack 5babel 7 似乎存在一些问题。感谢您的回答 Ernesto 和 IWI!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-04
        • 2018-10-28
        • 2021-12-06
        • 2016-06-15
        • 1970-01-01
        • 2022-07-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多