Предоставьте не минимизированного поставщика javascript, используя конфигурацию webpack - PullRequest
0 голосов
/ 04 апреля 2020

Я собираю приложение aurelia, используя aurelia-cli 1.3 и webpack 4.4. В рамках этого у меня установлены различные узловые модули, которые поставляют css и javascript.

В моей среде разработки я хочу получить не минифицированного поставщика js - или, по крайней мере, указать c поставщика js.

Это, в частности, oidc-client , Но, тем не менее, есть ли хорошие стратегии, которые вы можете использовать, чтобы легко включить полный js / minified js?

Таким образом, файлы существуют здесь:

node_modules \ oid c -client \ lib \ oid c -client. js
node_modules \ oid c -client \ lib \ oid c -client.min. js

Вот мои файлы ...

webpack.config. js

Приложение было создано с использованием aurelia-cli, которое генерирует следующую конфигурацию веб-пакета:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const DuplicatePackageCheckerPlugin = require('duplicate-package-checker-webpack-plugin');
const project = require('./aurelia_project/aurelia.json');
const { AureliaPlugin, ModuleDependenciesPlugin } = require('aurelia-webpack-plugin');
const { ProvidePlugin } = require('webpack');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

// config helpers:
const ensureArray = (config) => config && (Array.isArray(config) ? config : [config]) || [];
const when = (condition, config, negativeConfig) =>
  condition ? ensureArray(config) : ensureArray(negativeConfig);

// primary config:
const title = 'My App';
const outDir = path.resolve(__dirname, project.platform.output);
const srcDir = path.resolve(__dirname, 'src');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const baseUrl = '/';

const cssRules = [
  { loader: 'css-loader' },
];

const sassRules = [
  {
    loader: "sass-loader",
    options: {
      sassOptions: {
        includePaths: ['node_modules']
      }
    }
  }
];

module.exports = ({ production } = {}, { extractCss, analyze, tests, hmr, port, host } = {}) => ({
  resolve: {
    extensions: ['.ts', '.js'],
    modules: [srcDir, 'node_modules'],

    alias: {
      // https://github.com/aurelia/dialog/issues/387
      // Uncomment next line if you had trouble to run aurelia-dialog on IE11
      // 'aurelia-dialog': path.resolve(__dirname, 'node_modules/aurelia-dialog/dist/umd/aurelia-dialog.js'),

      // https://github.com/aurelia/binding/issues/702
      // Enforce single aurelia-binding, to avoid v1/v2 duplication due to
      // out-of-date dependencies on 3rd party aurelia plugins
      'aurelia-binding': path.resolve(__dirname, 'node_modules/aurelia-binding')
    }
  },
  entry: {
    app: [
      // Uncomment next line if you need to support IE11
      // 'promise-polyfill/src/polyfill',
      'aurelia-bootstrapper'
    ]
  },
  mode: production ? 'production' : 'development',
  output: {
    path: outDir,
    publicPath: baseUrl,
    filename: production ? '[name].[chunkhash].bundle.js' : '[name].[hash].bundle.js',
    sourceMapFilename: production ? '[name].[chunkhash].bundle.map' : '[name].[hash].bundle.map',
    chunkFilename: production ? '[name].[chunkhash].chunk.js' : '[name].[hash].chunk.js'
  },
  optimization: {
    runtimeChunk: true,  // separates the runtime chunk, required for long term cacheability
    // moduleIds is the replacement for HashedModuleIdsPlugin and NamedModulesPlugin deprecated in https://github.com/webpack/webpack/releases/tag/v4.16.0
    // changes module id's to use hashes be based on the relative path of the module, required for long term cacheability
    moduleIds: 'hashed',
    // Use splitChunks to breakdown the App/Aurelia bundle down into smaller chunks
    // https://webpack.js.org/plugins/split-chunks-plugin/
    splitChunks: {
      hidePathInfo: true, // prevents the path from being used in the filename when using maxSize
      chunks: "initial",
      // sizes are compared against source before minification
      maxSize: 200000, // splits chunks if bigger than 200k, adjust as required (maxSize added in webpack v4.15)
      cacheGroups: {
        default: false, // Disable the built-in groups default & vendors (vendors is redefined below)
        // You can insert additional cacheGroup entries here if you want to split out specific modules
        // This is required in order to split out vendor css from the app css when using --extractCss
        // For example to separate font-awesome and bootstrap:
        // fontawesome: { // separates font-awesome css from the app css (font-awesome is only css/fonts)
        //   name: 'vendor.font-awesome',
        //   test:  /[\\/]node_modules[\\/]font-awesome[\\/]/,
        //   priority: 100,
        //   enforce: true
        // },
        // bootstrap: { // separates bootstrap js from vendors and also bootstrap css from app css
        //   name: 'vendor.font-awesome',
        //   test:  /[\\/]node_modules[\\/]bootstrap[\\/]/,
        //   priority: 90,
        //   enforce: true
        // },

        // This is the HTTP/1.1 optimised cacheGroup configuration
        vendors: { // picks up everything from node_modules as long as the sum of node modules is larger than minSize
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          priority: 19,
          enforce: true, // causes maxInitialRequests to be ignored, minSize still respected if specified in cacheGroup
          minSize: 30000 // use the default minSize
        },
        vendorsAsync: { // vendors async chunk, remaining asynchronously used node modules as single chunk file
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors.async',
          chunks: 'async',
          priority: 9,
          reuseExistingChunk: true,
          minSize: 10000  // use smaller minSize to avoid too much potential bundle bloat due to module duplication.
        },
        commonsAsync: { // commons async chunk, remaining asynchronously used modules as single chunk file
          name: 'commons.async',
          minChunks: 2, // Minimum number of chunks that must share a module before splitting
          chunks: 'async',
          priority: 0,
          reuseExistingChunk: true,
          minSize: 10000  // use smaller minSize to avoid too much potential bundle bloat due to module duplication.
        }
      }
    }
  },
  performance: { hints: false },
  devServer: {
    contentBase: outDir,
    // serve index.html for all 404 (required for push-state)
    historyApiFallback: true,
    hot: hmr || project.platform.hmr,
    port: port || project.platform.port,
    host: host
  },
  devtool: production ? 'nosources-source-map' : 'cheap-module-eval-source-map',
  module: {
    rules: [
      // CSS required in JS/TS files should use the style-loader that auto-injects it into the website
      // only when the issuer is a .js/.ts file, so the loaders are not applied inside html templates
      {
        test: /\.css$/i,
        issuer: [{ not: [{ test: /\.html$/i }] }],
        use: extractCss ? [{
          loader: MiniCssExtractPlugin.loader
        }, ...cssRules
        ] : ['style-loader', ...cssRules]
      },
      {
        test: /\.css$/i,
        issuer: [{ test: /\.html$/i }],
        // CSS required in templates cannot be extracted safely
        // because Aurelia would try to require it again in runtime
        use: cssRules
      },
      {
        test: /\.scss$/,
        use: extractCss ? [{
          loader: MiniCssExtractPlugin.loader
        }, ...cssRules, ...sassRules
        ] : ['style-loader', ...cssRules, ...sassRules],
        issuer: /\.[tj]s$/i
      },
      {
        test: /\.scss$/,
        use: [...cssRules, ...sassRules],
        issuer: /\.html?$/i
      },
      { test: /\.html$/i, loader: 'html-loader' },
      { test: /\.ts$/, loader: "ts-loader" },
      // embed small images and fonts as Data Urls and larger ones as files:
      { test: /\.(png|gif|jpg|cur)$/i, loader: 'url-loader', options: { limit: 8192 } },
      { test: /\.woff2(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff2' } },
      { test: /\.woff(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } },
      // load these fonts normally, as files:
      { test: /\.(ttf|eot|svg|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'file-loader' },
      {
        test: /environment\.json$/i, use: [
          { loader: "app-settings-loader", options: { env: production ? 'production' : 'development' } },
        ]
      },
      ...when(tests, {
        test: /\.[jt]s$/i, loader: 'istanbul-instrumenter-loader',
        include: srcDir, exclude: [/\.(spec|test)\.[jt]s$/i],
        enforce: 'post', options: { esModules: true },
      })
    ]
  },
  plugins: [
    ...when(!tests, new DuplicatePackageCheckerPlugin()),
    new AureliaPlugin(),
//    new ProvidePlugin({
      //   'jQuery': 'jquery',
      //   '$': 'jquery',
      //   'window.jQuery': 'jquery',
      //   'window.$': 'jquery',
      //   'popper': 'popper.js' 
    //}),
    new ModuleDependenciesPlugin({
      'aurelia-testing': ['./compile-spy', './view-spy'],
      'aurelia-auth': [ './auth-filter' ]
    }),
    new HtmlWebpackPlugin({
      template: 'index.ejs',
      metadata: {
        // available in index.ejs //
        title, baseUrl
      }
    }),
    // ref: https://webpack.js.org/plugins/mini-css-extract-plugin/
    ...when(extractCss, new MiniCssExtractPlugin({ // updated to match the naming conventions for the js files
      filename: production ? 'css/[name].[contenthash].bundle.css' : 'css/[name].[hash].bundle.css',
      chunkFilename: production ? 'css/[name].[contenthash].chunk.css' : 'css/[name].[hash].chunk.css'
    })),
    ...when(!tests, new CopyWebpackPlugin([
      { from: 'static', to: outDir, ignore: ['.*'] }])), // ignore dot (hidden) files
    ...when(analyze, new BundleAnalyzerPlugin()),
    /**
     * Note that the usage of following plugin cleans the webpack output directory before build.
     * In case you want to generate any file in the output path as a part of pre-build step, this plugin will likely
     * remove those before the webpack build. In that case consider disabling the plugin, and instead use something like
     * `del` (https://www.npmjs.com/package/del), or `rimraf` (https://www.npmjs.com/package/rimraf).
     */
    new CleanWebpackPlugin()
  ]
});

пакет. json

{
  "name": "aurelia-app",
  "description": "An Aurelia client application.",
  "version": "0.1.0",
  "repository": {
    "type": "???",
    "url": "???"
  },
  "license": "MIT",
  "dependencies": {
    "aurelia-animator-css": "^1.0.4",
    "aurelia-auth": "^3.0.5",
    "aurelia-bootstrapper": "^2.3.3",
    "aurelia-fetch-client": "^1.8.2",
    "font-awesome": "^4.7.0",
    "oidc-client": "^1.10.1"
  },
  "devDependencies": {
    "aurelia-cli": "^1.3.0",
    "aurelia-testing": "^1.0.0",
    "gulp": "^4.0.0",
    "minimatch": "^3.0.4",
    "through2": "^3.0.1",
    "vinyl-fs": "^3.0.3",
    "promise-polyfill": "^8.1.3",
    "ts-loader": "^6.2.1",
    "ts-node": "^8.6.2",
    "@types/node": "^13.7.6",
    "@types/lodash": "^4.14.149",
    "@types/webpack": "^4.41.6",
    "typescript": "^3.8.2",
    "html-webpack-plugin": "^3.2.0",
    "copy-webpack-plugin": "^5.1.1",
    "mini-css-extract-plugin": "^0.9.0",
    "aurelia-webpack-plugin": "^4.0.0",
    "duplicate-package-checker-webpack-plugin": "^3.0.0",
    "clean-webpack-plugin": "^3.0.0",
    "webpack": "^4.41.6",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.10.3",
    "expose-loader": "^0.7.5",
    "style-loader": "^1.1.3",
    "url-loader": "^3.0.0",
    "css-loader": "^3.4.2",
    "file-loader": "^5.1.0",
    "app-settings-loader": "^1.0.3",
    "json-loader": "^0.5.7",
    "html-loader": "^0.5.5",
    "istanbul-instrumenter-loader": "^3.0.1",
    "webpack-bundle-analyzer": "^3.6.0",
    "tree-kill": "^1.2.1",
    "jest": "^25.1.0",
    "jest-cli": "^25.1.0",
    "jest-transform-stub": "^2.0.0",
    "aurelia-loader-nodejs": "^1.1.0",
    "aurelia-pal-nodejs": "^2.0.0",
    "ts-jest": "^25.2.1",
    "sass-loader": "^8.0.2",
    "node-sass": "^4.13.1",
    "@types/jest": "^25.1.3"
  },
  "scripts": {
    "build": "webpack --env.production --extractCss",
    "start": "webpack-dev-server --extractCss",
    "build:dev": "webpack --extractCss",
    "analyze": "webpack --env.production --analyze",
    "test": "au test"
  },
  "engines": {
    "node": ">=8.9.0"
  },
  "jest": {
    "moduleNameMapper": {
      "^aurelia-binding$": "<rootDir>/node_modules/aurelia-binding"
    },
    "modulePaths": [
      "<rootDir>/src",
      "<rootDir>/node_modules"
    ],
    "moduleFileExtensions": [
      "ts",
      "js",
      "json"
    ],
    "transform": {
      "^.+\\.(css|less|sass|scss|styl|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "jest-transform-stub",
      "^.+\\.ts$": "ts-jest"
    },
    "testRegex": "\\.spec\\.(ts|js)$",
    "setupFiles": [
      "<rootDir>/test/jest-pretest.ts"
    ],
    "testEnvironment": "node",
    "collectCoverage": true,
    "collectCoverageFrom": [
      "src/**/*.{js,ts}",
      "!**/*.spec.{js,ts}",
      "!**/node_modules/**",
      "!**/test/**"
    ],
    "coverageDirectory": "<rootDir>/test/coverage-jest",
    "coverageReporters": [
      "json",
      "lcov",
      "text",
      "html"
    ]
  }
}

...