Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack fails to import module in parent directory

Tags:

webpack

I have a dir structure like so:

/src
   /components
     fooComponent.js
     /someDir
        webpack.json
        index.js
        package.json

package.json:

      "devDependencies": {
    "babel-core": "^6.4.5",
    "babel-loader": "^6.2.1",
    "babel-preset-es2015": "^6.3.13",
    "css-loader": "^0.22.0",
    "style-loader": "^0.13.0",
    "stylus-loader": "^1.5.1",
    "webpack": "^1.12.12"
  }

The index json is imported the fooComponent.js like so:

import fooComponent from '../fooComponent'

But when running webpack I get this error:

Error: Couldn't find preset "es2015" relative to directory "me/src/components

webpack.config:

module.exports = {
  context: __dirname,
  entry: {
    main: [
      "./index"
    ]
  },
  output: {
    path: __dirname + "/dist",
    filename: "foo.js"
  },
  devtool: "source-map",
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015']
        }
      },
      {test: /\.styl$/, loader: 'style-loader!css-loader!stylus-loader'}


    ]
  },
  resolve: {
    // you can now require('file') instead of require('file.js')
    extensions: ['', '.js', '.json']
  }
}
like image 607
SuperUberDuper Avatar asked Oct 18 '22 16:10

SuperUberDuper


1 Answers

The webpack config considers that your working directory is defined by context. Your context is set to someDir, your component is outside the directory to be transformed by babel and will be treated at a regular javascript file.

Change the configuration to make context point to src directory. It will start transforming all the files in your codebase.

Or you can use a include tag to include the parent directory to be transformed as well.

Try a structure like this

src/
  components/
    fooComponent.js
  someDir/
    otherJsFiles.js
  index.js
webpack.config.js

Keep webpack.config out of src as it is a config to build the code and not the code itself. Then in your js loader section add include: path.resolve(__dirname, "src"),.

Your index.js will be an entry point like entry: "./src/index.js";

like image 135
sandeep Avatar answered Oct 21 '22 07:10

sandeep