require变量形式动态取资源he webpack

2,868 阅读1分钟

webpack使用

  import(
        /* webpackChunkName:"[request]"*/ "./pel/" + chartsOnly + "/core"
      ).then(({ renderDefault }) => {
        let instance = new renderDefault(option, optionSet);
        }))

require()中给一个变量为参数,根据实际要求加载不同的内容,但是require直接加变量会报错,实际import也会报错的。can’t require module’.’

采用es6的模板字符串,将字符串分为三部分,并在字符串中用${}包裹变量,

例如:var name;

require(`pages/${name}.js`);

当使用require去请求资源时,如果路径为变量则需要使用反引号去拼接(此处拼接必须包含字符串才可以成功),不能直接使用变量,需要变量和一个非空字符串用反引号拼接

let url="www.baidu"
let result=require(`${url}.com`)//这是正确的
//错误示例
//require(`${url}`)
//require(`${url}`+'')
//require(url)

备注:

// webpack.config.js

{
  module: {
    // require
    unknownContextRegExp: /$^/,
    unknownContextCritical: false,

    // require(expr)
    exprContextRegExp: /$^/,
    exprContextCritical: false,

    // require("prefix" + expr + "surfix")
    wrappedContextRegExp: /$^/,
    wrappedContextCritical: false
  }
}

require.context 参考官方文档

语法:

require.context(directory, useSubdirectories = false, regExp = /^.//)
  • 1

require.context有三个参数:

  • directory:说明需要检索的目录
  • useSubdirectories:是否检索子目录
  • regExp: 匹配文件的正则表达式

使用介绍:

var context = require.context('.', true, /^./less/.*.css$/);//参数3正则介绍:扫描./less/目录下所有以.css结尾的文件
console.log(context.keys());//获取正则less目录下文件,转化成数组形势 =>例如: ['a.css','b.css']等
const filename = "./less/r.css";
console.log(context(filename));

require with expression

A context is created if your request contains expressions, so the exact module is not known on compile time.

Example, given we have the following folder structure including .ejs files:

example_directory
│
└───template
│   │   table.ejs
│   │   table-row.ejs
│   │
│   └───directory
│       │   another.ejs

When following require() call is evaluated:

require('./template/' + name + '.ejs');

Webpack parses the require() call and extracts some information:

Directory: ./template
Regular expression: /^.*.ejs$/

context module

A context module is generated. It contains references to all modules in that directory that can be required with a request matching the regular expression. The context module contains a map which translates requests to module ids.

Example map:

{
  "./table.ejs": 42,
  "./table-row.ejs": 43,
  "./directory/another.ejs": 44
}

The context module also contains some runtime logic to access the map.

This means dynamic requires are supported but will cause all matching modules to be included in the bundle.

require.context

You can create your own context with the require.context() function.

It allows you to pass in a directory to search, a flag indicating whether subdirectories should be searched too, and a regular expression to match files against.

Webpack parses for require.context() in the code while building.

The syntax is as follows:

require.context(
  directory,
  (useSubdirectories = true),
  (regExp = /^./.*$/),
  (mode = 'sync')
);

Examples:

require.context('./test', false, /.test.js$/);
// a context with files from the test directory that can be required with a request ending with `.test.js`.
require.context('../', true, /.stories.js$/);
// a context with all files in the parent folder and descending folders ending with `.stories.js`.
Warning

The arguments passed to require.context must be literals!

context module API

A context module exports a (require) function that takes one argument: the request.

The exported function has 3 properties: resolvekeysid.

  • resolve is a function and returns the module id of the parsed request.
  • keys is a function that returns an array of all possible requests that the context module can handle.

This can be useful if you want to require all files in a directory or matching a pattern, Example:

function importAll(r) {
  r.keys().forEach(r);
}

importAll(require.context('../components/', true, /.js$/));
const cache = {};

function importAll(r) {
  r.keys().forEach((key) => (cache[key] = r(key)));
}

importAll(require.context('../components/', true, /.js$/));
// At build-time cache will be populated with all required modules.
  • id is the module id of the context module. This may be useful for module.hot.accept.

Edit this page·Print this page