javascript - Webpack 不排除 node_modules

标签 javascript webpack ecmascript-6

我有以下目录结构:

- webpack.config.js - 源代码 - 索引.js -距离 - 索引.js

Webpack 配置:

module.exports = {
    module: {
      loaders: [{
        test: /\.js$/,
        include: __dirname + 'src',
        exclude: __dirname + 'node_modules',
        loader: "babel-loader"
      }],
    },
    resolve: {
      extensions: ['.js']
    },
    output: {
      path: __dirname + '/dist',
      filename: 'index.js'
    }
};

但是,如果我在 src/index.js 中导入 request (const request = require('request');),我会从 node_modules 收到错误。

如何避免这种情况?我以为我已经排除了node_modules。

只是为了完成我的 package.json:

{
  "name": "leo-trans",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "watch": "webpack --watch",
    "start": "node dist/index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "preferGlobal": true,
  "bin": {
    "leo-trans": "./dist/index.js"
  },
  "devDependencies": {
    "babel-core": "^6.3.26",
    "babel-loader": "^6.2.1"
  },
  "dependencies": {
    "cheerio": "^0.19.0",
    "request": "^2.67.0"
  }
}

最佳答案

您尚未排除 node_modules,因为 __dirname 不包含尾部斜杠。尝试使用path.resolve :

const path = require('path');

module.exports = {
  module: {
    loaders: [{
      test: /\.js$/,
      include: path.resolve(__dirname, 'src'),
      exclude: path.resolve(__dirname, 'node_modules'),
      loader: "babel-loader"
    }],
  },
  // ...
}

关于javascript - Webpack 不排除 node_modules,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34609437/

相关文章:

javascript - React 中的 Video.js 播放列表

Javascript (ECMA-6) 类魔术方法 __call 像 PHP

javascript - Sequelize JS : How to remove nested object in result set

javascript - 创建 MEAN API 路由错误

npm - webpack 4 是否重复删除了已经被 webpack 捆绑的 npm 包?

javascript - Angular 无法绑定(bind)到 'dragula',因为它不是 'ul' 的已知属性

javascript - 如何根据条件合并对象的数组属性?

javascript - 执行一个 promise 循环并捕获过程中的错误

javascript - 位置 :sticky? 的替代方案是什么

javascript - 如何在没有媒体查询的情况下使图像标签图像响应并使布局成为一个屏幕