node.js - "You may need an appropriate loader for this file type", webpack 无法解析 angular2 文件

标签 node.js angular webpack

我正在尝试让一个非常简单的 Angular2 应用程序运行,并使用 Webpack 作为模块 bundler 。我正在关注this code ,我按原样复制了所有配置文件,仅更改了文件路径。但是,当我运行 npm-start 时,出现以下错误,我认为这是一个 Webpack 错误:

ERROR in ./hello.js
Module parse failed: /home/marieficid/Documentos/cloud/cloud/hello.js Line 1: Unexpected token
You may need an appropriate loader to handle this file type.
| import {bootstrap} from "angular2/platform/browser";
| import {Component} from "angular2/core";
| 
 @ ./app.ts 2:0-21

因此,我的应用中的 Angular2 代码未加载。

这是我的app.ts:

import "./hello.js"; 

这是 hello.js,其中的错误似乎是(我认为这意味着 webpack 解析了 app.ts 很好):

import {bootstrap} from "angular2/platform/browser";
import {Component} from "angular2/core";

@Component({
    selector: 'app',
    template: '<div>Hello world</div>'
})
class App{}

bootstrap(App);

这是webpack.config.js:

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

module.exports = {
  entry: {
    'app': './app.ts',
    'vendor': './vendor.ts'
  },
  output: {
    path: "./dist",
    filename: "bundle.js"
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'),
    new HtmlWebpackPlugin({
      inject: false,
      template: './index.html'
    })       
  ],

  resolve: {
    extensions: ['', '.ts', '.js']
  },

  module: {
    loaders: [
      { test: /\.ts$/, loader: 'ts-loader' },
    ],
    noParse: [ path.join(__dirname, 'node_modules', 'angular2', 'bundles') ]
  },

  devServer: {
    historyApiFallback: true
  }
};

所有这些文件和node_modules都位于同一目录中。

我在网上发现了类似的问题,但对我来说没有任何作用。我也没有安装 babel,因为我用作基础的示例代码没有使用它,但如果有必要,我会的。

最佳答案

按照@napstablook的建议

因为在你的 webpack.config.js 文件中你有

resolve: {
   extensions: ['', '.ts', '.js']
},

Webpack 将尝试处理这些 .js 文件,但它需要一个特定的加载器来执行此操作,如果我没记错的话,script-loader .

就您而言,解决方案非常简单,只需删除 .js 文件,或将其扩展名更改为 .ts

关于node.js - "You may need an appropriate loader for this file type", webpack 无法解析 angular2 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35990003/

相关文章:

node.js - 在mongodb中的特定值之后插入一个数组项

node.js - Typeorm 急切加载不适用于一对一关系

jquery - 关于在加载 Angular 2 应用程序时要做什么的一些问题

php - 当 SPA 中的路由发生变化时,http 请求会发生什么情况

javascript - Angular2 cli (Webpack) 为不同模块创建 block

node.js - 在express js和node js上创建动态子域

node.js - 将Electron + Puppeteer打包为.exe

javascript - 中等缩放实现在 Angular 13 中不起作用

webpack - 在 Electron 窗口中禁用 webSecurity 是显示本地镜像的唯一方法吗?

javascript - webpack: "[ERR_REQUIRE_ESM]: Must use import to load ES Module"- 但我正在使用导入!