令人困惑的webpack / ES6项目设置

时间:2017-09-11 22:02:24

标签: javascript npm webpack ecmascript-6 es6-class

我正在尝试设置我的第一个ES6和webpack“应用程序”,并希望使用类和模块。但每次我想通过webpack命令转换应用程序时,我都会收到以下错误:

$ webpack
Hash: c91db5651ec9123b8959
Version: webpack 3.5.6
Time: 2319ms
    Asset       Size  Chunks                    Chunk Names
app.bundle.js     354 kB       0  [emitted]  [big]  main
   index.html  978 bytes          [emitted]
   [0] ./src/app.js 14 kB {0} [built]
    + 1 hidden module

ERROR in ./src/app.js
Module not found: Error: Can't resolve 'radar' in 'C:\dev\git\my-first-app\src'
 @ ./src/app.js 7:13-29
Child html-webpack-plugin for "index.html":
     1 asset
       [0] ./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html 1.37 kB {0} [built]
       [2] (webpack)/buildin/global.js 509 bytes {0} [built]
       [3] (webpack)/buildin/module.js 517 bytes {0} [built]
        + 1 hidden module

我有以下文件

的package.json

{
  "name": "my-first-app",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "build": "./node_modules/.bin/babel src -d dest",
    "start": "webpack-dev-server"
  }
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.0",
    "babel-preset-es2015": "^6.24.1",
    "webpack": "^3.5.6"
  },
  "dependencies": {
    "babel-polyfill": "^6.26.0",
    "d3": "3.5.17",
    "html-webpack-plugin": "^2.28.0",
    "webpack-dev-server": "^2.4.5"
  }
}

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: './src/app.js',
    output: {
        path: path.resolve(__dirname, 'dest'),
        filename: 'app.bundle.js'
    },
    module: {
        loaders: [
            {
                loader: 'babel-loader',
                include: [
                    path.resolve(__dirname, "src")
                ],
                test: /\.js$/
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'src/index.html',
            filename: 'index.html',
            inject: 'body'
        })
    ]
};

的src / app.js

'use strict';

import * as d3 from 'd3';
import radar from 'radar';

var r = new radar();
r.render();

radar.js

'use strict';

import * as d3 from 'd3';

export default class radar {
    render() { ... }
}

index.html是一些基本的HTML文件,它只包含一个带头部和正文的空文档。

我认为我的错误在webpack.config.js中某处,或者我混合使用不同的技术来使用ES6。命令npm build也无济于事(似乎没有任何反应)。 有谁可以帮助我吗?我有点困惑,不知道看什么/搜索......

1 个答案:

答案 0 :(得分:3)

radar是从app.js导入的,但它不在您的package.json依赖项列表中。 您可以从命令行运行npm install radar --save来安装软件包并在package.json

中保存引用

如果雷达是本地文件而不是包,则需要使用文件路径导入它。像:

import radar from './path/to/file/radar';

以下是在Webpack中解析import语句的方法 - https://webpack.js.org/concepts/module-resolution/