无法使用webpack和index.js文件引导角度1.x应用程序

时间:2017-03-11 10:35:35

标签: angularjs webpack

所以,我有一个有效的webpack配置文件:

var webpack =  require('webpack');
var path = require('path');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var ChunkManifestPlugin = require("chunk-manifest-webpack-plugin");
var WebpackChunkHash = require("webpack-chunk-hash");
var OpenBrowserPlugin =  require("open-browser-webpack-plugin");
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports =  {
entry: {
    main: './index.js',
    vendors: './vendors.js'
},
output: {
    filename: '[name].js',
    chunkFilename: "[name].[chunkhash].js",
    path: path.resolve(__dirname, 'dist')
},
module: {
        rules: [
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    use: 'css-loader'
                })
            },
            {
                test: /\.html$/,
                use: 'raw-loader'
            }
        ]
},
plugins: [
    new HtmlWebpackPlugin({
        template: 'index.html',
        filename: 'index.html',
        inject: 'body'}),
    new webpack.optimize.CommonsChunkPlugin({
        names: ['vendor', 'manifest'],
        minChunks: function (module) {
            return module.context && module.context.indexOf('node_modules') !== -1;
        }
    }),
    new ChunkManifestPlugin({
        filename: "chunk-manifest.json",
        manifestVariable: "webpackManifest"
    }),
    new webpack.HashedModuleIdsPlugin(),
    new WebpackChunkHash(),
    new ExtractTextPlugin('styles.css'),
    new OpenBrowserPlugin({ url: 'http://localhost:3000' }),
],
devtool: "inline-source-map",
devServer: {
    contentBase: path.join(__dirname, "app"),
    watchContentBase: true,
    watchOptions: {
        poll: true
    },
    compress: true,
    port: 3000,
    clientLogLevel: 'error'
 }
};

现在,这是我的文件夹结构:

|-- root
|-- index.html
|-- index.js
|-- package.json
|-- vendors.js
|-- webpack.config.js
|-- app
|   |-- index.js
|   |-- shared
|       |-- index.js
|       |-- navbar
|           |-- index.js

vendors.js:

require('angular');
require('moment');

index.js:

module.exports = function () {
 require('./app')();
};

应用程序/ index.js:

var angular = require('angular');
module.exports = function () {
    angular.module('app', []);
};

我的index.html有一个<html ng-app="app">绑定

但是当我运行我的webpack时,找不到这样的模块 我不确定自从我在index.html所有的捆绑包中看到了什么。

我收到此错误:

  

未捕获错误:[$ injector:modulerr]由于以下原因无法实例化模块应用程序:   错误:[$ injector:nomod]模块'app'不可用!您要么错误拼写了模块名称,要么忘记加载它。如果注册模块,请确保将依赖项指定为第二个参数。

1 个答案:

答案 0 :(得分:0)

这里的问题是你的顶级 index.js文件没有创建你的angular.module它导出一个创建它的函数。由于永远不会调用此函数,因此模块永远不会在AngularJS中注册,从而导致指示错误。

您当前的顶级index.js文件看起来像

module.exports = function () {
  require('./app')();
};

这定义了一个CommonJS模块,其值是一个动态导入和注册角度应用程序的函数。 由于我们想要引导应用程序,最简单的方法是将顶级index.js文件更改为

require('./app')();

注意没有包装,也没有导出。

如果我们想要通过另一个模块公开应用程序以进行导入,同时仍然可以引导它,我们可以改为编写

module.exports = require('./app')();