Search code examples
reactjswebpackbabeljsbabel-loaderdynamic-import

client side babel-loader with @babel/plugin-syntax-dynamic-import still complains about top level imports


Here's the piece of code where it's complaining about:

function something(param) {
  import { whatisthis } from './dir/dir/anotherone';
}

Error output:

SyntaxError: pathtofile.jsx: 'import' and 'export' may only appear at the top level

webpack config:

const baseConfig = {
  resolve: {
    extensions: ['*', '.js', '.jsx'],
    alias: {
      imports: path.resolve(__dirname, 'stuff/'),
      ...other alias
    }
  },
  devServer: {
    hot: true,
  },
};

const clientConfig = Object.assign({}, baseConfig, {
  entry: './client/main.js',
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.js$|\.jsx$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            plugins: [
              '@babel/plugin-syntax-dynamic-import',
              ['@babel/plugin-proposal-decorators', { legacy: true }],
              '@babel/plugin-proposal-function-sent',
              '@babel/plugin-proposal-export-namespace-from',
              '@babel/plugin-proposal-numeric-separator',
              '@babel/plugin-proposal-throw-expressions',
              '@babel/plugin-syntax-import-meta',
              ['@babel/plugin-proposal-class-properties', { loose: false }],
              '@babel/plugin-proposal-json-strings',
              '@babel/plugin-proposal-object-rest-spread',
              '@babel/plugin-transform-runtime',
            ],
            presets: ['@babel/preset-env', '@babel/preset-react'],
          },
        },
      },
      {
        test: /\.css|\.scss$/,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './client/body.html',
    }),
    new webpack.HotModuleReplacementPlugin(),
  ],
});

I have tried having the above config and also tried replacing that with a .babelrc file and no matter what, it always keeps complaining about top level imports. Also removed the node_modules and the lock file, re-installed and same thing happened. Is this not supposed to work?

PS: I'm using webpack4 and babel7.x.


Solution

  • import statement can only be used in top-level of the file, which means it can't be used inside any scope containing {}, for example it can't be used in

    function something(param) {
      import { whatisthis } from './dir/dir/anotherone';
    }
    

    If you want, you can use dynamic import for that:

    let whatisthis;
    function something(param) {
      import('./dir/dir/anotherone').then(m => (whatisthis = m.whatisthis));
    }