简体   繁体   中英

Not able to import Express with Babel and Webpack

I'm using webpack and babel to create an app using ES6 syntax. The problem is that I'm not able to import express .

(Note: I'm able to import (and require) node module "path", didn't check any more)

Here's my app:

import express from 'express';

Even the below results in same error:

var app = require('express');

Here's my webpack.config.js

module.exports = {
    entry: './src/app.js',
    output: {
        path: 'builds',
        filename: 'bundle.js'
    },
    module: {
        loaders: [
            {
                test: /\.js/,
                loader: 'babel',
                include: __dirname + '/src',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015']
                }
            }
        ],
    }
};

I've tried the following as well:

exclude: [/node_modules/],
exclude: __dirname + '/node_modules',

But I still keep getting a very big stack trace which starts with:

WARNING in ./~/express/lib/view.js
Critical dependencies:
78:29-56 the request of a dependency is an expression
 @ ./~/express/lib/view.js 78:29-56

ERROR in ./~/express/lib/request.js
Module not found: Error: Cannot resolve module 'net' in /home/projects/node_modules/express/lib
 @ ./~/express/lib/request.js 18:11-25

ERROR in ./~/express/lib/view.js
Module not found: Error: Cannot resolve module 'fs' in /home/projects/node_modules/express/lib
 @ ./~/express/lib/view.js 18:9-22

And ends with

 @ ./~/mime/mime.js 87:12-35

ERROR in ./~/mime-db/db.json
Module parse failed: /home/projects/node_modules/mime-db/db.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
|   "application/1d-interleaved-parityfec": {
|     "source": "iana"
|   },
 @ ./~/mime-db/index.js 11:17-37

I guess this is because node_modules folder is not being ignored?

Also this is my package.json if maybe module versions are a problem:

{
  "name": "testing",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "MIT",
  "dependencies": {
    "express": "^4.13.4"
  },
  "devDependencies": {
    "babel-core": "^6.6.0",
    "babel-loader": "^6.2.4",
    "babel-preset-es2015": "^6.6.0",
    "webpack": "^1.12.14"
  }
}

This can be fixed by using json-loader:

npm install json-loader --save-dev

And in webpack.config add this loader:

{ test: /\.json$/, loader: "json-loader" }

Please, look at this answer . SudoPlz - shared working example. Looks like the method Michael Plakhov suggested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM