找不到模块包

时间:2016-05-17 14:54:39

标签: javascript node.js gulp webpack

在开发的某个地方,这个错误开始出现,我无法确定它的来源。错误是广泛的'据我所知。我正在使用webpack和gulp。如果有人能指出我正确的方向。

我可以发布更多代码,但您需要告诉我哪些文件。该应用程序可以正常工作,REST,页面加载等。只有css没有显示。

Starting gatling-rsync-deamon...

Starting containers...
Starting vagrant_redis_1
Starting vagrant_mongo_1
Starting vagrant_app_1
Connection to 127.0.0.1 closed.

 launching stream...
[14:39:00] Requiring external module babel-register
[14:39:14] Using gulpfile /var/www/app/gulpfile.babel.js
[14:39:14] Starting 'set-dev-env'...
NODE_ENV will be set to development...
[14:39:14] Finished 'set-dev-env' after 310 μs
[14:39:14] Starting 'backend-watch'...
[14:39:14] Backend warming up...
[14:39:14] Starting 'frontend-watch'...
[14:39:15] Finished 'frontend-watch' after 694 ms
[14:39:15] Starting 'server'...
[14:39:15] Finished 'server' after 1.55 ms
Webpack-dev-server listening at localhost:9090.

module.js:340
    throw err;
          ^
Error: Cannot find module '/var/www/app/build/bundle'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:945:3
[14:39:20] Finished 'backend-watch' after 5.25 s
[14:39:20] Starting 'dev'...
[14:39:20] Finished 'dev' after 3.46 μs
Hash: 5e15e9e5b2fd1c868120
Version: webpack 1.13.0

gulpfile.babel.js

import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import gulp from 'gulp';
import gutil from 'gulp-util';
import nodemon from 'nodemon';
import path from 'path';
import jsdoc from 'gulp-jsdoc3';
import WebpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
// import backendConfig from './config/webpack.backend.config.js';
// import frontendConfig from './config/webpack.frontend.config.js';

import configs from './config/webpack.config';
import jsdocConfig from './config/jsdoc.config';

const [frontendConfig, backendConfig] = configs;


const FRONTEND_PORT = 8085;
const BACKEND_PORT = 9090;

function onBuild(err, stats) {
  if (err) {
    throw new Error(err);
  }
  console.log(stats.toString());
}

// Default: list all tasks.
gulp.task('default', () => {
  console.log('Available commands: dev, build');
});

// Start frontend
gulp.task('frontend', (done) => {
  webpack(frontendConfig).run((err, stats) => {
    onBuild(err, stats);
    done();
  });
});

// Start frontend watch
gulp.task('frontend-watch', () => {
  const webpackDevserver = new WebpackDevServer(webpack(frontendConfig), {
    publicPath: frontendConfig.output.publicPath,
    stats: { colors: true },
    historyApiFallback: true,
    proxy: {
      '*': `http://localhost:${BACKEND_PORT}`
    }
  });
  webpackDevserver.listen(BACKEND_PORT, 'localhost', (err, result) => {
    if (err) {
      console.log(err);
    }
    else {
      console.log(`Webpack-dev-server listening at localhost:${BACKEND_PORT}.`);
    }
  });
});

// Start backend
gulp.task('backend', (done) => {
  webpack(backendConfig).run((err, stats) => {
    onBuild(err, stats);
    done();
  });
});

// Start backend watch
gulp.task('backend-watch', (done) => {
  gutil.log('Backend warming up...');
  let firedDone = false;

  webpack(backendConfig).watch(100, (err, stats) => {
    if (!firedDone) { done(); firedDone = true; }
    onBuild(err, stats);
    nodemon.restart();
  });
});

// 
// gulp.task('run', ['set-dev-env', 'backend-watch'], () => {
//   nodemon({
//     execMap: {
//       js: 'node'
//     },
//     script: path.join(__dirname, 'build/backend'),
//     ignore: ['*'],
//     watch: ['foo/'],
//     ext: 'noop'
//   }).on('restart', () => {
//     console.log('Patched!');
//   });
// });

// Set NODE_ENV to development
gulp.task('set-dev-env', () => {
  console.log('NODE_ENV will be set to development...');
  process.env.NODE_ENV = 'development';
});

// Set NODE_ENV to production
gulp.task('set-prod-env', () => {
  console.log('NODE_ENV will be set to production...');
  process.env.NODE_ENV = 'production';
});

// Start server
gulp.task('server', () => {
  nodemon({
    execMap: {
      js: 'node'
    },
    script: path.join(__dirname, 'build/bundle'),
    ignore: ['*'],
    watch: ['foo/'],
    ext: 'noop'
  }).on('restart', () => {
    console.log('Server restarted!');
  });
});

// Generate docs
gulp.task('docs', (cb) => {
  // gulp.src(['README.md', './client/**/*.js', './server/**/*.js'], { read: false })
  //       .pipe(jsdoc(jsdocConfig, cb));
});

// Build project
gulp.task('build', ['set-prod-env', 'build-js']);

// Build backend & frontend
gulp.task('build-js', ['backend', 'frontend']);

// Watch backend & frontend
gulp.task('watch', ['backend-watch', 'frontend-watch']);

// Start development session
gulp.task('dev', ['set-dev-env', 'backend-watch', 'frontend-watch', 'server']);

webpack.config

import webpack from 'webpack';
import path from 'path';
import fs from 'fs';
import HtmlWebpackPlugin from 'html-webpack-plugin';
const embedFileSize = 50000;

const nodeModules = {};
fs.readdirSync('node_modules')
  .filter(module => {
    return ['.bin'].indexOf(module) === -1;
  })
  .forEach(mod => {
    nodeModules[mod] = 'commonjs ' + mod;
  });

const frontendConfig = {
  entry: [
    'webpack-hot-middleware/client',
    path.join(__dirname, '../client/index.js')
  ],

  output: {
    filename: 'bundle.js',
    path: path.join(__dirname, 'build', 'public')
  },

  devtool: 'sourcemap',

  plugins: [
    new HtmlWebpackPlugin({
      template: './client/public/index.html',
      inject: 'body',
      filename: 'index.html'
    }),
    new webpack.ProvidePlugin({
      'Promise': 'es6-promise',
      'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch'
    }),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development'),
      '__DEV__': JSON.stringify(process.env.NODE_ENV)
    })
  ],

  module: {
    preloaders: [
      { test: /\.js$/, loader: 'eslint'}
    ],
    loaders: [
      {
        test: /\.js?$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
      {
        test: /\.json?$/,
        loader: 'json'
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader?modules&&importLoaders=1&localIdentName=[name]---[local]---[hash:base64:5]!postcss-loader'
      },
      {
        test: /\.less$/,
        loader: "style!css!less"
      },
      { test: /\.svg/,
        loader: 'url?limit=' + embedFileSize + '&mimetype=image/svg+xml'
      },
      { test: /\.png$/,
        loader: 'url?limit=' + embedFileSize + '&mimetype=image/png'
      },
      { test: /\.jpg/,
        loader: 'url?limit=' + embedFileSize + '&mimetype=image/jpeg'
      },
      { test: /\.gif/,
        loader: 'url?limit=' + embedFileSize + '&mimetype=image/gif'
      },
      {
        test: /\.(otf|eot|ttf|woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url?limit=' + embedFileSize
      }
    ]
  },
  resolve: {
    extensions: ['', '.js', '.jsx', '.json', '.css']
  },
};

const serverConfig = {
  entry: './server/server.js',
  output: {
    path: path.join(__dirname, '../build'),
    filename: 'bundle.js'
  },

  devtool: 'sourcemap',

  target: 'node',
  // do not include polyfills or mocks for node stuff
  node: {
    console: false,
    global: false,
    process: false,
    Buffer: false,
    __filename: false,
    __dirname: false
  },
  externals: nodeModules,

  plugins: [
    // enable source-map-support by installing at the head of every chunk
    new webpack.BannerPlugin('require("source-map-support").install();',
      {raw: true, entryOnly: false})
  ],

  module: {
    loaders: [
      {
        // transpile all .js files using babel
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel'
      }
    ]
  }
};

export default [frontendConfig, serverConfig];

2 个答案:

答案 0 :(得分:0)

我现在的答案是基于您粘贴的代码。当我得到更多信息时,我会编辑这个答案。

我不确定如果我能为您找到远程正确的解决方案。但是你的问题可能是公共路径,它被添加到webpack和WebpackDevServer。 WebpackDevServer没有看到捆绑在bundle.js中的js代码

答案 1 :(得分:0)

将目标更改为" web"而不是节点。您应该编译最有可能的Web类型的环境,而不是像环境那样的node.js。

target: 'web',