Skip to content

Import lots of variables in a single line of code #10

@linonetwo

Description

@linonetwo
  • "codegen.macro": "^1.0.0",
  • node -v: v9.11.1
  • yarn -v: 1.3.2

I'm generating variables so that my colleague who doesn't know how to code can write simple code now.

[💖this part has no problem]

// ./memeTemplate/variables.js
const codegen = require('codegen.macro');

// preload formulas variables, and generate more variables, so my colleague can import them easily
codegen`
const fs = require('fs');

const formulasJSON = JSON.parse(fs.readFileSync(require.resolve('../formulas.json'), 'utf8'));
const variableNames = [
  ...Object.keys(formulasJSON),
  ...Object.keys(formulasJSON).map(name => '上期' + name),
  ...Object.keys(formulasJSON).map(name => '上上期' + name),
];

module.exports = variableNames
  .map(
    variableName =>
      'export var ' + variableName.replace(/[()、:()]/g, '') + ' = loader => loader.load("' + variableName + '")'
  )
  .join(';');
`;

[Here are problems]

// ./templates.js
// try to automatiously import variables
codegen`
  'const { ' + Object.keys(require('./memeTemplate/variables')).join(',') + '} = require("./memeTemplate/variables");'
`;


// using the automatiously imported variable
`
偿债能力分析
2017年流动资产合计为${流动资产合计}
`

Now it will show an error ./src/templates.js Module build failed: MacroError: The macro you imported from "undefined" is being executed outside the context of compilation with babel-plugin-macros. This indicates that you don't have the babel plugin "babel-plugin-macros" configured correctly. Please see the documentation for how to configure babel-plugin-macros properly

I had tried console.log( 'const { ' + Object.keys(require('./memeTemplate/variables')).join(',') + '} = require("./memeTemplate/variables");' );, it logs the correct require statement:

const { 净资产收益率,平均净资产, ...hugeAmountOfVariables } = require("./memeTemplate/variables");

And if I just import them statisticly:

import {
  销售利润率,
  流动比率,
  ...lotsToImport,
} from './memeTemplate/variables';

It works correctly.

So I can't use codegen to load code generated by codegen?
Or I can't use codegen to generate import statement?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions