简体   繁体   English

找不到变量:数字

[英]Can't find variable: numeral

错误信息

declare let numeral:any;

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

I am using Angular2 + Webpack3. 我正在使用Angular2 + Webpack3。

Here is my webpack.config.ts and tsconfig.json. 这是我的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 file 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"
  ]
}

It seems you don't include numeral.js in your index.html 看来您的index.html中没有包含numeric.js

add this to your index.html 将此添加到您的index.html

  <script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>

This is by design, You can only access properties of the component from the template. 这是设计使然,您只能从模板访问组件的属性。

declare let numeral:any;

numeral is declared out of the component so it is inaccessible. numeral组件中声明出来,因此无法访问。

Edit: this should work 编辑:这应该工作

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'); 
  }
}

If you want to use numeral() in your template you should create a pipe 如果要在模板中使用digit(),则应创建一个管道

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

and use it this way 并以这种方式使用

<div>{{ myNumber | numeral }}</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM