【问题标题】:How to exclude a specific file from my bundle?如何从我的包中排除特定文件?
【发布时间】:2017-12-01 13:43:04
【问题描述】:

我正在使用 webpack 构建我的应用程序(angular2/typescript),我创建了两个文件,一个用于我的代码,一个用于供应商。但我想要第三个文件来分隔我的配置(主要用于 API_ENDPOINT),它直接在我的代码中使用。

如何使用我的配置文件 (config.ts) 使用加载器构建我的应用程序,但将其从生成的 Js 文件中排除?

目前

<!DOCTYPE html> 
<html>
   <head>
      <base href="/configuration/" >
      <title>Gestion de la configuration technique</title>
      <meta charset=UTF-8>
      <meta name=viewport content="width=device-width,initial-scale=1">
      <link rel="shortcut icon" href=./assets/logo.png />
      <link href="vendor.841ccc40b7395ddc1da4.css" rel="stylesheet">
      <link href="app.841ccc40b7395ddc1da4.css" rel="stylesheet">
   </head>
   <body>
      <sg-conf>loading ...</sg-conf>
      <script type="text/javascript" src="vendor.841ccc40b7395ddc1da4.js"></script>
      <script type="text/javascript" src="app.841ccc40b7395ddc1da4.js"></script>
   </body>
</html>

预期

<!DOCTYPE html> 
<html>
   <head>
      <base href="/configuration/" >
      <title>Gestion de la configuration technique</title>
      <meta charset=UTF-8>
      <meta name=viewport content="width=device-width,initial-scale=1">
      <link rel="shortcut icon" href=./assets/logo.png />
      <link href="vendor.841ccc40b7395ddc1da4.css" rel="stylesheet">
      <link href="app.841ccc40b7395ddc1da4.css" rel="stylesheet">
   </head>
   <body>
      <sg-conf>loading ...</sg-conf>
      <script type="text/javascript" src="vendor.841ccc40b7395ddc1da4.js"></script>
      <script type="text/javascript" src="app.841ccc40b7395ddc1da4.js"></script>
      <script type="text/javascript" src="config.js"></script>
   </body>
</html>

我想从 app.js 中排除的文件 src/config.ts

export class Config {
   static apiUrl = (process.env.ENV === "prod" ?  "xxxxxxx" : "http://localhost:8080/");
   static token = (process.env.ENV === "prod" ? "aaaaaa" : "bbbbb");
}

我合并了两个 webpack 配置文件,first

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var helpers = require('./helpers');
var path = require('path');

module.exports = {
  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'app': './src/main.ts',
    'config' : './src/config.ts'
  },
  resolve: {
    extensions: ['', '.js', '.ts']
  },

  module: {
    loaders: [
      {
        test: /\.ts$/,
        loaders: [/*'console',*/  'awesome-typescript-loader', 'angular2-template-loader']
      },
      {
        test: /\.html$/,
        loader: 'html'
      },
      { 
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, 
        loader: "url-loader?limit=10000&mimetype=application/font-woff"
      },
      { 
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
         loader: "file-loader"
      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
        loader: 'file?name=assets/[name].[hash].[ext]'
      },
      {
        test: /\.css$/,
        exclude: helpers.root('src', 'app'),
        loader: ExtractTextPlugin.extract('style', 'css?sourceMap')
      },
      {
        test: /\.css$/,
        include: helpers.root('src', 'app'),
        loader: 'raw'
      }
    ]
  },

  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: ['app', 'vendor', 'polyfills', 'config']
    }),
    new HtmlWebpackPlugin({
      template: 'src/index.html'
    }),
    new CopyWebpackPlugin([
      { from: 'src/assets', to: 'assets' }
    ]),
  ],

  tslint: {
    "configuration" : {
      "extends": "tslint:recommended",
      "rulesDirectory": [
        "node_modules/codelyzer"
      ],
      "rules":{
        "directive-selector-name": [true, "camelCase"],
        "component-selector-name": [true, "kebab-case"],
        "directive-selector-type": [true, "attribute"],
        "component-selector-type": [true, "element"],
        "directive-selector-prefix": [true, "sg"],
        "component-selector-prefix": [true, "sg"],
        "use-input-property-decorator": true,
        "use-output-property-decorator": true,
        "use-host-property-decorator": true,
        "no-attribute-parameter-decorator": true,
        "no-input-rename": true,
        "no-output-rename": true,
        "no-forward-ref": true,
        "use-life-cycle-interface": true,
        "use-pipe-transform-interface": true,
        "pipe-naming": [true, "camelCase", "sg"],
        "component-class-suffix": true,
        "directive-class-suffix": true,
        "import-destructuring-spacing": true,
        "templates-use-public": true,
        "no-access-missing-member": true,
        "invoke-injectable": true
      }
    },
    emitErrors: true,
    failOnHint: true,
    fileOutput: { 
      ext: "xml", 
      clean: true, 
      header: "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<checkstyle version=\"5.7\">",
      footer: "</checkstyle>"
    }
  }
};

第二:

var webpack = require('webpack');
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var WebpackBaseHref = require('webpack-base-href');
var helpers = require('./helpers');
var path = require('path');

const ENV = process.env.NODE_ENV = process.env.ENV = 'prod';

module.exports = [ webpackMerge(commonConfig, {
  devtool: 'source-map',

  output: {
    path: helpers.root('dist'),
    publicPath: '',
    filename: '[name].[hash].js',
    chunkFilename: '[id].[hash].chunk.js'
  },

  htmlLoader: {
    minimize: false // workaround for ng2
  },

  plugins: [
    new webpack.NoErrorsPlugin(),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({ // https://github.com/angular/angular/issues/10618
      mangle: {
        keep_fnames: true
      }
    }),
    new ExtractTextPlugin('[name].[hash].css'),
    new webpack.DefinePlugin({
      'process.env': {
        'ENV': (ENV && JSON.stringify(ENV)) || 'prod'
      }
    }),
    new WebpackBaseHref.WebpackBaseHref({
      baseHref: '/configuration/'
    })
  ]
})];

【问题讨论】:

    标签: angular typescript webpack


    【解决方案1】:

    你能告诉我你的 webpack 配置吗?

    因为你想要三个输出文件(内部脚本、供应商脚本和配置),你必须在 webpack 配置文件中定义:

    • 入口部分的三个入口点(入口:[这里精确我们的入口点])
    • 在输出部分使用'filename: "build.[name].js"' 以生成与入口点包含的文件一样多的文件。

    然后您可以使用动态工具将这些文件插入到您的 html 中,因为您的名称将是动态的

    希望对你有帮助

    【讨论】:

    • 感谢您的回答,但我已经尝试过但它不起作用:43/362 build modulesModuleNotFoundError: Module not found: Error: a dependency to an entry point is not allowed
    • 你能不能尝试在入口点周围添加 [] 不能像 'config' 一样工作:["./src/config.ts"]
    • 通过这样做你明确告诉 webpack 为这个配置文件生成一个新的包
    • 我没有更多错误,但 config.xxxx.js 文件为空,我的 API_ENDPOINT 在 app.xxx.js 中
    • 我做了一个简单的例子,它正确地生成了我要求的包
    【解决方案2】:

    我做了一个简单的例子,它正确地生成了我要求的包

    webpack.config.js

    const path = require('path');
    
    module.exports = {
        context: path.join(__dirname),
        entry: {
            'index': path.join(__dirname, 'src/index.js'),
            'config': path.join(__dirname, 'src/config.js')
        },
        output: {
            path: path.join(__dirname, 'public'),
            filename: '[name].bundle.js'
        },
        module: {
            loaders: [
                {
                    test: /(\.js)|(\.jsx)$/,
                    loader: 'babel-loader',
                    query: {
                        presets: ['react', 'es2015', 'stage-0']
                    }
                },
            ]
        },
        resolve: {
            extensions: ['.js', '.jsx']
        }
    };
    

    在公共目录中输出

    • config.bundle.js
    • index.bundle.js

    两者都有预期的内容

    如果这没有帮助,您可以将您的 config.ts 发送给我吗 如果我有时间,我在 es6 中做的精度很低,我会在 typescript 中做,看看它是否可以链接到那个,但我对此表示怀疑

    【讨论】:

    • 我在第一篇文章中添加了我的 config.ts。我认为问题出在打字稿上,因为我的应用程序中的代码需要 config.ts 来反编译代码。或者也许我的类 Config 没有作为模块公开?
    • 抱歉我没看到!好的,我会尝试设置它并回复你。但是如果你在 webpack 中有正确的 typescript 加载器,它就必须工作。转译和生成包是不同的步骤。
    • 你是对的,编译和生成包是不同的步骤。我认为问题是由于我使用了 webpack 插件 CommonsChunkPlugin。如果我删除它或者我只留下名称:['config','vendor','polyfills'] 而不是名称:['config','app','vendor','polyfills'],输出配置。 js 文件似乎正确。
    • 它的工作,但我有一个最后的请求。我想在输出文件名中添加哈希,但不是为 config.js。在我的 webpack 配置文件中,我使用“文件名:'[name].[hash].js'”,我该如何添加条件? => "文件名" : (([name] === 'config') ? '[name].js' : '[name].[hash].js')
    • 如果 CommonsChunkPlugin 工作正常,你可以从你的包中删除 config.ts 并在 CommonsChunkPlugin 中使用它以插入到你的 html 中,这将被你的包使用。就像那个 config.ts 不会有任何哈希码,而你的所有入口点都会有
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 2012-07-23
    相关资源
    最近更新 更多