faker在mock数据的时候常常会用到,但是这次用到的时候遇到一个问题。

    问题:

    1. import * as faker from 'faker';
    2. faker.locale = 'zh_CN';

    image.png

    原因:
    es6在import一个模块的时候会自动设置变量为readonly/常量. 比如

    1. // hello-world/index.d.ts
    2. declare namespace Hello {
    3. interface World {
    4. name: string;
    5. }
    6. }
    7. declare const hello: Hello.World;
    8. declare module 'hello-world' {
    9. export = hello;
    10. }
    11. // 项目目录
    12. import * as hello from 'hello-world';
    13. hello.name // readonly

    解决:

    1. import hello = require('hello-world');
    2. hello.name = 'yuejiang';
    3. const faker = require('faker'); // 也可以,但是会报建议使用import,编辑器无法推导类型
    4. import faker = require('faker');
    5. faker.locale = 'zh_CN';