Path: blob/main/src/rules/dynamic-import-chunkname.js
829 views
import vm from 'vm';1import docsUrl from '../docsUrl';23module.exports = {4meta: {5type: 'suggestion',6docs: {7url: docsUrl('dynamic-import-chunkname'),8},9schema: [{10type: 'object',11properties: {12importFunctions: {13type: 'array',14uniqueItems: true,15items: {16type: 'string',17},18},19webpackChunknameFormat: {20type: 'string',21},22},23}],24},2526create(context) {27const config = context.options[0];28const { importFunctions = [] } = config || {};29const { webpackChunknameFormat = '[0-9a-zA-Z-_/.]+' } = config || {};3031const paddedCommentRegex = /^ (\S[\s\S]+\S) $/;32const commentStyleRegex = /^( \w+: (["'][^"']*["']|\d+|false|true),?)+ $/;33const chunkSubstrFormat = ` webpackChunkName: ["']${webpackChunknameFormat}["'],? `;34const chunkSubstrRegex = new RegExp(chunkSubstrFormat);3536function run(node, arg) {37const sourceCode = context.getSourceCode();38const leadingComments = sourceCode.getCommentsBefore39? sourceCode.getCommentsBefore(arg) // This method is available in ESLint >= 4.40: sourceCode.getComments(arg).leading; // This method is deprecated in ESLint 7.4142if (!leadingComments || leadingComments.length === 0) {43context.report({44node,45message: 'dynamic imports require a leading comment with the webpack chunkname',46});47return;48}4950let isChunknamePresent = false;5152for (const comment of leadingComments) {53if (comment.type !== 'Block') {54context.report({55node,56message: 'dynamic imports require a /* foo */ style comment, not a // foo comment',57});58return;59}6061if (!paddedCommentRegex.test(comment.value)) {62context.report({63node,64message: `dynamic imports require a block comment padded with spaces - /* foo */`,65});66return;67}6869try {70// just like webpack itself does71vm.runInNewContext(`(function() {return {${comment.value}}})()`);72}73catch (error) {74context.report({75node,76message: `dynamic imports require a "webpack" comment with valid syntax`,77});78return;79}8081if (!commentStyleRegex.test(comment.value)) {82context.report({83node,84message:85`dynamic imports require a leading comment in the form /*${chunkSubstrFormat}*/`,86});87return;88}8990if (chunkSubstrRegex.test(comment.value)) {91isChunknamePresent = true;92}93}9495if (!isChunknamePresent) {96context.report({97node,98message:99`dynamic imports require a leading comment in the form /*${chunkSubstrFormat}*/`,100});101}102}103104return {105ImportExpression(node) {106run(node, node.source);107},108109CallExpression(node) {110if (node.callee.type !== 'Import' && importFunctions.indexOf(node.callee.name) < 0) {111return;112}113114run(node, node.arguments[0]);115},116};117},118};119120121