问题描述
我正在尝试让一个非常简单的 Angular2 应用程序工作,并将 Webpack 作为模块捆绑器.我正在关注 此代码,并且我按原样复制了所有配置文件,仅更改文件路径.但是,当我运行 npm-start
时,出现以下错误,我认为是 Webpack 错误:
I'm trying to get a very simple Angular2 app working, with Webpack as a module bundler. I'm following this code, and I copied all the configuration files as they are, only changing file paths. However, when I run npm-start
, I get the following error, which I think is a Webpack error:
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 代码未加载.
As a result, the Angular2 code in my app isn't loaded.
这是我的app.ts
:
import "./hello.js";
这是 hello.js
,错误似乎在其中(我认为 webpack 解析 app.ts 就好了):
This is hello.js
, where the error seems to be (which I take to mean that webpack parsed app.ts just fine):
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
都在同一个目录中.
All these files and node_modules
are in the same directory.
我在网上找到了类似的问题,但对我没有任何帮助.我也没有安装 babel,因为我用作基础的示例代码没有使用它,但如果有必要我会.
I have found similar questions online but nothing worked for me. I also didn't install babel because the sample code I'm using as base doesn't use it, but if it's necessary I'm will.
推荐答案
如@napstablook 所建议
As suggested by @napstablook
因为在你的 webpack.config.js 文件中你有
Since in your webpack.config.js file you have
resolve: {
extensions: ['', '.ts', '.js']
},
Webpack 会尝试处理那些 .js
文件,但它需要一个特定的加载器来处理,如果我没记错的话,script-loader
.
Webpack will try to handle those .js
files but it needs a specific loader to do so which is, if I'm not wrong, script-loader
.
在您的情况下,解决方案就像删除 .js
文件一样简单,或者将其扩展名更改为 .ts
.
In your case the solution is as simple as deleting the .js
files, or changing their extension to be .ts
.
这篇关于“您可能需要适合该文件类型的加载器",webpack 无法解析 angular2 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!