Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
felixexter opened this issue Aug 25, 2016 · 42 comments
Closed

Comments

@felixexter
Copy link

felixexter commented Aug 25, 2016

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?

@ericclemmons
Copy link

ericclemmons commented Aug 25, 2016

Can you post up your config for babel-loader? Because this structure should be fine:

app/
test/
webpack.config.js

I've never a script import something outside of an entire project. (That's what node_modules is for)

@felixexter
Copy link
Author

felixexter commented Aug 25, 2016

This structure

|- project
| |- app/
| |- node_modules/
| |- webpack.config.js
|- test/
  |- node_modules/
  |- index.js

.babelrc

{
    "ignore": [
        "node_modules/**/*"
    ],
    "presets": [
        "es2015",
        "stage-0"
    ],
    "plugins": [
        "transform-runtime"
    ]
}

webpack.config.js

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

@ericclemmons
Copy link

Hmm, maybe Babel isn't the one processing it. (This directory structure is unorthodox, since files are being referenced outside of process.cwd()).

Does it work if you run webpack --config project/webpack.config.js?

@hiroppy
Copy link
Member

hiroppy commented Aug 26, 2016

Please rewrite below for webpack.config.js.

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

How is it?

@felixexter
Copy link
Author

felixexter commented Aug 26, 2016

@abouthiroppy yes, it's same code, i just copied part of code, updated below
@ericclemmons no, it doesn't work, updated structure below, each directory have node_modules, i run webpack --config webpack.config.js in project & get the same error

@hiroppy
Copy link
Member

hiroppy commented Aug 26, 2016

@felixexter Are you writing modules in webpack.config.js ? (I think I look at your updated comment)

@felixexter
Copy link
Author

@abouthiroppy fixed below, I write module :)

@hiroppy
Copy link
Member

hiroppy commented Sep 9, 2016

@felixexter Sorry for my late reply. Did you solve this problem?

@felixexter
Copy link
Author

@abouthiroppy no

@kevincaradant
Copy link

kevincaradant commented Sep 12, 2016

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 :)

@loganfsmyth
Copy link
Member

@felixexter What folder is your .babelrc in? Your directory structure with tests and source split into two separate modules is rather unusual. A .babelrc applies to all files inside the directory is it in, so unless you've got the presets installed in both tests and app with a .babelrc in both directories, you'll definitely get the error you are seeing.

@eugene1g
Copy link

Sometimes it helps to add a .babelrc file into the 'external' folder which points to your main config like so {extends: '../../mainroot/.babelrc'}

@felixexter
Copy link
Author

@kevincaradant No, it doesn't work for me.

@felixexter
Copy link
Author

@loganfsmyth project folder has .babelrc, test foder has one file index.js only.

@garaboo
Copy link

garaboo commented Nov 22, 2016

@felixexter Try to place .babelrc into the app folder

@inkorcoder
Copy link

inkorcoder commented Jan 23, 2017

I have a similar problem. Babel doesn't transpile js-files. npm i babel-loader@5 works for me, thanks!

@samsul003
Copy link

Hi, i have the same issue. I have asked a question in stackoverflow to see if anyone has a solution for that.
here is the question i asked in stackoverflow:

my package.json:

    "babel-core": "^6.22.1",
    "babel-loader": "^5.0.0",
    "babel-preset-es2015": "^6.22.0"

my webpack.config.js

module.exports = {
  entry: {
    app: "./app/assets/scripts/App.js"
  },
  output: {
    path: "./app/temp/scripts",
    filename: "App.js"
  },
  module: {
    loaders: [
      {
        loader: 'babel-loader',
        query: {
          presets: ['es2015']
        },
        test: /\.js$/,
        exclude: /node_modules/
      }
    ]
  }
}

and my .babelrc (project root dir)

{
  "presets": ["es2015"]
}

@inkorcoder
i tried to install babel-loader@5.0.0 but still no luck !
@kevincaradant
hey man, u said u solved it but how?

@kevincaradant
Copy link

@samsul003, Hi, really sorry but I didn't remember, and when I see my answer, I don't know. I think the configuration suggested in my previous message is the thing which resolved my problem but maybe it's not the case of everyone :/

@samsul003
Copy link

samsul003 commented Mar 15, 2017

Hi, i got it solved. As it seems to me it doesnt really matter which version of the babel core, babel-loader you actually use. Also .babelrc file was not required for me. What worked for me was to include the bundled file in my HTML which was generated at temp/scripts/App.js, instead of including the original source at assets/scripts/App.js. Thats it ! cheers

@MichaelMammoliti
Copy link

MichaelMammoliti commented Apr 8, 2017

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>

@mareksuscak
Copy link

mareksuscak commented Jun 1, 2017

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.

@monkindey
Copy link

monkindey commented Jul 13, 2017

@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)

@mass85
Copy link

mass85 commented Jul 25, 2017

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?

@jamescoq
Copy link

I have the same issue as @mass85.
When importing JS file from a simlinked module in lerna monorepo I get error
Unexpected token (6:4) You may need an appropriate loader to handle this file type. | export default { | en: { | ...en | }, | cs: {
when remove the simlink and copy the files, then it woks fine.

@richburdon
Copy link

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/'
          }
        }
      }
    ]
  }

@loganfsmyth
Copy link
Member

Have you updated to a new Webpack version or anything?

@richburdon
Copy link

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/'
          }
        }]
      }
    ]
  }

@thedamon
Copy link

thedamon commented Nov 27, 2017

I have a very similar issue in a monorepo. Adding a .babelrc to the exterior file's parent and that started it working, but a different build broke because it was using an old version of babel that doesn't support "presets" as an option. My solution so far is that this build doesn't get minified and that we obviously have bigger structural problems to worry about. 😜

davwards added a commit to davwards/elementals that referenced this issue Dec 9, 2017
Discovered while doing this some weirdness involving babel
transpilation. gherkin-runner wasn't getting transpiled when tests run.

Found some discussion of the issue, including an indication that a fix
is due out in jest soon:

jestjs/jest#4761

I updated jest to 21.3.0-beta.3 to see if that helped. It didn't at
first, which turned out to be because it wasn't under the original
package directory, so babel didn't know what transforms to run (?).
(These thoughts are based on discussion here:)

babel/babel-loader#293

I added some babel configuration to the root-level package.json which
fixed the issue.
@ericclemmons
Copy link

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")
        ),
      }

@piranna
Copy link

piranna commented Feb 24, 2018

I have a similar problem, hope it helps.

I have an app project that builds successfully, and I have it as dependency of an Integration project (forr global tests and showcases), that fails, also having all app project devDependencies set as dependencies for both the app and the Integration projects. Only solution I've found so far is to go into the node_modules/<app> forlder and exec npm install there, so the dependencies (babel-loader and friends) are at the app project root folder and NOT at its parent Integration project. This shows me that babel or babel-loader search for plugins on the node_modules folder of the current project root and not search towards its parent dirs, although the Node.js modules path resolution allows this. I think what's proposed at #293 (comment) would fix this for me, that would confirm that so I'll try to look at it later. Maybe would only it needed to have the babel-preset-env module installed inside the app project?

@renatonmendes
Copy link

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

@richardtallent
Copy link

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.

@Morphexe
Copy link

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.

@ViBiOh
Copy link

ViBiOh commented Mar 29, 2018

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"
  ]
}

@good-idea
Copy link

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

@KindWizzard
Copy link

KindWizzard commented May 24, 2018

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:)

@mqliutie
Copy link

Hi, in my case I have two entry files called a.js and b.js.

a.js is es6 code
b.js imported a.js

I need b.js using presets-es2015 but a.js not. in other words b.js will be es5 code a.js still es6
I also ask question in stackoverflow

@robatwilliams
Copy link

Workaround for when this problem arises when depending on a sibling lerna package: resolve.symlinks: false in webpack config

@loganfsmyth
Copy link
Member

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

@antriver
Copy link

antriver commented Feb 7, 2019

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.

@ShineKidd
Copy link

ShineKidd commented Jul 3, 2019

@felixexter Try to place .babelrc into the app folder

|- project
| |- app/
| |- node_modules/
| |- webpack.config.js
|- test/
| |- node_modules/
| |- index.js
|- .babelrc 

I place .bablerc into the root folder, it works!

@revanth0212
Copy link

My fix was to add another route to the includes array. I was referencing certain file from another package outside my current package, so did this for both JS and CSS rules in webpack.config.js:

Before

resolve(__dirname, 'src')

After

[resolve(__dirname, 'src'), resolve(__dirname, '..', ANOTHER_PACKAGE, 'src')]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests