Search code examples
javascriptwebpackgulpbabeljs

Webpack - module not found even though module exists


This is a branch off of my previous question and applied suggestions. But I am still having major issues.

I now have my babel transpiler, along with a .babelrc file in place. My import code to import my module looks like this:

var init = require('./app/js/modules/toc');
init();

However I'm getting this:

ERROR in ./app/js/script.js
Module not found: Error: Cannot resolve 'file' or 'directory' ./app/js/modules/toc in /projects/project-root/app/js
 @ ./app/js/script.js 1:11-42

Webpack config:

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');

module.exports = {
  context: __dirname,
  devtool: debug ? "inline-sourcemap" : null,
  entry: "./app/js/script.js",
  module: {
  rules: [{
      test: /\.js$/,
      use: 'babel-loader'
    }]
  },
  output: {
    path: __dirname + "public/javascripts",
    filename: "scripts.min.js"
  },
  plugins: debug ? [] : [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
  ],
};

.babelrc

{
  "presets": ["es2015"]
}

Gulptask

//scripts task, also "Uglifies" JS
gulp.task('scripts', function() {
    gulp.src('app/js/script.js')
    .pipe(webpack(require('./webpack.config.js')))
    .pipe(gulp.dest('public/javascripts'))
    .pipe(livereload());
});

I'm totally lost...what am I doing wrong?

For my import code I also tried:

import {toc} from './modules/toc'
toc();

UPDATE: As recommended I needed to add resolve to my config. It looks like this now:

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');

module.exports = {
  context: __dirname,
  devtool: debug ? "inline-sourcemap" : null,
  entry: "./app/js/script.js",
  resolve: {
    extensions: ['.js']
  },
  module: {
  rules: [{
      test: /\.js$/,
      use: 'babel-loader'
    }]
  },
  output: {
    path: __dirname + "public/javascripts",
    filename: "scripts.min.js"
  },
  plugins: debug ? [] : [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
  ],
};

Sadly I still get:

ERROR in Entry module not found: Error: Cannot resolve 'file' or 'directory' ./app/js/script.js in /projects/project-root

Does my file structure need to change?


Solution

  • You are specifying an entry point in your webpack config AND in gulp. Remove the entry property in your webpack config.

    If you specify it twice, the gulp config will tell webpack to get the file in ./app/js/script.jsand then webpack in ./app/js/script.js which will result in a path like ./app/js/app/js/script.js.

    Keep us posted if you fixed it. =)