【问题标题】:Webpack build or TypeScript is creating JS files right in my SRCWebpack 构建或 TypeScript 正在我的 SRC 中创建 JS 文件
【发布时间】:2020-12-04 22:38:19
【问题描述】:

我不明白这是怎么回事。这看起来不正常吧?在我构建后,我会为每个.tsx.ts 文件生成一个.js 文件,但这不应该在我的源代码中。我应该只在我的构建中看到 .js 文件。

我的脚本

"start": "PORT=3000 nodemon --trace-warnings --experimental-json-modules --no-warnings dist/server/server.js",
"build": "NODE_ENV=production yarn lint && yarn copyData && yarn compile-server && yarn start & webpack -p --env=prod --watch",
"dev": "NODE_ENV=development yarn lint && yarn copyData && yarn compile-server && yarn start & webpack-dev-server -d --watch",

./webpack.config.js

const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const TerserJSPlugin = require('terser-webpack-plugin');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');

const isProduction = process.env.NODE_ENV === 'production';

const html = () =>
    new HtmlWebPackPlugin({
        template: path.resolve(__dirname, 'src/client', 'index.html'),
        filename: 'index.html',
        hash: true,
    });

const copyAllOtherDistFiles = () =>
    new CopyPlugin({
        patterns: [
            { from: 'src/client/assets', to: 'lib/assets' },
            { from: 'package.json', to: './' },
            { from: 'ext/ink-3.1.10/js/ink-all.min.js', to: 'lib/js' },
            { from: 'ext/ink-3.1.10/js/autoload.min.js', to: 'lib/js' },
            { from: 'ext/ink-3.1.10/css/ink-flex.min.css', to: 'lib/css' },
            { from: 'ext/js/jquery-2.2.3.min.js', to: 'lib/js' },
            { from: 'ext/ink-3.1.10/fonts', to: 'lib/css/fonts' },
            { from: 'feed.xml', to: './' },
        ],
    });

module.exports = {
    entry: './src/client/index.tsx',
    output: {
        filename: 'scripts/app.[hash].bundle.js',
        publicPath: '/',
        path: path.resolve(__dirname, 'dist'),
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.js'],
    },
    devtool: 'source-map',
    devServer: {
        open: true,
        writeToDisk: false,
        publicPath: '/',
        compress: true,
        historyApiFallback: {
            index: '/',
        },
        stats: 'errors-only',
        proxy: {
            '/api': {
                target: 'http://localhost:3000',
                secure: false,
                changeOrigin: true,
                logLevel: 'debug',
            },
        },
    },
    optimization: {
        splitChunks: {
            cacheGroups: {
                styles: {
                    name: 'styles',
                    test: /\.css$/,
                    chunks: 'all',
                    enforce: true,
                },
            },
        },
    },
    module: {
        rules: [
            {
                test: /\.(js)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                },
            },
            {
                test: /\.(tsx|ts)?$/,
                use: 'ts-loader',
                exclude: /node_modules/,
            },
            {
                test: /\.html$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: 'html-loader',
                    },
                ],
            },
            {
                test: /\.less$/,
                exclude: /node_modules/,
                use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader'],
            },
            {
                test: /\.css$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            publicPath: '../../',
                            outputPath: 'lib/css',
                        },
                    },
                    'css-loader',
                ],
            },
            {
                test: /\.(woff(2)?|ttf|eot|otf|svg)?$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].[ext]',
                            publicPath: '/lib/css/fonts', // <--resolve the path in css files
                            outputPath: 'lib/css/fonts', // <-- path to place font files
                        },
                    },
                ],
            },
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: ['url-loader'],
            },
        ],
    },
    plugins: isProduction
        ? [
                new CleanWebpackPlugin(),
                copyAllOtherDistFiles(),
                new MiniCssExtractPlugin({
                    filename: 'lib/css/[name].[hash].css',
                }),
                html(),
          ]
        : [
                copyAllOtherDistFiles(),
                new MiniCssExtractPlugin({
                    filename: 'lib/css/[name].[hash].css',
                }),
                html(),
          ],
};

./tsconfig.json

{
  "compilerOptions": {
    "target": "ES2015",                     /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "es2020",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "lib": ["es5", "es6", "dom"],                      /* Specify library files to be included in the compilation. */
    "moduleResolution": "node",
    "allowJs": false,                     /* Allow javascript files to be compiled. */
    "jsx": "react",
    "noImplicitAny": false,
    "sourceMap": false,                   /* Generates corresponding '.map' file. */
    "rootDir": "./",                     /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    "removeComments": true,              /* Do not emit comments to output. */
    "strict": true,                      /* Enable all strict type-checking options. */
    "noUnusedLocals": true,                /* Report errors on unused locals. */
    "noUnusedParameters": true,            /* Report errors on unused parameters. */
    "typeRoots": [
      "node_modules/@types"
    ],                      /* List of folders to include type definitions from. */
    "esModuleInterop": true,
     "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    "resolveJsonModule": true,
    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true,
    },
    "include": [
        "src"
    ],
    "exclude": [
        "/node_modules",
        "/src/server",
        "/src/client/js/ink-config.js",
        "**/test",
        "dist"
  ]
}

./src/server/tsconfig.json

{
    "extends": "../../tsconfig",
    "compilerOptions": {
    "outDir": "../../dist/server", /* Redirect output structure to the directory. */
    "rootDir": "."                 /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    },
    "module": "commonjs",
    "include": ["./*.ts"],
    "resolveJsonModule": true
}

【问题讨论】:

  • 其实我不明白为什么我需要outDir 如果 webpack 正在为我构建几乎所有东西并捆绑到它自己指定的输出目录。我不是要求 tsconfig 为我的构建输出所有 ts 文件。 webpack 正在打包并使用 typescript 来处理我的包。我需要 webpack 创建的捆绑包,而不是 webpack 捆绑的所有内容的 js 文件,对吗?也许我在这里真的很困惑。我只有一个子 tsconfig 为我的服务器输出一些东西,但其余部分由 webpack 为客户端捆绑
  • 如果在"compilerOptions" 下添加"outDir": "dist" 会怎样?
  • 并排发射是默认设置。这有很多很好的理由,包括它使人们更容易上手。如果你只想编译 webpack,使用 noEmit 选项
  • 如果我添加 "outDir": "dist" 那么它只会将所有这些 .js 文件输出到 dist 而不是 src 但我不希望这样,因为我的 webpack 包在构建过程中已经包含了所有这些 js 文件跨度>

标签: javascript reactjs angular typescript webpack


【解决方案1】:

我的决定是:

  1. 由于我在 webpack 中使用 ts-loader,它希望 tsconfig 发出 .js 文件,然后 webpack 可以通过加载器处理这些文件
  2. 由于 #1,我不能只在 tsconfig 中将 emit 设置为 false,因为 webpack 依赖于处理输出的 js 文件,以便最终可以从它们中创建一个包
  3. 因为我不希望 tsconfig 生成的那些中间 js 文件弄乱我的 src 文件夹,所以我将我的 tsconfig 输出目录设置为 build
  4. webpack 的输出目录是dist,所以我最终只会生成生产版本

这样,中间的TS js文件输出到build,被webpack拾取,处理成bundle,bundle输出到dist

./tsconfig.json

"compilerOptions": {
   "outDir": "./build",
}

./webpack.config.js

entry: './src/client/index.tsx',
output: {
  filename: 'scripts/app.[hash].bundle.js',
  publicPath: '/',
  path: path.resolve(__dirname, 'dist'),
},
resolve: {
  extensions: ['.ts', '.tsx', '.js'],
  },
{
  test: /\.(tsx|ts)?$/,
  use: 'ts-loader',
  exclude: /node_modules/,
},

这让一切都保持清洁。

【讨论】:

    猜你喜欢
    • 2017-04-05
    • 2017-12-30
    • 2022-01-01
    • 2018-01-30
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    相关资源
    最近更新 更多