webpack анализирует node_modules так же, как и другие js-файлы

1

Я взял на себя проект, который использует webpack, и я не слишком уверен в том, как все это все вместе, но у меня возникают проблемы при переходе кода из проекта в пакеты npm - мы пытаемся сделать некоторые js-пакеты npm, поэтому мы можем использовать их в нескольких проектах.

Вот пример - если у меня есть следующий код в проекте:

const combinedFilters = {
  ...currentFilters,
  ...filters,
};

Это будет скомпилировано без проблем, но если я переведу его в пакет npm, я получаю следующую ошибку:

Module parse failed: C:\Code Team Services\Web\SiteFiles\src\node_modules\@private\search\filter\SearchBaseFilter.js Unexpected token(31: 6)
You may need an appropriate loader to handle this file type.
|     // Combine new filters with old filters.
|     const combinedFilters = {
|       ...currentFilters,
|       ...filters,
|     };

Это мой конфигуратор webpack - есть ли что-то, что я могу добавить (или удалить) здесь, чтобы заставить загрузчик также анализировать пакеты npm?

/* eslint-disable func-names, no-useless-escape, object-shorthand */

// modules
const merge = require('webpack-merge');
const path = require('path');
const webpack = require('webpack');

// webpack plugins
const AssetsPlugin = require('assets-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const StatsWriterPlugin = require('webpack-stats-plugin').StatsWriterPlugin;

// load base configuration.
const baseConfig = require('./webpack.config');

// Get paths.
const paths = require('../core/paths');

module.exports = merge.smart(baseConfig, {
  cache: true,
    // Enable sourcemaps - see https://webpack.js.org/configuration/devtool/
    // Also see the point about using Uglify in combination with devtool and webpack
    // To disable sourcemaps comment out the line below
  devtool: 'source-map',

  // Define the entry points - each of these creates a new file.
  entry: {
    critical: ['sass/critical.scss'],
    styleguide: ['sass/styleguide.scss'],
    main: [
      'webpack/hot/dev-server',
      'webpack-hot-middleware/client?reload=true',
      'sass/main.scss',
      'js/main',
    ],
  },

  module: {
    rules: [
      {
        test: /\.(eot|ttf|woff|woff2)(\?.+)?$/,
        // Use the file-loader to include referenced fonts in dist folder.
        use: ['file-loader'],
      },
      {
          test: /\.(jpeg|jpg|gif|png|svg)(\?.+)?$/,
          use: [
            {
                // Use the url-loader to convert images to Data URIs.
                loader: 'url-loader',
                options: { limit: 10000 },
            },
            //{
            //    // Use the image-webpack-loader to optimize images and reduce overall file size.
            //    loader: 'image-webpack-loader',
            //},
          ],
      }
    ],
  },

  output: {
    // Define file naming convention - chunkhash is used to bypass the browser cache.
    chunkFilename: '[name].js',
    filename: '[name].js',

    // Define where generated assets will be located.
    path: paths.dist,

    // Define URL for output file path (as above).
    publicPath: paths.mvcAppPath + '/sitefiles/dist/',
  },

  plugins: [
    // Remove existing assets from dist folder.
    new CleanWebpackPlugin([paths.dist], {
      exclude: ['.gitignore', 'fallback'],
      root: paths.sitefiles,
    }),
    // Create JSON file containing the names of generated assets - used by styleguide and MVC site.
    new AssetsPlugin({
      filename: 'assets.json',
      path: paths.dist,
    }),
    // Reduce number of locales loaded by Moment JS.
    new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en-gb/),
    // Define constants to be accessed in source code.
    new webpack.DefinePlugin({
      // The Google Maps API key.
      GOOGLE_MAPS_API_KEY: JSON.stringify(''),
      // The URL prefix for local API calls.
      URL_VIRTUAL_PATH: JSON.stringify(paths.mvcAppPath),
      // This enables production mode on some modules.
      'process.env': {
        NODE_ENV: JSON.stringify('development'),
      },
    }),
    // Use the ExtractTextPlugin to move CSS to a separate file.
    new ExtractTextPlugin({
      allChunks: true,
      disable: false,
      filename: '[name].css',
    }),
    // Write bundle statistics to file for analysis and debugging tools.
    new StatsWriterPlugin({
      transform(data, opts) {
        const stats = opts.compiler.getStats().toJson({ chunkModules: true });
        return JSON.stringify(stats, null, 2);
      },
    }),
    // Enable HMR (https://webpack.js.org/guides/hot-module-replacement/).
    new webpack.HotModuleReplacementPlugin(),
    // Do not write files to disk when errors occur during bundling.
    new webpack.NoEmitOnErrorsPlugin(),
  ],
});

Это базовая конфигурация webpack:

/* eslint-disable func-names, no-useless-escape, object-shorthand */

// webpack plugins
const ExtractTextPlugin = require('extract-text-webpack-plugin');

// Get paths.
const paths = require('../core/paths');

const baseConfig = {
  // These modules will be loaded outside of webpack e.g. via a CDN.
  externals: {
    jquery: 'jQuery',
  },

  // Define which loaders will be used for different file extensions.
  module: {
    rules: [{
        test: /\.html$/,
        use: [
          // Use the html-loader to parse and minify HTML imports.
          'html-loader',
        ],
      },
      {
        test: /\.js$/,
        use: [{
          // Use the eslint-loader to validate the JS files before bundling.
          loader: 'eslint-loader',
          options: {
            ignorePath: paths.eslintIgnore
          },
        }, ],
        enforce: 'pre',
        include: [paths.js],
        exclude: [paths.vendor],
      },
      {
        test: /\.js$/,
        use: [{
          // Use the babel-loader to transpile the JS to browser-compatible syntax.
          loader: 'babel-loader',
        }],
        include: [paths.js],
        exclude: [paths.vendor],
      },
      {
        test: /\.(css|scss)$/,
        // Use the ExtractTextPlugin to move CSS to a separate file.
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [{
              // Use the css-loader to parse and minify CSS imports.
              // N.B Sourcemaps enabled, but wont be output if devtool setting is commented out
              loader: 'css-loader',
              options: {
                autoprefixer: false,
                sourceMap: true
              },
            },
            {
              // Use the postcss-loader to add vendor prefixes via autoprefixer.
              // N.B Sourcemaps enabled, but wont be output if devtool setting is commented out
              loader: 'postcss-loader',
              options: {
                config: {
                  path: paths.postcssConfig
                },
                sourceMap: true
              },
            },
            {
              // Use the sass-loader to parse and minify CSS imports.
              // N.B Sourcemaps enabled, but wont be output if devtool setting is commented out
              loader: 'sass-loader?sourceMap',
              options: {
                sourceMap: true
              },
            },
          ],
          publicPath: paths.mvcAppPath + '/sitefiles/dist/',
        }),
      },
      {
        test: /loadcss\.js$/,
        use: [
          // Shim fg-loadcss to access the window object.
          'imports-loader?exports=>undefined',
          'exports-loader?window.loadCSS',
        ],
        exclude: [paths.js],
        include: /fg-loadcss/,
      },
      {
        test: /cssrelpreload\.js$/,
        use: [
          // Shim fg-loadcss to access the window object.
          'imports-loader?this=>window',
        ],
        exclude: [paths.js],
        include: /fg-loadcss/,
      },
      {
        test: /waypoints\.js$/,
        use: [
          // Shim waypoints to access the window object.
          'exports-loader?window.Waypoint',
        ],
        exclude: [paths.js],
        include: /waypoints/,
      },
      {
        test: /\.js$/,
        use: [
          // Shim videojs to force correct module syntax.
          'imports-loader?this=>window&exports=>false&define=>false',
        ],
        exclude: [paths.js],
        include: /video\.js/,
      },
      {
        test: /\.js$/,
        use: [
          // Shim videojs to force correct module syntax.
          'imports-loader?this=>window&exports=>false&define=>false',
        ],
        exclude: [paths.js],
        include: /videojs-youtube/,
      },
    ],

    noParse: [
      // Ignore prebuilt warning for videojs
      /[\/\\]video\.js$/,
      /[\/\\]video\.min\.js$/,
      /[\/\\]videojs-youtube/,
    ],
  },

  resolve: {
    alias: {
      // Add aliases for common source folders.
      fonts: paths.fonts,
      img: paths.img,
      js: paths.js,
      sass: paths.sass,
      vendor: paths.vendor,

      // Add aliases for vendor modules.
      'loadcss-core': 'fg-loadcss/src/loadcss',
      'loadcss-polyfill': 'fg-loadcss/src/cssrelpreload',
      'videojs-core': 'video.js/dist/video.js',
      'videojs-youtube': 'videojs-youtube/dist/Youtube',
      'waypoints-core': 'waypoints/lib/jquery.waypoints.js',
      'waypoints-infinite': 'waypoints/lib/shortcuts/infinite.js',
      'waypoints-inview': 'waypoints/lib/shortcuts/inview.js',
      'waypoints-sticky': 'waypoints/lib/shortcuts/sticky.js',
    },
  },
};

module.exports = baseConfig;
  • 0
    в качестве примера пакета npm вы можете смоделировать WP.config здесь: github.com/material-components/material-components-web/blob/… И затем, если необходимо, на основе пакетов, не исключайте ваши пакеты в соответствии с обычной директивой обойти ./node_modules
  • 1
    Я предполагаю, что node_modules находится в вашем paths.vendor который исключен из вашей конфигурации. Вы можете попробовать добавить node_modules / your_package во включаемый файл, где у вас есть paths.js .
Показать ещё 1 комментарий
Теги:
webpack
npm

1 ответ

2
Лучший ответ

Проблема в том, что node_modules обычно исключается в конфигурациях webpack. В вашем случае это, вероятно, содержится в переменной paths.vendor которая исключена. Путь, который все еще должен быть включен, может быть добавлен в параметр include (в вашем случае он содержит значение paths.js).

См. Https://webpack.js.org/configuration/module/#rule-exclude и https://webpack.js.org/configuration/module/#rule-include.

Обратите внимание, что это значение также может быть массивом, поэтому вы можете оставить свою конфигурацию такой, какой она есть, и просто добавить дополнительные дополнительные пути или условия в массив.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню