【问题标题】:Webpack - The selector "my-app" did not match any elementsWebpack - 选择器“my-app”不匹配任何元素
【发布时间】:2018-09-23 00:56:05
【问题描述】:

我正在尝试在 Visual Studio for Angular 应用程序中实现 Webpack。

Webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const source = path.resolve(__dirname, 'src', 'index.ts');
const destination = path.resolve(__dirname, 'dist');

module.exports = {
    entry: source,
    output: {
        filename: 'index.js',
        path: destination
    },
    resolve: {
        extensions: ['.ts', '.js']
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                loaders: ['awesome-typescript-loader', 'angular2-template-loader']
            },
            {
                test: /\.(css|html)$/,
                loader: 'raw-loader'
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html'
        }),
    ]
};

Index.html

   <!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <script src="index.js"></script>
</head>
<body>
    <my-app>Loading...</my-app>
    <script src="index.js"></script>
<script type="text/javascript" src="index.js"></script></body>
</html>

我可以通过运行 webpack 命令来构建捆绑文件,但是当我运行 Visual Studio 并指向 index.html 时,它会抛出错误:

选择器“my-app”没有匹配任何元素

我不确定我错过了什么,我查看了所有互联网 SO、Git、Webpack 文档等,但没有发现任何有用的东西。

【问题讨论】:

  • 您是否考虑过从 Angular CLI 作为构建工具开始?
  • 这样我会更容易理解,但我正在尝试从头开始实现它以便完全理解。
  • 你可以随时分离他们的 webpack 配置,看看他们设置了什么和你做了什么。
  • 如果您使用 CLI 创建示例项目,您可以运行 ng eject 命令,它将为您提供他们正在使用的整个 webpack.config.js 文件。
  • 我不认为 webpack.config 有问题,因为创建了 bundle。无论如何我正在使用官方文档来创建配置文件。我已经在上面发布了我的配置文件,如果你能指出我是否遗漏了一些很有帮助的东西。

标签: angular visual-studio typescript webpack


【解决方案1】:

你的 html 模板加载你的 index.js 文件三次是有原因的吗?我认为您上面的错误是由于第一次将脚本包含在文档的头部。

<!DOCTYPE html>
<html>
<head>
    ...
    <script src="index.js"></script> <!-- this guy here -->
</head>
...
</html>

我测试将我的 Angular 脚本移动到头部并收到相同类型的错误。

【讨论】:

  • webpack 是这样生成的。
  • 查看你的'./src/index.html' 文件,我敢打赌你有&lt;script&gt; 标签包含在其中。我的猜测是 WebPack 将最后一个放在那里:&lt;script type="text/javascript" src="index.js"&gt;&lt;/script&gt;
  • 你是对的。我在 src/index 中包含了脚本,这使得捆绑文件重复相同的脚本导致错误。多谢。 :)
猜你喜欢
  • 2016-06-09
  • 2016-11-24
  • 2016-06-09
  • 1970-01-01
  • 1970-01-01
  • 2016-05-16
  • 2020-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多