【问题标题】:load node_modules with webpack使用 webpack 加载 node_modules
【发布时间】:2017-02-19 16:58:05
【问题描述】:

我想加载一些模块,例如:

  • 时刻
  • 图表

我的 package.json:

  • “图表”:“^3.1.10”
  • “时刻”:“^2.14.1”

但我有下一个错误:

VM2282:1 Uncaught ReferenceError: moment is not defined(…)

我的 Webpack 配置:

{ test: /\.js$/, loader: 'babel', exclude: /node_modules/ }

我不知道发生了什么。有人可以帮帮我吗?

【问题讨论】:

  • 我认为你还没有发布所有相关代码,是吗?
  • 您是否手动要求('moment')?您至少应该粘贴产生错误的代码。
  • 我有一个 Angular 2 项目,我在 src/main.browser.ts 中编写了 require('moment')。我的项目与:github.com/AngularClass/angular2-webpack-starter 相同,因为我使用这个项目作为模板。非常感谢。

标签: javascript node.js angular webpack


【解决方案1】:

添加到 vendor.ts:

import 'echarts';
import 'moment';

并从 webpack 配置中删除您的代码。 这对我有用。

【讨论】:

  • 感谢您的回答:我可以在 vendor.bundle.js 中看到对 moment 和 echarts 的引用,但我无法访问 moment() 方法。例如,我打开 Chrome 控制台,我写了 moment() 并出现下一个错误:VM350:1 Uncaught ReferenceError: moment is not defined(...)。
  • 嘿!从 vendor.ts 中删除导入!添加到您正在编写代码“import * as moment from 'moment'”的 .ts 文件中,webpack 将从 node_modules 导入 moment 库。
【解决方案2】:
import { Component } from '@angular/core';
import * as moment from 'moment';
import '../../public/css/styles.css';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent { 

  constructor(){
    let now = moment().format('LLLL');
    console.log(now)
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    • 2018-07-15
    • 2016-03-22
    • 2017-04-16
    • 1970-01-01
    • 2017-07-16
    相关资源
    最近更新 更多