0

错误信息

declare let numeral:any;

@Component({     
      //moduleId: module.id,     
      selector: 'app-dashboard',   
      templateUrl: './dashboard.component.html',     
      styleUrls:  hboard.component.css' 
})

我正在使用 Angular2 + Webpack3。

这是我的 webpack.config.ts 和 tsconfig.json。

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');


function webpackConfig(options: EnvOptions = {}): WebpackConfig {

  return {
      cache: false,

      entry: {
          polyfills: './src/polyfills',
          vendor:       './src/vendor',
          main:           './src/main'
      },

      output: {
          path: path.join(__dirname, '/public'),
          filename: '[name].bundle.js',
          sourceMapFilename: '[name].map',
          chunkFilename: '[id].chunk.js'
      },

      module: {
          loaders: [


               { test:/\.ts$/,loaders:['awesome-typescript-loader','angular2-template-loader']},
               { test: /\.json$/,loader:'json-loader'},
               { test: /\.html$/, loader:'html-loader'},
               { test: /\.(css|scss)$/, loaders:['to-string-loader','css-loader','sass-loader'] },
               { test: /\.json$/, loader: 'raw-loader' },
               { test: /\.(png|woff|woff2|eot|ttf|svg)(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=100000' }
          ]
      },

      plugins: [
              new HtmlWebpackPlugin({
                      template: './src/index.html',
                      filename: './index.html',
                      inject: 'body'
              }),

              new webpack.LoaderOptionsPlugin({
                  debug: true,
                  options: {
                      context: __dirname,   
                      output: { path :   './' }, //This has to be './' and not your output folder.
                      sassLoader: {
                          includePaths: [path.resolve(__dirname, 'src', 'scss')]
                      }
                  }
              }),
              new webpack.HotModuleReplacementPlugin(),
              new webpack.optimize.CommonsChunkPlugin({
                      name: ['main', 'vendor', 'polyfills'],
                      minChunks: Infinity
              }),
              new webpack.ContextReplacementPlugin(
                      /@angular(\\|\/)core/,
                      path.join(__dirname, 'src'),
                      {}
              ),
              new webpack.DefinePlugin({
                      ENV: JSON.stringify(options.ENV),
                      HMR: options.HMR
              })
      ],

      devtool: 'cheap-eval-source-map',
      resolve: {
          modules: [ path.join(__dirname, 'node_modules/'), path.join(__dirname, 'src/')],
          extensions: ['.ts', '.js', '.json', '.html']
      },

      devServer: {
          contentBase: path.join(__dirname, '/public'),
          port: 4200,
          historyApiFallback: true
      }
  };
}

// Export
module.exports = logOptions(webpackConfig);

function logOptions(fn) {
  return function(options: EnvOptions = {}) {
      console.log('Env Options: ', JSON.stringify(options, null, 2));
      return fn(options);
  };
}

// Types
type Entry = Array<string> | Object;

type Output = Array<string> | {
  path: string,
  filename: string
};

type EnvOptions = any;

interface WebpackConfig {
  cache?: boolean;
  devtool?: string;
  entry: Entry;
  output: any;
  module?: {
      loaders?: Array<any>
  },
  plugins?: Array<any>;
  resolve?: {
      extensions?: Array<string>;
      modules: Array<string>;
  },
  devServer?: {
      contentBase?: string;
      port?: number;
      historyApiFallback?: boolean;
      hot?: boolean;
  }
}

tsconfig.json 文件

 {
  "compileOnSave": false,
  "compilerOptions": {
      "module" : "commonjs",
      "moduleResolution": "node",
      "declaration": false,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "noEmitOnError": true,
      "noImplicitAny": false,
      "removeComments": false,
      "outDir": "./public",
      "sourceMap": false,
      "target": "es5",
      "lib": [
          "es2015",
          "dom"
      ],
      "baseUrl": ".",
      "paths": {
          "@angular/*": ["node_modules/@angular/*"]
      },
      "typeRoots": [
          "node_modules/@types"
      ],
      "types": [
          "node"
      ]
  },
  "include" : [
      "src/app/**/*"
  ],
  "exclude": [
      "node_modules",
      "public",
      "src/app/**/*.spec.ts",
      "src/app/**/*.e2e.ts"
  ],
  "files": [
      "main.ts",
      "./src/app/**/*.ts"
  ]
}
4

2 回答 2

2

您的 index.html 中似乎没有包含 numeric.js

将此添加到您的 index.html

  <script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
于 2017-11-01T15:54:33.703 回答
2

这是设计使然,您只能从模板访问组件的属性。

declare let numeral:any;

numeral被声明在组件之外,因此它是不可访问的。

编辑:这应该工作

import { Component } from '@angular/core';

import numeral from 'numeral';

@Component({
  selector: 'my-app',
  template: `{{myNumber}}`,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  get myNumber () {
     numeral(1000).format('0,0'); 
  }
}

如果你想在你的模板中使用 numeric() 你应该创建一个管道

import numeral from 'numeral';
@Pipe({
name:'numeral'
})
@Injectable()
export class NumeralPipe implements PipeTransform{
    transform(myNumber:any):any{ 
      numeral(1000).format('0,0'); 
    }; 
} 

并以这种方式使用它

<div>{{ myNumber | numeral }}</div>
于 2017-11-01T14:07:15.193 回答