javascript - Webpack 无法在外部包中构建 ES6

标签 javascript npm ecmascript-6 webpack babeljs

我正在尝试在项目中使用 ES6 npm 包(在本例中称为 gamesystem)并使用 webpack(和 babel)构建它无法在外部依赖项中构建任何 ES6 代码,这是为什么?如果我有与具有相对路径的依赖项相同的代码,它就可以正常工作。

应用代码:

'use strict';

import World from 'gamesystem'; // Breaks
//import World from '../node_modules/gamesystem'; // Also breaks
//import World from '../gamesystem'; // Works (copied the same directory gamesystem outside the node_modules directory)

let world = new World();

错误:

ERROR in ./~/gamesystem/World.js
Module parse failed: /home/user/project/node_modules/gamesystem/World.js Line 3: Unexpected token
You may need an appropriate loader to handle this file type.
| 'use strict';
| 
| import System from './System';
| 
| export default class World {
 @ ./src/app.js 3:18-39

网络包配置:

'use strict';

// Modules
let WebpackNotifierPlugin = require('webpack-notifier');
let HtmlWebpackPlugin = require('html-webpack-plugin');

let config = {
  entry: {
    app: __dirname + '/../src/app.js'
  },
  devtool: 'source-map',
  devServer: {
    stats: {
      modules: false,
      cached: false,
      colors: true,
      chunk: false
    },
    proxy: require('./devProxy')
  },
  module: {
    loaders: [{
      test: /\.js$/,
      loader: 'babel',
      exclude: /node_modules/,
      query: {
        presets: ['es2015', 'stage-0']
      }
    },
    {
      test: /\.css$/,
      loader: 'style!css'
    },
    {
      test: /\.html$/,
      loader: 'raw'
    }]
  },
  plugins: [
    new WebpackNotifierPlugin(),
    new HtmlWebpackPlugin({
      template: __dirname + '/../src/index.html',
      inject: 'body',
      minify: false
    })
  ]
};

module.exports = config;

最佳答案

你明确地从 babel-loader 中排除了 node_modules:

exclude: /node_modules/,

如果你想通过 babel 传递来自 node_modules 的模块,你需要调整它。您可能会考虑这样的显式包含:

// be sure to req path
// var path = require('path')

include: [
  // Include everything from your app path
  path.resolve(__dirname, 'my-app-js-path'),

  // Include gamesystem modules
  /\bgamesystem\b/,
],

关于javascript - Webpack 无法在外部包中构建 ES6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35273956/

相关文章:

javascript - 无法从全新安装在 npm 上运行脚本

Javascript 尝试根据内部对象数组值对对象数组进行排序

javascript - 是否有 ES6 快捷方式来比较元素数组和对象键并删除不匹配的元素?

javascript 引擎 v8 内联缓存

node.js - npm install --save-exact 不考虑确切的版本

javascript - 更改所选选项功能的输入

node.js - 尝试启动包裹开发服务器时出现问题

reactjs - React onClick `this` 绑定(bind)

javascript - Meteor 中的复合集合

JavaScript/Angular1 - Refacto 算法/逻辑条件