babel-loader: babel-loader doesn't transpile imported js from an outside directory

Webpack Version: 1.13.2 Babel Core Version: 6.14.0 Babel Loader Version: 6.2.5 Environment: Windows 7

I’m trying to import a script from an outside app directory

// app/scripts/app.js
import test from '../../../test'

// ../test/index.js
import muliply from './multiply'
export default (a, b) => muliply(a, b)

It should be transpiled to es5, but i get an error in browser console:

Uncaught SyntaxError: Unexpected token import

Is it a bug or a feature and I need to config something else?

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 58
  • Comments: 42 (6 by maintainers)

Commits related to this issue

Most upvoted comments

Ran into a similar issue today. This was my folder structure:

root/
  node_modules/
  lib/
    dep.js
  demo/
    node_modules/
      babel-preset-es2015
    .babelrc
    entry.js
    package.json
    webpack.config.js
  package.json

Now, entry.js was importing ../lib/dep.js. Here’s the loader configuration (webpack2):

{
  test: /\.js$/,
  loader: 'babel-loader',
  exclude: /node_modules/
}

The solution that helped me was to remove .babelrc file and move the options to webpack.config.js as such:

{
  test: /\.jsx?$/,
  use: {
    loader: 'babel-loader',
    options: {
      presets: [
        require.resolve('babel-preset-react'),
        [require.resolve('babel-preset-es2015'), { "modules": false }],
        require.resolve('babel-preset-stage-0')
      ]
    }
  },
  exclude: /node_modules/
}

I suspect there’s a problem with package paths if you don’t resolve the path at build time.

@felixexter I also Ran into a similar issue. When I tried to find the reason, I add the console.log and it work. Maybe you can try it.

// ../test/index.js
import muliply from './multiply'
console.log('The strange bug');
export default (a, b) => muliply(a, b)

@felixexter Try to place .babelrc into the app folder

Hi 😃, I think I get the same problem today. Just to know, for me, If I install the babel-loader (version 5.0.0) instead of 6.2.X, that works. Is it the same for you ? Thank you

OK i fix the problem but i don’t know really how …

This is my package.json libraries:

"babel-core": "6.14.0",
    "babel-loader": "6.2.5",
    "babel-plugin-transform-runtime": "6.15.0",
    "babel-polyfill": "6.13.0",
    "babel-preset-es2015": "6.14.0",
    "babel-runtime": "6.11.6",

And i create a .babelrc file with this lines inside:

{
  "presets": ["es2015"]
}

and i think that’s all 😃

I had this same issue and tried a few fixes here that didn’t solve it.

My directory structure is: parent project-1 project-2

project-1 imported some modules from project-2 (temporarily!) and was erroring because the ‘babel-plugin-transform-object-rest-spread’ plugin was not working.

My parent/project-1/webpack.config.js used to be:

module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        babelrc: true,
                    },
                },
            },`

And parent/project-1/.babelrc

{
    "presets": [
        "babel-preset-env"
    ],
    "plugins": [
        "babel-plugin-transform-object-rest-spread",
        "babel-plugin-syntax-dynamic-import"
    ]
}

It started working by removing babelrc:true from the webpack config and putting the options in the webpack config instead:

module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['babel-preset-env'],
                        plugins: [
                            "babel-plugin-transform-object-rest-spread",
                            "babel-plugin-syntax-dynamic-import"
                        ]
                    },
                },
            },

You also must have the babel plugins installed in both project-1/node_modules and project-2/node_modules.

I had the same issue here, I wanted to keep my .babelrc (for editor and clearness) so the config was:

webpack.config.js

const babelConfig = JSON.parse(fs.readFileSync('.babelrc'));

...

{
    test: /\.js$/,
    exclude: /node_modules/,
    use: {
        loader: 'babel-loader',
        options: {
          presets: babelConfig.presets.map(preset => [require.resolve(`babel-preset-${preset}`), { "modules": false }]),
          plugins: babelConfig.plugins.map(plugin => require.resolve(`babel-plugin-${plugin}`)),
        }
    },
},

No config needed in external folder, and my .babelrc contains

{
  "presets": ["env"],
  "plugins": [
    "transform-class-properties",
    "transform-runtime"
  ]
}

This just started happening with me using a yarn monorepo.

Previously, the problem was resolved by adding the appropriate (linked) paths to the webpack include param for the babel-loader. But this no longer works (doesn’t seem to matter if they are linked or hard copied).

E.g.,

  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        include: [
          path.resolve('.'),
          path.resolve('../registry'),            // Linked modules.
          path.resolve('../util')
        ],
        use: {
          loader: 'babel-loader',
          options: {
            cacheDirectory: './dist/babel-cache/'
          }
        }
      }
    ]
  }

The same issue going on, I have a utility that needs to import Class File from a package outside the folder ( Its model definition for a database) from a sister project,

I mean, it should just transpile the imported file as if it was same dir import, I can’t see why this does not work out of the box, to be honest.

Same issue here. This is my folder structure: | common/ |— core.js | project1/ |— webpack.conf.js |— index.js |—package.json

config.resolve.alias['@'] = resolve(__dirname, '../common');

import Core from '@/core.js';

Webpack resolves filename normally, but for some reason babel-loader is trying to find all the plugins not at the project directory, but from the /common folder. So I get something like that:

Module build failed: ReferenceError: Unknown plugin...

But if copy node_modules from the project folder to the common, it’s starts working as is should be.

PS: Babel-loader 7.x.x, this bug is too years old:)

I’m triaging old issues on babel-loader. Since this has been inactive for ages, I’m going to close it. Feel free to re-open if there’s still something to discuss, but I’m assuming at this point it’s been too long to address in a useful way.

The issue is that .babelrc files do not affect files in sibling folders. With Babel 6, you’d need to pass your config via babel-loader’s options. For Babel 7, you can consider using a project-wide babel.config.js

Having the same problem here. I have two repos – a Vue component, and a demo/test site for said component. I want to have them pulled in sister folders and use the demo site to test live changes I’m making in the Vue components.

I ran into the same issue today! The example repo (https://github.com/mass85/no_transpilation_with_lerna) does a good job capturing the problem.

I did notice (along with @thedamon) that when I move .babelrc up into the monorepo root, things get closer, but it creates problems with other projects that end up keying off of that .babelrc then =/

One thing that seemed to have helped was explicitly setting the options & removing the .babelrc entirely:

      {
        test: /\.js$/,
        loader: "babel-loader",
        include: [
          path.resolve(__dirname, "src"),
          path.resolve(__dirname, "../../packages"),
        ],
        query: Object.assign(
          {
            babelrc: false,
            cacheDirectory: false,
          }
          require("./my-babel-preset")
        ),
      }

I have the same issue with a monorepo, and my working solution is adapted from @ViBiOh’s above:

{
	loader: 'babel-loader',
	options: {
		presets: babelConfig.presets.map((preset) => [preset, { modules: false }]),
		plugins: babelConfig.plugins.map((plugin) => {
			if (typeof plugin === 'string') return plugin
			return [...plugin]
		}),
	},
},

.babelrc:

{
	"presets": ["@babel/preset-react", "@babel/preset-flow", "@babel/preset-env"],
	"env": {
		"development": {
			"plugins": ["flow-react-proptypes"]
		}
	},
	"plugins": [
		[
			"babel-plugin-module-resolver",
			{
				"root": ["./app"],
				"extensions": [".js", ".web.js", ".native.js"],
				"alias": {
					"App": "./app/"
				},
				"cwd": "babelrc"
			}
		],
		"babel-plugin-styled-components",
		"@babel/plugin-proposal-class-properties",
		"@babel/plugin-proposal-object-rest-spread",
		"react-hot-loader/babel",
		"ramda"
	]
}

My solution was a little different because one of my plugins has configuration options.

I should also note that this doesn’t use require.resolve() and it’s working fine. If I do use it, there’s an error loading babel-plugin-ramda. I’m not sure if the issue lies with babel or the plugin.

ERROR in ./app/index.js
Module build failed: Error: Plugin/Preset files are not allowed to export objects, only functions. In /Users/joseph/Sites/myProject/beta/node_modules/ramda/src/index.js
    at createDescriptor (/Users/joseph/Sites/myProject/beta/node_modules/@babel/core/lib/config/config-descriptors.js:181:11)
    at /Users/joseph/Sites/myProject/beta/node_modules/@babel/core/lib/config/config-descriptors.js:106:12
    at Array.map (<anonymous>)
    at createDescriptors (/Users/joseph/Sites/myProject/beta/node_modules/@babel/core/lib/config/config-descriptors.js:105:27)
    at createPluginDescriptors (/Users/joseph/Sites/myProject/beta/node_modules/@babel/core/lib/config/config-descriptors.js:101:10)
    at /Users/joseph/Sites/myProject/beta/node_modules/@babel/core/lib/config/config-descriptors.js:92:12
    at cachedFunction (/Users/joseph/Sites/myProject/beta/node_modules/@babel/core/lib/config/caching.js:42:17)
    at plugins (/Users/joseph/Sites/myProject/beta/node_modules/@babel/core/lib/config/config-descriptors.js:23:61)
    at mergeChainOpts (/Users/joseph/Sites/myProject/beta/node_modules/@babel/core/lib/config/config-chain.js:369:68)
    at /Users/joseph/Sites/myProject/beta/node_modules/@babel/core/lib/config/config-chain.js:324:7
 @ multi (webpack)-dev-server/client?http://0.0.0.0:8080 webpack/hot/dev-server babel-polyfill react-hot-loader/patch webpack-dev-server/client?https://localhost:8080 webpack/hot/only-dev-server ./app/index.js

Is this problem solved ? I´m running the same issue as @felixexter

I resolved my issue and may have a solution for folks (Webpack 2). My webpack config above does in fact work for me (I had a gnarly bug where one of my JS files actually had a different file suffix – really hard to find).

If you’re in doubt install echo-loader and add that to the babel-loader config. When running webpack it will output each file that is visited. You should see whether the file is transpiled or not.

  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        include: [
          path.resolve('.'),
          path.resolve('../registry'),            // Linked module.
        ],
        use: [{
          loader: 'echo-loader',
        }, {
          loader: 'babel-loader',
          options: {
            cacheDirectory: './dist/babel-cache/'
          }
        }]
      }
    ]
  }

I have a similar issue when imported module is linked. In order to isolate it I created a simple project: https://github.com/mass85/no_transpilation_with_lerna

Could anyone be so kind and have a look at this and try to fix it?

Remember to include the output file and not the input one.

this: <script src='app/index.js'></script>

to: <script src='bundle/bundle.js'></script>

Please rewrite below for webpack.config.js.

{
// ...
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/
      }
    ]
  }
// ...
}

How is it?